babylon.max.js 2.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494
  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 false;
  4223. }
  4224. this.push(value);
  4225. return true;
  4226. };
  4227. SmartArray.prototype.sort = function (compareFn) {
  4228. this.data.sort(compareFn);
  4229. };
  4230. SmartArray.prototype.reset = function () {
  4231. this.length = 0;
  4232. this._duplicateId++;
  4233. };
  4234. SmartArray.prototype.concat = function (array) {
  4235. if (array.length === 0) {
  4236. return;
  4237. }
  4238. if (this.length + array.length > this.data.length) {
  4239. this.data.length = (this.length + array.length) * 2;
  4240. }
  4241. for (var index = 0; index < array.length; index++) {
  4242. this.data[this.length++] = (array.data || array)[index];
  4243. }
  4244. };
  4245. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4246. if (array.length === 0) {
  4247. return;
  4248. }
  4249. if (this.length + array.length > this.data.length) {
  4250. this.data.length = (this.length + array.length) * 2;
  4251. }
  4252. for (var index = 0; index < array.length; index++) {
  4253. var item = (array.data || array)[index];
  4254. this.pushNoDuplicate(item);
  4255. }
  4256. };
  4257. SmartArray.prototype.indexOf = function (value) {
  4258. var position = this.data.indexOf(value);
  4259. if (position >= this.length) {
  4260. return -1;
  4261. }
  4262. return position;
  4263. };
  4264. // Statics
  4265. SmartArray._GlobalId = 0;
  4266. return SmartArray;
  4267. })();
  4268. BABYLON.SmartArray = SmartArray;
  4269. })(BABYLON || (BABYLON = {}));
  4270. var BABYLON;
  4271. (function (BABYLON) {
  4272. /**
  4273. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4274. * The underlying implementation relies on an associative array to ensure the best performances.
  4275. * The value can be anything including 'null' but except 'undefined'
  4276. */
  4277. var StringDictionary = (function () {
  4278. function StringDictionary() {
  4279. this._count = 0;
  4280. this._data = {};
  4281. }
  4282. /**
  4283. * Get a value based from its key
  4284. * @param key the given key to get the matching value from
  4285. * @return the value if found, otherwise undefined is returned
  4286. */
  4287. StringDictionary.prototype.get = function (key) {
  4288. var val = this._data[key];
  4289. if (val !== undefined) {
  4290. return val;
  4291. }
  4292. return undefined;
  4293. };
  4294. /**
  4295. * Get a value from its key or add it if it doesn't exist.
  4296. * This method will ensure you that a given key/data will be present in the dictionary.
  4297. * @param key the given key to get the matching value from
  4298. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4299. * The factory will only be invoked if there's no data for the given key.
  4300. * @return the value corresponding to the key.
  4301. */
  4302. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4303. var val = this.get(key);
  4304. if (val !== undefined) {
  4305. return val;
  4306. }
  4307. val = factory(key);
  4308. if (val) {
  4309. this.add(key, val);
  4310. }
  4311. return val;
  4312. };
  4313. /**
  4314. * Get a value from its key if present in the dictionary otherwise add it
  4315. * @param key the key to get the value from
  4316. * @param val if there's no such key/value pair in the dictionary add it with this value
  4317. * @return the value corresponding to the key
  4318. */
  4319. StringDictionary.prototype.getOrAdd = function (key, val) {
  4320. var curVal = this.get(key);
  4321. if (curVal !== undefined) {
  4322. return curVal;
  4323. }
  4324. this.add(key, val);
  4325. return val;
  4326. };
  4327. /**
  4328. * Check if there's a given key in the dictionary
  4329. * @param key the key to check for
  4330. * @return true if the key is present, false otherwise
  4331. */
  4332. StringDictionary.prototype.contains = function (key) {
  4333. return this._data[key] !== undefined;
  4334. };
  4335. /**
  4336. * Add a new key and its corresponding value
  4337. * @param key the key to add
  4338. * @param value the value corresponding to the key
  4339. * @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
  4340. */
  4341. StringDictionary.prototype.add = function (key, value) {
  4342. if (this._data[key] !== undefined) {
  4343. return false;
  4344. }
  4345. this._data[key] = value;
  4346. ++this._count;
  4347. return true;
  4348. };
  4349. StringDictionary.prototype.set = function (key, value) {
  4350. if (this._data[key] === undefined) {
  4351. return false;
  4352. }
  4353. this._data[key] = value;
  4354. return true;
  4355. };
  4356. /**
  4357. * Remove a key/value from the dictionary.
  4358. * @param key the key to remove
  4359. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4360. */
  4361. StringDictionary.prototype.remove = function (key) {
  4362. if (this.contains(key)) {
  4363. delete this._data[key];
  4364. --this._count;
  4365. return true;
  4366. }
  4367. return false;
  4368. };
  4369. /**
  4370. * Clear the whole content of the dictionary
  4371. */
  4372. StringDictionary.prototype.clear = function () {
  4373. this._data = {};
  4374. this._count = 0;
  4375. };
  4376. Object.defineProperty(StringDictionary.prototype, "count", {
  4377. get: function () {
  4378. return this._count;
  4379. },
  4380. enumerable: true,
  4381. configurable: true
  4382. });
  4383. /**
  4384. * Execute a callback on each key/val of the dictionary.
  4385. * Note that you can remove any element in this dictionary in the callback implementation
  4386. * @param callback the callback to execute on a given key/value pair
  4387. */
  4388. StringDictionary.prototype.forEach = function (callback) {
  4389. for (var cur in this._data) {
  4390. var val = this._data[cur];
  4391. callback(cur, val);
  4392. }
  4393. };
  4394. /**
  4395. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4396. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4397. * Note that you can remove any element in this dictionary in the callback implementation
  4398. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4399. */
  4400. StringDictionary.prototype.first = function (callback) {
  4401. for (var cur in this._data) {
  4402. var val = this._data[cur];
  4403. var res = callback(cur, val);
  4404. if (res) {
  4405. return res;
  4406. }
  4407. }
  4408. return null;
  4409. };
  4410. return StringDictionary;
  4411. })();
  4412. BABYLON.StringDictionary = StringDictionary;
  4413. })(BABYLON || (BABYLON = {}));
  4414. var BABYLON;
  4415. (function (BABYLON) {
  4416. // Screenshots
  4417. var screenshotCanvas;
  4418. var cloneValue = function (source, destinationObject) {
  4419. if (!source)
  4420. return null;
  4421. if (source instanceof BABYLON.Mesh) {
  4422. return null;
  4423. }
  4424. if (source instanceof BABYLON.SubMesh) {
  4425. return source.clone(destinationObject);
  4426. }
  4427. else if (source.clone) {
  4428. return source.clone();
  4429. }
  4430. return null;
  4431. };
  4432. var Tools = (function () {
  4433. function Tools() {
  4434. }
  4435. Tools.Instantiate = function (className) {
  4436. var arr = className.split(".");
  4437. var fn = (window || this);
  4438. for (var i = 0, len = arr.length; i < len; i++) {
  4439. fn = fn[arr[i]];
  4440. }
  4441. if (typeof fn !== "function") {
  4442. return null;
  4443. }
  4444. return fn;
  4445. };
  4446. Tools.SetImmediate = function (action) {
  4447. if (window.setImmediate) {
  4448. window.setImmediate(action);
  4449. }
  4450. else {
  4451. setTimeout(action, 1);
  4452. }
  4453. };
  4454. Tools.IsExponentOfTwo = function (value) {
  4455. var count = 1;
  4456. do {
  4457. count *= 2;
  4458. } while (count < value);
  4459. return count === value;
  4460. };
  4461. Tools.GetExponentOfTwo = function (value, max) {
  4462. var count = 1;
  4463. do {
  4464. count *= 2;
  4465. } while (count < value);
  4466. if (count > max)
  4467. count = max;
  4468. return count;
  4469. };
  4470. Tools.GetFilename = function (path) {
  4471. var index = path.lastIndexOf("/");
  4472. if (index < 0)
  4473. return path;
  4474. return path.substring(index + 1);
  4475. };
  4476. Tools.GetDOMTextContent = function (element) {
  4477. var result = "";
  4478. var child = element.firstChild;
  4479. while (child) {
  4480. if (child.nodeType === 3) {
  4481. result += child.textContent;
  4482. }
  4483. child = child.nextSibling;
  4484. }
  4485. return result;
  4486. };
  4487. Tools.ToDegrees = function (angle) {
  4488. return angle * 180 / Math.PI;
  4489. };
  4490. Tools.ToRadians = function (angle) {
  4491. return angle * Math.PI / 180;
  4492. };
  4493. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4494. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4495. var output = "";
  4496. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4497. var i = 0;
  4498. var bytes = new Uint8Array(buffer);
  4499. while (i < bytes.length) {
  4500. chr1 = bytes[i++];
  4501. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4502. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4503. enc1 = chr1 >> 2;
  4504. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4505. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4506. enc4 = chr3 & 63;
  4507. if (isNaN(chr2)) {
  4508. enc3 = enc4 = 64;
  4509. }
  4510. else if (isNaN(chr3)) {
  4511. enc4 = 64;
  4512. }
  4513. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4514. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4515. }
  4516. return "data:image/png;base64," + output;
  4517. };
  4518. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4519. if (bias === void 0) { bias = null; }
  4520. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4521. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4522. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4523. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4524. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4525. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4526. }
  4527. if (bias) {
  4528. minimum.x -= minimum.x * bias.x + bias.y;
  4529. minimum.y -= minimum.y * bias.x + bias.y;
  4530. minimum.z -= minimum.z * bias.x + bias.y;
  4531. maximum.x += maximum.x * bias.x + bias.y;
  4532. maximum.y += maximum.y * bias.x + bias.y;
  4533. maximum.z += maximum.z * bias.x + bias.y;
  4534. }
  4535. return {
  4536. minimum: minimum,
  4537. maximum: maximum
  4538. };
  4539. };
  4540. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4541. if (bias === void 0) { bias = null; }
  4542. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4543. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4544. if (!stride) {
  4545. stride = 3;
  4546. }
  4547. for (var index = start; index < start + count; index++) {
  4548. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4549. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4550. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4551. }
  4552. if (bias) {
  4553. minimum.x -= minimum.x * bias.x + bias.y;
  4554. minimum.y -= minimum.y * bias.x + bias.y;
  4555. minimum.z -= minimum.z * bias.x + bias.y;
  4556. maximum.x += maximum.x * bias.x + bias.y;
  4557. maximum.y += maximum.y * bias.x + bias.y;
  4558. maximum.z += maximum.z * bias.x + bias.y;
  4559. }
  4560. return {
  4561. minimum: minimum,
  4562. maximum: maximum
  4563. };
  4564. };
  4565. Tools.Vector2ArrayFeeder = function (array) {
  4566. return function (index) {
  4567. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4568. var length = isFloatArray ? array.length / 2 : array.length;
  4569. if (index >= length) {
  4570. return null;
  4571. }
  4572. if (isFloatArray) {
  4573. var fa = array;
  4574. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4575. }
  4576. var a = array;
  4577. return a[index];
  4578. };
  4579. };
  4580. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4581. if (bias === void 0) { bias = null; }
  4582. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4583. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4584. var i = 0;
  4585. var cur = feeder(i++);
  4586. while (cur) {
  4587. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4588. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4589. cur = feeder(i++);
  4590. }
  4591. if (bias) {
  4592. minimum.x -= minimum.x * bias.x + bias.y;
  4593. minimum.y -= minimum.y * bias.x + bias.y;
  4594. maximum.x += maximum.x * bias.x + bias.y;
  4595. maximum.y += maximum.y * bias.x + bias.y;
  4596. }
  4597. return {
  4598. minimum: minimum,
  4599. maximum: maximum
  4600. };
  4601. };
  4602. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4603. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4604. return undefined;
  4605. return Array.isArray(obj) ? obj : [obj];
  4606. };
  4607. // Misc.
  4608. Tools.GetPointerPrefix = function () {
  4609. var eventPrefix = "pointer";
  4610. // Check if pointer events are supported
  4611. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4612. eventPrefix = "mouse";
  4613. }
  4614. return eventPrefix;
  4615. };
  4616. Tools.QueueNewFrame = function (func) {
  4617. if (window.requestAnimationFrame)
  4618. window.requestAnimationFrame(func);
  4619. else if (window.msRequestAnimationFrame)
  4620. window.msRequestAnimationFrame(func);
  4621. else if (window.webkitRequestAnimationFrame)
  4622. window.webkitRequestAnimationFrame(func);
  4623. else if (window.mozRequestAnimationFrame)
  4624. window.mozRequestAnimationFrame(func);
  4625. else if (window.oRequestAnimationFrame)
  4626. window.oRequestAnimationFrame(func);
  4627. else {
  4628. window.setTimeout(func, 16);
  4629. }
  4630. };
  4631. Tools.RequestFullscreen = function (element, options) {
  4632. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4633. if (!requestFunction)
  4634. return;
  4635. requestFunction.call(element, options);
  4636. };
  4637. Tools.ExitFullscreen = function () {
  4638. if (document.exitFullscreen) {
  4639. document.exitFullscreen();
  4640. }
  4641. else if (document.mozCancelFullScreen) {
  4642. document.mozCancelFullScreen();
  4643. }
  4644. else if (document.webkitCancelFullScreen) {
  4645. document.webkitCancelFullScreen();
  4646. }
  4647. else if (document.msCancelFullScreen) {
  4648. document.msCancelFullScreen();
  4649. }
  4650. };
  4651. // External files
  4652. Tools.CleanUrl = function (url) {
  4653. url = url.replace(/#/mg, "%23");
  4654. return url;
  4655. };
  4656. Tools.LoadImage = function (url, onload, onerror, database) {
  4657. if (url instanceof ArrayBuffer) {
  4658. url = Tools.EncodeArrayBufferTobase64(url);
  4659. }
  4660. url = Tools.CleanUrl(url);
  4661. var img = new Image();
  4662. if (url.substr(0, 5) !== "data:") {
  4663. if (Tools.CorsBehavior) {
  4664. switch (typeof (Tools.CorsBehavior)) {
  4665. case "function":
  4666. var result = Tools.CorsBehavior(url);
  4667. if (result) {
  4668. img.crossOrigin = result;
  4669. }
  4670. break;
  4671. case "string":
  4672. default:
  4673. img.crossOrigin = Tools.CorsBehavior;
  4674. break;
  4675. }
  4676. }
  4677. }
  4678. img.onload = function () {
  4679. onload(img);
  4680. };
  4681. img.onerror = function (err) {
  4682. Tools.Error("Error while trying to load texture: " + url);
  4683. if (Tools.UseFallbackTexture) {
  4684. 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";
  4685. onload(img);
  4686. }
  4687. else {
  4688. onerror();
  4689. }
  4690. };
  4691. var noIndexedDB = function () {
  4692. img.src = url;
  4693. };
  4694. var loadFromIndexedDB = function () {
  4695. database.loadImageFromDB(url, img);
  4696. };
  4697. //ANY database to do!
  4698. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4699. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4700. }
  4701. else {
  4702. if (url.indexOf("file:") === -1) {
  4703. noIndexedDB();
  4704. }
  4705. else {
  4706. try {
  4707. var textureName = url.substring(5).toLowerCase();
  4708. var blobURL;
  4709. try {
  4710. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4711. }
  4712. catch (ex) {
  4713. // Chrome doesn't support oneTimeOnly parameter
  4714. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4715. }
  4716. img.src = blobURL;
  4717. }
  4718. catch (e) {
  4719. img.src = null;
  4720. }
  4721. }
  4722. }
  4723. return img;
  4724. };
  4725. //ANY
  4726. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4727. url = Tools.CleanUrl(url);
  4728. var noIndexedDB = function () {
  4729. var request = new XMLHttpRequest();
  4730. var loadUrl = Tools.BaseUrl + url;
  4731. request.open('GET', loadUrl, true);
  4732. if (useArrayBuffer) {
  4733. request.responseType = "arraybuffer";
  4734. }
  4735. request.onprogress = progressCallBack;
  4736. request.onreadystatechange = function () {
  4737. if (request.readyState === 4) {
  4738. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4739. callback(!useArrayBuffer ? request.responseText : request.response);
  4740. }
  4741. else {
  4742. if (onError) {
  4743. onError();
  4744. }
  4745. else {
  4746. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4747. }
  4748. }
  4749. }
  4750. };
  4751. request.send(null);
  4752. };
  4753. var loadFromIndexedDB = function () {
  4754. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4755. };
  4756. if (url.indexOf("file:") !== -1) {
  4757. var fileName = url.substring(5).toLowerCase();
  4758. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4759. }
  4760. else {
  4761. // Caching all files
  4762. if (database && database.enableSceneOffline) {
  4763. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4764. }
  4765. else {
  4766. noIndexedDB();
  4767. }
  4768. }
  4769. };
  4770. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4771. var reader = new FileReader();
  4772. reader.onload = function (e) {
  4773. //target doesn't have result from ts 1.3
  4774. callback(e.target['result']);
  4775. };
  4776. reader.onprogress = progressCallback;
  4777. reader.readAsDataURL(fileToLoad);
  4778. };
  4779. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4780. var reader = new FileReader();
  4781. reader.onerror = function (e) {
  4782. Tools.Log("Error while reading file: " + fileToLoad.name);
  4783. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4784. };
  4785. reader.onload = function (e) {
  4786. //target doesn't have result from ts 1.3
  4787. callback(e.target['result']);
  4788. };
  4789. reader.onprogress = progressCallBack;
  4790. if (!useArrayBuffer) {
  4791. // Asynchronous read
  4792. reader.readAsText(fileToLoad);
  4793. }
  4794. else {
  4795. reader.readAsArrayBuffer(fileToLoad);
  4796. }
  4797. };
  4798. //returns a downloadable url to a file content.
  4799. Tools.FileAsURL = function (content) {
  4800. var fileBlob = new Blob([content]);
  4801. var url = window.URL || window.webkitURL;
  4802. var link = url.createObjectURL(fileBlob);
  4803. return link;
  4804. };
  4805. // Misc.
  4806. Tools.Format = function (value, decimals) {
  4807. if (decimals === void 0) { decimals = 2; }
  4808. return value.toFixed(decimals);
  4809. };
  4810. Tools.CheckExtends = function (v, min, max) {
  4811. if (v.x < min.x)
  4812. min.x = v.x;
  4813. if (v.y < min.y)
  4814. min.y = v.y;
  4815. if (v.z < min.z)
  4816. min.z = v.z;
  4817. if (v.x > max.x)
  4818. max.x = v.x;
  4819. if (v.y > max.y)
  4820. max.y = v.y;
  4821. if (v.z > max.z)
  4822. max.z = v.z;
  4823. };
  4824. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4825. for (var prop in source) {
  4826. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4827. continue;
  4828. }
  4829. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4830. continue;
  4831. }
  4832. var sourceValue = source[prop];
  4833. var typeOfSourceValue = typeof sourceValue;
  4834. if (typeOfSourceValue === "function") {
  4835. continue;
  4836. }
  4837. if (typeOfSourceValue === "object") {
  4838. if (sourceValue instanceof Array) {
  4839. destination[prop] = [];
  4840. if (sourceValue.length > 0) {
  4841. if (typeof sourceValue[0] == "object") {
  4842. for (var index = 0; index < sourceValue.length; index++) {
  4843. var clonedValue = cloneValue(sourceValue[index], destination);
  4844. if (destination[prop].indexOf(clonedValue) === -1) {
  4845. destination[prop].push(clonedValue);
  4846. }
  4847. }
  4848. }
  4849. else {
  4850. destination[prop] = sourceValue.slice(0);
  4851. }
  4852. }
  4853. }
  4854. else {
  4855. destination[prop] = cloneValue(sourceValue, destination);
  4856. }
  4857. }
  4858. else {
  4859. destination[prop] = sourceValue;
  4860. }
  4861. }
  4862. };
  4863. Tools.IsEmpty = function (obj) {
  4864. for (var i in obj) {
  4865. return false;
  4866. }
  4867. return true;
  4868. };
  4869. Tools.RegisterTopRootEvents = function (events) {
  4870. for (var index = 0; index < events.length; index++) {
  4871. var event = events[index];
  4872. window.addEventListener(event.name, event.handler, false);
  4873. try {
  4874. if (window.parent) {
  4875. window.parent.addEventListener(event.name, event.handler, false);
  4876. }
  4877. }
  4878. catch (e) {
  4879. }
  4880. }
  4881. };
  4882. Tools.UnregisterTopRootEvents = function (events) {
  4883. for (var index = 0; index < events.length; index++) {
  4884. var event = events[index];
  4885. window.removeEventListener(event.name, event.handler);
  4886. try {
  4887. if (window.parent) {
  4888. window.parent.removeEventListener(event.name, event.handler);
  4889. }
  4890. }
  4891. catch (e) {
  4892. }
  4893. }
  4894. };
  4895. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4896. // Read the contents of the framebuffer
  4897. var numberOfChannelsByLine = width * 4;
  4898. var halfHeight = height / 2;
  4899. //Reading datas from WebGL
  4900. var data = engine.readPixels(0, 0, width, height);
  4901. //To flip image on Y axis.
  4902. for (var i = 0; i < halfHeight; i++) {
  4903. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4904. var currentCell = j + i * numberOfChannelsByLine;
  4905. var targetLine = height - i - 1;
  4906. var targetCell = j + targetLine * numberOfChannelsByLine;
  4907. var temp = data[currentCell];
  4908. data[currentCell] = data[targetCell];
  4909. data[targetCell] = temp;
  4910. }
  4911. }
  4912. // Create a 2D canvas to store the result
  4913. if (!screenshotCanvas) {
  4914. screenshotCanvas = document.createElement('canvas');
  4915. }
  4916. screenshotCanvas.width = width;
  4917. screenshotCanvas.height = height;
  4918. var context = screenshotCanvas.getContext('2d');
  4919. // Copy the pixels to a 2D canvas
  4920. var imageData = context.createImageData(width, height);
  4921. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4922. var castData = imageData.data;
  4923. castData.set(data);
  4924. context.putImageData(imageData, 0, 0);
  4925. var base64Image = screenshotCanvas.toDataURL();
  4926. if (successCallback) {
  4927. successCallback(base64Image);
  4928. }
  4929. else {
  4930. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4931. if (("download" in document.createElement("a"))) {
  4932. var a = window.document.createElement("a");
  4933. a.href = base64Image;
  4934. var date = new Date();
  4935. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4936. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4937. window.document.body.appendChild(a);
  4938. a.addEventListener("click", function () {
  4939. a.parentElement.removeChild(a);
  4940. });
  4941. a.click();
  4942. }
  4943. else {
  4944. var newWindow = window.open("");
  4945. var img = newWindow.document.createElement("img");
  4946. img.src = base64Image;
  4947. newWindow.document.body.appendChild(img);
  4948. }
  4949. }
  4950. };
  4951. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4952. var width;
  4953. var height;
  4954. //If a precision value is specified
  4955. if (size.precision) {
  4956. width = Math.round(engine.getRenderWidth() * size.precision);
  4957. height = Math.round(width / engine.getAspectRatio(camera));
  4958. size = { width: width, height: height };
  4959. }
  4960. else if (size.width && size.height) {
  4961. width = size.width;
  4962. height = size.height;
  4963. }
  4964. else if (size.width && !size.height) {
  4965. width = size.width;
  4966. height = Math.round(width / engine.getAspectRatio(camera));
  4967. size = { width: width, height: height };
  4968. }
  4969. else if (size.height && !size.width) {
  4970. height = size.height;
  4971. width = Math.round(height * engine.getAspectRatio(camera));
  4972. size = { width: width, height: height };
  4973. }
  4974. else if (!isNaN(size)) {
  4975. height = size;
  4976. width = size;
  4977. }
  4978. else {
  4979. Tools.Error("Invalid 'size' parameter !");
  4980. return;
  4981. }
  4982. var scene = camera.getScene();
  4983. var previousCamera = null;
  4984. if (scene.activeCamera !== camera) {
  4985. previousCamera = scene.activeCamera;
  4986. scene.activeCamera = camera;
  4987. }
  4988. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4989. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4990. texture.renderList = scene.meshes;
  4991. texture.onAfterRenderObservable.add(function () {
  4992. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4993. });
  4994. scene.incrementRenderId();
  4995. texture.render(true);
  4996. texture.dispose();
  4997. if (previousCamera) {
  4998. scene.activeCamera = previousCamera;
  4999. }
  5000. camera.getProjectionMatrix(true); // Force cache refresh;
  5001. };
  5002. // XHR response validator for local file scenario
  5003. Tools.ValidateXHRData = function (xhr, dataType) {
  5004. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5005. if (dataType === void 0) { dataType = 7; }
  5006. try {
  5007. if (dataType & 1) {
  5008. if (xhr.responseText && xhr.responseText.length > 0) {
  5009. return true;
  5010. }
  5011. else if (dataType === 1) {
  5012. return false;
  5013. }
  5014. }
  5015. if (dataType & 2) {
  5016. // Check header width and height since there is no "TGA" magic number
  5017. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5018. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5019. return true;
  5020. }
  5021. else if (dataType === 2) {
  5022. return false;
  5023. }
  5024. }
  5025. if (dataType & 4) {
  5026. // Check for the "DDS" magic number
  5027. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5028. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5029. return true;
  5030. }
  5031. else {
  5032. return false;
  5033. }
  5034. }
  5035. }
  5036. catch (e) {
  5037. }
  5038. return false;
  5039. };
  5040. Object.defineProperty(Tools, "NoneLogLevel", {
  5041. get: function () {
  5042. return Tools._NoneLogLevel;
  5043. },
  5044. enumerable: true,
  5045. configurable: true
  5046. });
  5047. Object.defineProperty(Tools, "MessageLogLevel", {
  5048. get: function () {
  5049. return Tools._MessageLogLevel;
  5050. },
  5051. enumerable: true,
  5052. configurable: true
  5053. });
  5054. Object.defineProperty(Tools, "WarningLogLevel", {
  5055. get: function () {
  5056. return Tools._WarningLogLevel;
  5057. },
  5058. enumerable: true,
  5059. configurable: true
  5060. });
  5061. Object.defineProperty(Tools, "ErrorLogLevel", {
  5062. get: function () {
  5063. return Tools._ErrorLogLevel;
  5064. },
  5065. enumerable: true,
  5066. configurable: true
  5067. });
  5068. Object.defineProperty(Tools, "AllLogLevel", {
  5069. get: function () {
  5070. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5071. },
  5072. enumerable: true,
  5073. configurable: true
  5074. });
  5075. Tools._AddLogEntry = function (entry) {
  5076. Tools._LogCache = entry + Tools._LogCache;
  5077. if (Tools.OnNewCacheEntry) {
  5078. Tools.OnNewCacheEntry(entry);
  5079. }
  5080. };
  5081. Tools._FormatMessage = function (message) {
  5082. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5083. var date = new Date();
  5084. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5085. };
  5086. Tools._LogDisabled = function (message) {
  5087. // nothing to do
  5088. };
  5089. Tools._LogEnabled = function (message) {
  5090. var formattedMessage = Tools._FormatMessage(message);
  5091. console.log("BJS - " + formattedMessage);
  5092. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5093. Tools._AddLogEntry(entry);
  5094. };
  5095. Tools._WarnDisabled = function (message) {
  5096. // nothing to do
  5097. };
  5098. Tools._WarnEnabled = function (message) {
  5099. var formattedMessage = Tools._FormatMessage(message);
  5100. console.warn("BJS - " + formattedMessage);
  5101. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5102. Tools._AddLogEntry(entry);
  5103. };
  5104. Tools._ErrorDisabled = function (message) {
  5105. // nothing to do
  5106. };
  5107. Tools._ErrorEnabled = function (message) {
  5108. Tools.errorsCount++;
  5109. var formattedMessage = Tools._FormatMessage(message);
  5110. console.error("BJS - " + formattedMessage);
  5111. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5112. Tools._AddLogEntry(entry);
  5113. };
  5114. Object.defineProperty(Tools, "LogCache", {
  5115. get: function () {
  5116. return Tools._LogCache;
  5117. },
  5118. enumerable: true,
  5119. configurable: true
  5120. });
  5121. Tools.ClearLogCache = function () {
  5122. Tools._LogCache = "";
  5123. Tools.errorsCount = 0;
  5124. };
  5125. Object.defineProperty(Tools, "LogLevels", {
  5126. set: function (level) {
  5127. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5128. Tools.Log = Tools._LogEnabled;
  5129. }
  5130. else {
  5131. Tools.Log = Tools._LogDisabled;
  5132. }
  5133. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5134. Tools.Warn = Tools._WarnEnabled;
  5135. }
  5136. else {
  5137. Tools.Warn = Tools._WarnDisabled;
  5138. }
  5139. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5140. Tools.Error = Tools._ErrorEnabled;
  5141. }
  5142. else {
  5143. Tools.Error = Tools._ErrorDisabled;
  5144. }
  5145. },
  5146. enumerable: true,
  5147. configurable: true
  5148. });
  5149. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5150. get: function () {
  5151. return Tools._PerformanceNoneLogLevel;
  5152. },
  5153. enumerable: true,
  5154. configurable: true
  5155. });
  5156. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5157. get: function () {
  5158. return Tools._PerformanceUserMarkLogLevel;
  5159. },
  5160. enumerable: true,
  5161. configurable: true
  5162. });
  5163. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5164. get: function () {
  5165. return Tools._PerformanceConsoleLogLevel;
  5166. },
  5167. enumerable: true,
  5168. configurable: true
  5169. });
  5170. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5171. set: function (level) {
  5172. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5173. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5174. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5175. return;
  5176. }
  5177. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5178. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5179. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5180. return;
  5181. }
  5182. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5183. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5189. };
  5190. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5191. };
  5192. Tools._StartUserMark = function (counterName, condition) {
  5193. if (condition === void 0) { condition = true; }
  5194. if (!condition || !Tools._performance.mark) {
  5195. return;
  5196. }
  5197. Tools._performance.mark(counterName + "-Begin");
  5198. };
  5199. Tools._EndUserMark = function (counterName, condition) {
  5200. if (condition === void 0) { condition = true; }
  5201. if (!condition || !Tools._performance.mark) {
  5202. return;
  5203. }
  5204. Tools._performance.mark(counterName + "-End");
  5205. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5206. };
  5207. Tools._StartPerformanceConsole = function (counterName, condition) {
  5208. if (condition === void 0) { condition = true; }
  5209. if (!condition) {
  5210. return;
  5211. }
  5212. Tools._StartUserMark(counterName, condition);
  5213. if (console.time) {
  5214. console.time(counterName);
  5215. }
  5216. };
  5217. Tools._EndPerformanceConsole = function (counterName, condition) {
  5218. if (condition === void 0) { condition = true; }
  5219. if (!condition) {
  5220. return;
  5221. }
  5222. Tools._EndUserMark(counterName, condition);
  5223. if (console.time) {
  5224. console.timeEnd(counterName);
  5225. }
  5226. };
  5227. Object.defineProperty(Tools, "Now", {
  5228. get: function () {
  5229. if (window.performance && window.performance.now) {
  5230. return window.performance.now();
  5231. }
  5232. return new Date().getTime();
  5233. },
  5234. enumerable: true,
  5235. configurable: true
  5236. });
  5237. /**
  5238. * This method will return the name of the class used to create the instance of the given object.
  5239. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5240. * @param object the object to get the class name from
  5241. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5242. */
  5243. Tools.getClassName = function (object, isType) {
  5244. if (isType === void 0) { isType = false; }
  5245. var name = null;
  5246. if (!isType && object.getClassName) {
  5247. name = object.getClassName();
  5248. }
  5249. else {
  5250. if (object instanceof Object) {
  5251. var classObj = isType ? object : Object.getPrototypeOf(object);
  5252. name = classObj.constructor["__bjsclassName__"];
  5253. }
  5254. if (!name) {
  5255. name = typeof object;
  5256. }
  5257. }
  5258. return name;
  5259. };
  5260. Tools.first = function (array, predicate) {
  5261. for (var _i = 0; _i < array.length; _i++) {
  5262. var el = array[_i];
  5263. if (predicate(el)) {
  5264. return el;
  5265. }
  5266. }
  5267. };
  5268. /**
  5269. * 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.
  5270. * @param array
  5271. */
  5272. Tools.arrayOrStringFeeder = function (array) {
  5273. return function (index) {
  5274. if (index >= array.length) {
  5275. return null;
  5276. }
  5277. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5278. if (val && val.getHashCode) {
  5279. val = val.getHashCode();
  5280. }
  5281. if (typeof val === "string") {
  5282. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5283. }
  5284. return val;
  5285. };
  5286. };
  5287. /**
  5288. * Compute the hashCode of a stream of number
  5289. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5290. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5291. * @return the hash code computed
  5292. */
  5293. Tools.hashCodeFromStream = function (feeder) {
  5294. // Based from here: http://stackoverflow.com/a/7616484/802124
  5295. var hash = 0;
  5296. var index = 0;
  5297. var chr = feeder(index++);
  5298. while (chr != null) {
  5299. hash = ((hash << 5) - hash) + chr;
  5300. hash |= 0; // Convert to 32bit integer
  5301. chr = feeder(index++);
  5302. }
  5303. return hash;
  5304. };
  5305. Tools.BaseUrl = "";
  5306. Tools.CorsBehavior = "anonymous";
  5307. Tools.UseFallbackTexture = true;
  5308. // Logs
  5309. Tools._NoneLogLevel = 0;
  5310. Tools._MessageLogLevel = 1;
  5311. Tools._WarningLogLevel = 2;
  5312. Tools._ErrorLogLevel = 4;
  5313. Tools._LogCache = "";
  5314. Tools.errorsCount = 0;
  5315. Tools.Log = Tools._LogEnabled;
  5316. Tools.Warn = Tools._WarnEnabled;
  5317. Tools.Error = Tools._ErrorEnabled;
  5318. // Performances
  5319. Tools._PerformanceNoneLogLevel = 0;
  5320. Tools._PerformanceUserMarkLogLevel = 1;
  5321. Tools._PerformanceConsoleLogLevel = 2;
  5322. Tools._performance = window.performance;
  5323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5325. return Tools;
  5326. })();
  5327. BABYLON.Tools = Tools;
  5328. /**
  5329. * Use this className as a decorator on a given class definition to add it a name.
  5330. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5331. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5332. * @param name
  5333. */
  5334. function className(name) {
  5335. return function (target) {
  5336. target["__bjsclassName__"] = name;
  5337. };
  5338. }
  5339. BABYLON.className = className;
  5340. /**
  5341. * An implementation of a loop for asynchronous functions.
  5342. */
  5343. var AsyncLoop = (function () {
  5344. /**
  5345. * Constroctor.
  5346. * @param iterations the number of iterations.
  5347. * @param _fn the function to run each iteration
  5348. * @param _successCallback the callback that will be called upon succesful execution
  5349. * @param offset starting offset.
  5350. */
  5351. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5352. if (offset === void 0) { offset = 0; }
  5353. this.iterations = iterations;
  5354. this._fn = _fn;
  5355. this._successCallback = _successCallback;
  5356. this.index = offset - 1;
  5357. this._done = false;
  5358. }
  5359. /**
  5360. * Execute the next iteration. Must be called after the last iteration was finished.
  5361. */
  5362. AsyncLoop.prototype.executeNext = function () {
  5363. if (!this._done) {
  5364. if (this.index + 1 < this.iterations) {
  5365. ++this.index;
  5366. this._fn(this);
  5367. }
  5368. else {
  5369. this.breakLoop();
  5370. }
  5371. }
  5372. };
  5373. /**
  5374. * Break the loop and run the success callback.
  5375. */
  5376. AsyncLoop.prototype.breakLoop = function () {
  5377. this._done = true;
  5378. this._successCallback();
  5379. };
  5380. /**
  5381. * Helper function
  5382. */
  5383. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5384. if (offset === void 0) { offset = 0; }
  5385. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5386. loop.executeNext();
  5387. return loop;
  5388. };
  5389. /**
  5390. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5391. * @param iterations total number of iterations
  5392. * @param syncedIterations number of synchronous iterations in each async iteration.
  5393. * @param fn the function to call each iteration.
  5394. * @param callback a success call back that will be called when iterating stops.
  5395. * @param breakFunction a break condition (optional)
  5396. * @param timeout timeout settings for the setTimeout function. default - 0.
  5397. * @constructor
  5398. */
  5399. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5400. if (timeout === void 0) { timeout = 0; }
  5401. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5402. if (breakFunction && breakFunction())
  5403. loop.breakLoop();
  5404. else {
  5405. setTimeout(function () {
  5406. for (var i = 0; i < syncedIterations; ++i) {
  5407. var iteration = (loop.index * syncedIterations) + i;
  5408. if (iteration >= iterations)
  5409. break;
  5410. fn(iteration);
  5411. if (breakFunction && breakFunction()) {
  5412. loop.breakLoop();
  5413. break;
  5414. }
  5415. }
  5416. loop.executeNext();
  5417. }, timeout);
  5418. }
  5419. }, callback);
  5420. };
  5421. return AsyncLoop;
  5422. })();
  5423. BABYLON.AsyncLoop = AsyncLoop;
  5424. })(BABYLON || (BABYLON = {}));
  5425. var BABYLON;
  5426. (function (BABYLON) {
  5427. var Internals;
  5428. (function (Internals) {
  5429. var _AlphaState = (function () {
  5430. function _AlphaState() {
  5431. this._isAlphaBlendDirty = false;
  5432. this._isBlendFunctionParametersDirty = false;
  5433. this._alphaBlend = false;
  5434. this._blendFunctionParameters = new Array(4);
  5435. }
  5436. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5437. get: function () {
  5438. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5439. },
  5440. enumerable: true,
  5441. configurable: true
  5442. });
  5443. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5444. get: function () {
  5445. return this._alphaBlend;
  5446. },
  5447. set: function (value) {
  5448. if (this._alphaBlend === value) {
  5449. return;
  5450. }
  5451. this._alphaBlend = value;
  5452. this._isAlphaBlendDirty = true;
  5453. },
  5454. enumerable: true,
  5455. configurable: true
  5456. });
  5457. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5458. if (this._blendFunctionParameters[0] === value0 &&
  5459. this._blendFunctionParameters[1] === value1 &&
  5460. this._blendFunctionParameters[2] === value2 &&
  5461. this._blendFunctionParameters[3] === value3) {
  5462. return;
  5463. }
  5464. this._blendFunctionParameters[0] = value0;
  5465. this._blendFunctionParameters[1] = value1;
  5466. this._blendFunctionParameters[2] = value2;
  5467. this._blendFunctionParameters[3] = value3;
  5468. this._isBlendFunctionParametersDirty = true;
  5469. };
  5470. _AlphaState.prototype.reset = function () {
  5471. this._alphaBlend = false;
  5472. this._blendFunctionParameters[0] = null;
  5473. this._blendFunctionParameters[1] = null;
  5474. this._blendFunctionParameters[2] = null;
  5475. this._blendFunctionParameters[3] = null;
  5476. this._isAlphaBlendDirty = true;
  5477. this._isBlendFunctionParametersDirty = false;
  5478. };
  5479. _AlphaState.prototype.apply = function (gl) {
  5480. if (!this.isDirty) {
  5481. return;
  5482. }
  5483. // Alpha blend
  5484. if (this._isAlphaBlendDirty) {
  5485. if (this._alphaBlend) {
  5486. gl.enable(gl.BLEND);
  5487. }
  5488. else {
  5489. gl.disable(gl.BLEND);
  5490. }
  5491. this._isAlphaBlendDirty = false;
  5492. }
  5493. // Alpha function
  5494. if (this._isBlendFunctionParametersDirty) {
  5495. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5496. this._isBlendFunctionParametersDirty = false;
  5497. }
  5498. };
  5499. return _AlphaState;
  5500. })();
  5501. Internals._AlphaState = _AlphaState;
  5502. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5503. })(BABYLON || (BABYLON = {}));
  5504. var BABYLON;
  5505. (function (BABYLON) {
  5506. var Internals;
  5507. (function (Internals) {
  5508. var _DepthCullingState = (function () {
  5509. function _DepthCullingState() {
  5510. this._isDepthTestDirty = false;
  5511. this._isDepthMaskDirty = false;
  5512. this._isDepthFuncDirty = false;
  5513. this._isCullFaceDirty = false;
  5514. this._isCullDirty = false;
  5515. this._isZOffsetDirty = false;
  5516. }
  5517. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5518. get: function () {
  5519. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5520. },
  5521. enumerable: true,
  5522. configurable: true
  5523. });
  5524. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5525. get: function () {
  5526. return this._zOffset;
  5527. },
  5528. set: function (value) {
  5529. if (this._zOffset === value) {
  5530. return;
  5531. }
  5532. this._zOffset = value;
  5533. this._isZOffsetDirty = true;
  5534. },
  5535. enumerable: true,
  5536. configurable: true
  5537. });
  5538. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5539. get: function () {
  5540. return this._cullFace;
  5541. },
  5542. set: function (value) {
  5543. if (this._cullFace === value) {
  5544. return;
  5545. }
  5546. this._cullFace = value;
  5547. this._isCullFaceDirty = true;
  5548. },
  5549. enumerable: true,
  5550. configurable: true
  5551. });
  5552. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5553. get: function () {
  5554. return this._cull;
  5555. },
  5556. set: function (value) {
  5557. if (this._cull === value) {
  5558. return;
  5559. }
  5560. this._cull = value;
  5561. this._isCullDirty = true;
  5562. },
  5563. enumerable: true,
  5564. configurable: true
  5565. });
  5566. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5567. get: function () {
  5568. return this._depthFunc;
  5569. },
  5570. set: function (value) {
  5571. if (this._depthFunc === value) {
  5572. return;
  5573. }
  5574. this._depthFunc = value;
  5575. this._isDepthFuncDirty = true;
  5576. },
  5577. enumerable: true,
  5578. configurable: true
  5579. });
  5580. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5581. get: function () {
  5582. return this._depthMask;
  5583. },
  5584. set: function (value) {
  5585. if (this._depthMask === value) {
  5586. return;
  5587. }
  5588. this._depthMask = value;
  5589. this._isDepthMaskDirty = true;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5595. get: function () {
  5596. return this._depthTest;
  5597. },
  5598. set: function (value) {
  5599. if (this._depthTest === value) {
  5600. return;
  5601. }
  5602. this._depthTest = value;
  5603. this._isDepthTestDirty = true;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. _DepthCullingState.prototype.reset = function () {
  5609. this._depthMask = true;
  5610. this._depthTest = true;
  5611. this._depthFunc = null;
  5612. this._cullFace = null;
  5613. this._cull = null;
  5614. this._zOffset = 0;
  5615. this._isDepthTestDirty = true;
  5616. this._isDepthMaskDirty = true;
  5617. this._isDepthFuncDirty = false;
  5618. this._isCullFaceDirty = false;
  5619. this._isCullDirty = false;
  5620. this._isZOffsetDirty = false;
  5621. };
  5622. _DepthCullingState.prototype.apply = function (gl) {
  5623. if (!this.isDirty) {
  5624. return;
  5625. }
  5626. // Cull
  5627. if (this._isCullDirty) {
  5628. if (this.cull) {
  5629. gl.enable(gl.CULL_FACE);
  5630. }
  5631. else {
  5632. gl.disable(gl.CULL_FACE);
  5633. }
  5634. this._isCullDirty = false;
  5635. }
  5636. // Cull face
  5637. if (this._isCullFaceDirty) {
  5638. gl.cullFace(this.cullFace);
  5639. this._isCullFaceDirty = false;
  5640. }
  5641. // Depth mask
  5642. if (this._isDepthMaskDirty) {
  5643. gl.depthMask(this.depthMask);
  5644. this._isDepthMaskDirty = false;
  5645. }
  5646. // Depth test
  5647. if (this._isDepthTestDirty) {
  5648. if (this.depthTest) {
  5649. gl.enable(gl.DEPTH_TEST);
  5650. }
  5651. else {
  5652. gl.disable(gl.DEPTH_TEST);
  5653. }
  5654. this._isDepthTestDirty = false;
  5655. }
  5656. // Depth func
  5657. if (this._isDepthFuncDirty) {
  5658. gl.depthFunc(this.depthFunc);
  5659. this._isDepthFuncDirty = false;
  5660. }
  5661. // zOffset
  5662. if (this._isZOffsetDirty) {
  5663. if (this.zOffset) {
  5664. gl.enable(gl.POLYGON_OFFSET_FILL);
  5665. gl.polygonOffset(this.zOffset, 0);
  5666. }
  5667. else {
  5668. gl.disable(gl.POLYGON_OFFSET_FILL);
  5669. }
  5670. this._isZOffsetDirty = false;
  5671. }
  5672. };
  5673. return _DepthCullingState;
  5674. })();
  5675. Internals._DepthCullingState = _DepthCullingState;
  5676. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5677. })(BABYLON || (BABYLON = {}));
  5678. var BABYLON;
  5679. (function (BABYLON) {
  5680. var compileShader = function (gl, source, type, defines) {
  5681. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5682. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5683. gl.compileShader(shader);
  5684. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5685. throw new Error(gl.getShaderInfoLog(shader));
  5686. }
  5687. return shader;
  5688. };
  5689. var getWebGLTextureType = function (gl, type) {
  5690. var textureType = gl.UNSIGNED_BYTE;
  5691. if (type === Engine.TEXTURETYPE_FLOAT)
  5692. textureType = gl.FLOAT;
  5693. return textureType;
  5694. };
  5695. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5696. var magFilter = gl.NEAREST;
  5697. var minFilter = gl.NEAREST;
  5698. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5699. magFilter = gl.LINEAR;
  5700. if (generateMipMaps) {
  5701. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5702. }
  5703. else {
  5704. minFilter = gl.LINEAR;
  5705. }
  5706. }
  5707. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5708. magFilter = gl.LINEAR;
  5709. if (generateMipMaps) {
  5710. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5711. }
  5712. else {
  5713. minFilter = gl.LINEAR;
  5714. }
  5715. }
  5716. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5717. magFilter = gl.NEAREST;
  5718. if (generateMipMaps) {
  5719. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5720. }
  5721. else {
  5722. minFilter = gl.NEAREST;
  5723. }
  5724. }
  5725. return {
  5726. min: minFilter,
  5727. mag: magFilter
  5728. };
  5729. };
  5730. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5732. var engine = scene.getEngine();
  5733. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5734. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5735. gl.bindTexture(gl.TEXTURE_2D, texture);
  5736. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5737. texture._baseWidth = width;
  5738. texture._baseHeight = height;
  5739. texture._width = potWidth;
  5740. texture._height = potHeight;
  5741. texture.isReady = true;
  5742. processFunction(potWidth, potHeight);
  5743. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5746. if (!noMipmap && !isCompressed) {
  5747. gl.generateMipmap(gl.TEXTURE_2D);
  5748. }
  5749. gl.bindTexture(gl.TEXTURE_2D, null);
  5750. engine.resetTextureCache();
  5751. scene._removePendingData(texture);
  5752. if (onLoad) {
  5753. onLoad();
  5754. }
  5755. };
  5756. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5757. var img;
  5758. var onload = function () {
  5759. loadedImages[index] = img;
  5760. loadedImages._internalCount++;
  5761. scene._removePendingData(img);
  5762. if (loadedImages._internalCount === 6) {
  5763. onfinish(loadedImages);
  5764. }
  5765. };
  5766. var onerror = function () {
  5767. scene._removePendingData(img);
  5768. };
  5769. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5770. scene._addPendingData(img);
  5771. };
  5772. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5773. var loadedImages = [];
  5774. loadedImages._internalCount = 0;
  5775. for (var index = 0; index < 6; index++) {
  5776. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5777. }
  5778. };
  5779. var InstancingAttributeInfo = (function () {
  5780. function InstancingAttributeInfo() {
  5781. }
  5782. return InstancingAttributeInfo;
  5783. })();
  5784. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5785. var EngineCapabilities = (function () {
  5786. function EngineCapabilities() {
  5787. }
  5788. return EngineCapabilities;
  5789. })();
  5790. BABYLON.EngineCapabilities = EngineCapabilities;
  5791. /**
  5792. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5793. */
  5794. var Engine = (function () {
  5795. /**
  5796. * @constructor
  5797. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5798. * @param {boolean} [antialias] - enable antialias
  5799. * @param options - further options to be sent to the getContext function
  5800. */
  5801. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5802. var _this = this;
  5803. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5804. // Public members
  5805. this.isFullscreen = false;
  5806. this.isPointerLock = false;
  5807. this.cullBackFaces = true;
  5808. this.renderEvenInBackground = true;
  5809. // To enable/disable IDB support and avoid XHR on .manifest
  5810. this.enableOfflineSupport = true;
  5811. this.scenes = new Array();
  5812. this._windowIsBackground = false;
  5813. this._webGLVersion = "1.0";
  5814. this._drawCalls = 0;
  5815. this._renderingQueueLaunched = false;
  5816. this._activeRenderLoops = [];
  5817. // FPS
  5818. this.fpsRange = 60;
  5819. this.previousFramesDuration = [];
  5820. this.fps = 60;
  5821. this.deltaTime = 0;
  5822. // States
  5823. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5824. this._alphaState = new BABYLON.Internals._AlphaState();
  5825. this._alphaMode = Engine.ALPHA_DISABLE;
  5826. // Cache
  5827. this._loadedTexturesCache = new Array();
  5828. this._maxTextureChannels = 16;
  5829. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5830. this._compiledEffects = {};
  5831. this._uintIndicesCurrentlySet = false;
  5832. this._currentBoundBuffer = new Array();
  5833. this._currentInstanceLocations = new Array();
  5834. this._currentInstanceBuffers = new Array();
  5835. this._renderingCanvas = canvas;
  5836. this._externalData = new BABYLON.StringDictionary();
  5837. options = options || {};
  5838. options.antialias = antialias;
  5839. if (options.preserveDrawingBuffer === undefined) {
  5840. options.preserveDrawingBuffer = false;
  5841. }
  5842. // GL
  5843. //try {
  5844. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5845. // if (this._gl) {
  5846. // this._webGLVersion = "2.0";
  5847. // }
  5848. //} catch (e) {
  5849. // // Do nothing
  5850. //}
  5851. if (!this._gl) {
  5852. try {
  5853. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5854. }
  5855. catch (e) {
  5856. throw new Error("WebGL not supported");
  5857. }
  5858. }
  5859. if (!this._gl) {
  5860. throw new Error("WebGL not supported");
  5861. }
  5862. this._onBlur = function () {
  5863. _this._windowIsBackground = true;
  5864. };
  5865. this._onFocus = function () {
  5866. _this._windowIsBackground = false;
  5867. };
  5868. window.addEventListener("blur", this._onBlur);
  5869. window.addEventListener("focus", this._onFocus);
  5870. // Viewport
  5871. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5872. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5873. this.resize();
  5874. // Caps
  5875. this._caps = new EngineCapabilities();
  5876. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5877. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5878. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5879. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5880. // Infos
  5881. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5882. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5883. if (rendererInfo != null) {
  5884. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5885. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5886. }
  5887. if (!this._glVendor) {
  5888. this._glVendor = "Unknown vendor";
  5889. }
  5890. if (!this._glRenderer) {
  5891. this._glRenderer = "Unknown renderer";
  5892. }
  5893. // Extensions
  5894. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5895. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5896. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5897. 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');
  5898. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5899. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5900. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5901. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5902. this._caps.highPrecisionShaderSupported = true;
  5903. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5904. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5905. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5906. if (this._gl.getShaderPrecisionFormat) {
  5907. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5908. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5909. }
  5910. // Depth buffer
  5911. this.setDepthBuffer(true);
  5912. this.setDepthFunctionToLessOrEqual();
  5913. this.setDepthWrite(true);
  5914. // Fullscreen
  5915. this._onFullscreenChange = function () {
  5916. if (document.fullscreen !== undefined) {
  5917. _this.isFullscreen = document.fullscreen;
  5918. }
  5919. else if (document.mozFullScreen !== undefined) {
  5920. _this.isFullscreen = document.mozFullScreen;
  5921. }
  5922. else if (document.webkitIsFullScreen !== undefined) {
  5923. _this.isFullscreen = document.webkitIsFullScreen;
  5924. }
  5925. else if (document.msIsFullScreen !== undefined) {
  5926. _this.isFullscreen = document.msIsFullScreen;
  5927. }
  5928. // Pointer lock
  5929. if (_this.isFullscreen && _this._pointerLockRequested) {
  5930. canvas.requestPointerLock = canvas.requestPointerLock ||
  5931. canvas.msRequestPointerLock ||
  5932. canvas.mozRequestPointerLock ||
  5933. canvas.webkitRequestPointerLock;
  5934. if (canvas.requestPointerLock) {
  5935. canvas.requestPointerLock();
  5936. }
  5937. }
  5938. };
  5939. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5940. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5941. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5942. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5943. // Pointer lock
  5944. this._onPointerLockChange = function () {
  5945. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5946. document.webkitPointerLockElement === canvas ||
  5947. document.msPointerLockElement === canvas ||
  5948. document.pointerLockElement === canvas);
  5949. };
  5950. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5951. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5952. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5953. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5954. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5955. Engine.audioEngine = new BABYLON.AudioEngine();
  5956. }
  5957. //default loading screen
  5958. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5959. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5960. }
  5961. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5962. get: function () {
  5963. return Engine._ALPHA_DISABLE;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5969. get: function () {
  5970. return Engine._ALPHA_ONEONE;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Object.defineProperty(Engine, "ALPHA_ADD", {
  5976. get: function () {
  5977. return Engine._ALPHA_ADD;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5983. get: function () {
  5984. return Engine._ALPHA_COMBINE;
  5985. },
  5986. enumerable: true,
  5987. configurable: true
  5988. });
  5989. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5990. get: function () {
  5991. return Engine._ALPHA_SUBTRACT;
  5992. },
  5993. enumerable: true,
  5994. configurable: true
  5995. });
  5996. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5997. get: function () {
  5998. return Engine._ALPHA_MULTIPLY;
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6004. get: function () {
  6005. return Engine._ALPHA_MAXIMIZED;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6011. get: function () {
  6012. return Engine._DELAYLOADSTATE_NONE;
  6013. },
  6014. enumerable: true,
  6015. configurable: true
  6016. });
  6017. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6018. get: function () {
  6019. return Engine._DELAYLOADSTATE_LOADED;
  6020. },
  6021. enumerable: true,
  6022. configurable: true
  6023. });
  6024. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6025. get: function () {
  6026. return Engine._DELAYLOADSTATE_LOADING;
  6027. },
  6028. enumerable: true,
  6029. configurable: true
  6030. });
  6031. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6032. get: function () {
  6033. return Engine._DELAYLOADSTATE_NOTLOADED;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6039. get: function () {
  6040. return Engine._TEXTUREFORMAT_ALPHA;
  6041. },
  6042. enumerable: true,
  6043. configurable: true
  6044. });
  6045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6046. get: function () {
  6047. return Engine._TEXTUREFORMAT_LUMINANCE;
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6053. get: function () {
  6054. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6055. },
  6056. enumerable: true,
  6057. configurable: true
  6058. });
  6059. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6060. get: function () {
  6061. return Engine._TEXTUREFORMAT_RGB;
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6067. get: function () {
  6068. return Engine._TEXTUREFORMAT_RGBA;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6074. get: function () {
  6075. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6081. get: function () {
  6082. return Engine._TEXTURETYPE_FLOAT;
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Engine, "Version", {
  6088. get: function () {
  6089. return "2.4.0-beta";
  6090. },
  6091. enumerable: true,
  6092. configurable: true
  6093. });
  6094. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6095. get: function () {
  6096. return this._webGLVersion;
  6097. },
  6098. enumerable: true,
  6099. configurable: true
  6100. });
  6101. Engine.prototype._prepareWorkingCanvas = function () {
  6102. if (this._workingCanvas) {
  6103. return;
  6104. }
  6105. this._workingCanvas = document.createElement("canvas");
  6106. this._workingContext = this._workingCanvas.getContext("2d");
  6107. };
  6108. Engine.prototype.resetTextureCache = function () {
  6109. for (var index = 0; index < this._maxTextureChannels; index++) {
  6110. this._activeTexturesCache[index] = null;
  6111. }
  6112. };
  6113. Engine.prototype.getGlInfo = function () {
  6114. return {
  6115. vendor: this._glVendor,
  6116. renderer: this._glRenderer,
  6117. version: this._glVersion
  6118. };
  6119. };
  6120. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6121. if (useScreen === void 0) { useScreen = false; }
  6122. var viewport = camera.viewport;
  6123. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6124. };
  6125. Engine.prototype.getRenderWidth = function (useScreen) {
  6126. if (useScreen === void 0) { useScreen = false; }
  6127. if (!useScreen && this._currentRenderTarget) {
  6128. return this._currentRenderTarget._width;
  6129. }
  6130. return this._renderingCanvas.width;
  6131. };
  6132. Engine.prototype.getRenderHeight = function (useScreen) {
  6133. if (useScreen === void 0) { useScreen = false; }
  6134. if (!useScreen && this._currentRenderTarget) {
  6135. return this._currentRenderTarget._height;
  6136. }
  6137. return this._renderingCanvas.height;
  6138. };
  6139. Engine.prototype.getRenderingCanvas = function () {
  6140. return this._renderingCanvas;
  6141. };
  6142. Engine.prototype.getRenderingCanvasClientRect = function () {
  6143. return this._renderingCanvas.getBoundingClientRect();
  6144. };
  6145. Engine.prototype.setHardwareScalingLevel = function (level) {
  6146. this._hardwareScalingLevel = level;
  6147. this.resize();
  6148. };
  6149. Engine.prototype.getHardwareScalingLevel = function () {
  6150. return this._hardwareScalingLevel;
  6151. };
  6152. Engine.prototype.getLoadedTexturesCache = function () {
  6153. return this._loadedTexturesCache;
  6154. };
  6155. Engine.prototype.getCaps = function () {
  6156. return this._caps;
  6157. };
  6158. Object.defineProperty(Engine.prototype, "drawCalls", {
  6159. get: function () {
  6160. return this._drawCalls;
  6161. },
  6162. enumerable: true,
  6163. configurable: true
  6164. });
  6165. // Methods
  6166. Engine.prototype.resetDrawCalls = function () {
  6167. this._drawCalls = 0;
  6168. };
  6169. Engine.prototype.getDepthFunction = function () {
  6170. return this._depthCullingState.depthFunc;
  6171. };
  6172. Engine.prototype.setDepthFunction = function (depthFunc) {
  6173. this._depthCullingState.depthFunc = depthFunc;
  6174. };
  6175. Engine.prototype.setDepthFunctionToGreater = function () {
  6176. this._depthCullingState.depthFunc = this._gl.GREATER;
  6177. };
  6178. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6179. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6180. };
  6181. Engine.prototype.setDepthFunctionToLess = function () {
  6182. this._depthCullingState.depthFunc = this._gl.LESS;
  6183. };
  6184. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6185. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6186. };
  6187. /**
  6188. * stop executing a render loop function and remove it from the execution array
  6189. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6190. */
  6191. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6192. if (!renderFunction) {
  6193. this._activeRenderLoops = [];
  6194. return;
  6195. }
  6196. var index = this._activeRenderLoops.indexOf(renderFunction);
  6197. if (index >= 0) {
  6198. this._activeRenderLoops.splice(index, 1);
  6199. }
  6200. };
  6201. Engine.prototype._renderLoop = function () {
  6202. var shouldRender = true;
  6203. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6204. shouldRender = false;
  6205. }
  6206. if (shouldRender) {
  6207. // Start new frame
  6208. this.beginFrame();
  6209. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6210. var renderFunction = this._activeRenderLoops[index];
  6211. renderFunction();
  6212. }
  6213. // Present
  6214. this.endFrame();
  6215. }
  6216. if (this._activeRenderLoops.length > 0) {
  6217. // Register new frame
  6218. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6219. }
  6220. else {
  6221. this._renderingQueueLaunched = false;
  6222. }
  6223. };
  6224. /**
  6225. * Register and execute a render loop. The engine can have more than one render function.
  6226. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6227. * @example
  6228. * engine.runRenderLoop(function () {
  6229. * scene.render()
  6230. * })
  6231. */
  6232. Engine.prototype.runRenderLoop = function (renderFunction) {
  6233. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6234. return;
  6235. }
  6236. this._activeRenderLoops.push(renderFunction);
  6237. if (!this._renderingQueueLaunched) {
  6238. this._renderingQueueLaunched = true;
  6239. this._bindedRenderFunction = this._renderLoop.bind(this);
  6240. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6241. }
  6242. };
  6243. /**
  6244. * Toggle full screen mode.
  6245. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6246. * @param {any} options - an options object to be sent to the requestFullscreen function
  6247. */
  6248. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6249. if (this.isFullscreen) {
  6250. BABYLON.Tools.ExitFullscreen();
  6251. }
  6252. else {
  6253. this._pointerLockRequested = requestPointerLock;
  6254. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6255. }
  6256. };
  6257. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6258. this.applyStates();
  6259. if (backBuffer) {
  6260. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6261. }
  6262. if (depthStencil && this._depthCullingState.depthMask) {
  6263. this._gl.clearDepth(1.0);
  6264. }
  6265. var mode = 0;
  6266. if (backBuffer) {
  6267. mode |= this._gl.COLOR_BUFFER_BIT;
  6268. }
  6269. if (depthStencil && this._depthCullingState.depthMask) {
  6270. mode |= this._gl.DEPTH_BUFFER_BIT;
  6271. }
  6272. this._gl.clear(mode);
  6273. };
  6274. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6275. var gl = this._gl;
  6276. // Save state
  6277. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6278. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6279. // Change state
  6280. gl.enable(gl.SCISSOR_TEST);
  6281. gl.scissor(x, y, width, height);
  6282. // Clear
  6283. this.clear(clearColor, true, true);
  6284. // Restore state
  6285. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6286. if (curScissor === true) {
  6287. gl.enable(gl.SCISSOR_TEST);
  6288. }
  6289. else {
  6290. gl.disable(gl.SCISSOR_TEST);
  6291. }
  6292. };
  6293. /**
  6294. * Set the WebGL's viewport
  6295. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6296. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6297. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6298. */
  6299. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6300. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6301. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6302. var x = viewport.x || 0;
  6303. var y = viewport.y || 0;
  6304. this._cachedViewport = viewport;
  6305. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6306. };
  6307. /**
  6308. * Directly set the WebGL Viewport
  6309. * The x, y, width & height are directly passed to the WebGL call
  6310. * @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.
  6311. */
  6312. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6313. var currentViewport = this._cachedViewport;
  6314. this._cachedViewport = null;
  6315. this._gl.viewport(x, y, width, height);
  6316. return currentViewport;
  6317. };
  6318. Engine.prototype.beginFrame = function () {
  6319. this._measureFps();
  6320. };
  6321. Engine.prototype.endFrame = function () {
  6322. //this.flushFramebuffer();
  6323. };
  6324. /**
  6325. * resize the view according to the canvas' size.
  6326. * @example
  6327. * window.addEventListener("resize", function () {
  6328. * engine.resize();
  6329. * });
  6330. */
  6331. Engine.prototype.resize = function () {
  6332. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6333. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6334. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6335. for (var index = 0; index < this.scenes.length; index++) {
  6336. var scene = this.scenes[index];
  6337. if (scene.debugLayer.isVisible()) {
  6338. scene.debugLayer._syncPositions();
  6339. }
  6340. }
  6341. };
  6342. /**
  6343. * force a specific size of the canvas
  6344. * @param {number} width - the new canvas' width
  6345. * @param {number} height - the new canvas' height
  6346. */
  6347. Engine.prototype.setSize = function (width, height) {
  6348. this._renderingCanvas.width = width;
  6349. this._renderingCanvas.height = height;
  6350. for (var index = 0; index < this.scenes.length; index++) {
  6351. var scene = this.scenes[index];
  6352. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6353. var cam = scene.cameras[camIndex];
  6354. cam._currentRenderId = 0;
  6355. }
  6356. }
  6357. };
  6358. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6359. this._currentRenderTarget = texture;
  6360. var gl = this._gl;
  6361. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6362. if (texture.isCube) {
  6363. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6364. }
  6365. else {
  6366. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6367. }
  6368. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6369. this.wipeCaches();
  6370. };
  6371. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6372. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6373. this._currentRenderTarget = null;
  6374. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6375. var gl = this._gl;
  6376. gl.bindTexture(gl.TEXTURE_2D, texture);
  6377. gl.generateMipmap(gl.TEXTURE_2D);
  6378. gl.bindTexture(gl.TEXTURE_2D, null);
  6379. }
  6380. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6381. };
  6382. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6383. if (texture.generateMipMaps) {
  6384. var gl = this._gl;
  6385. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6386. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6387. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6388. }
  6389. };
  6390. Engine.prototype.flushFramebuffer = function () {
  6391. this._gl.flush();
  6392. };
  6393. Engine.prototype.restoreDefaultFramebuffer = function () {
  6394. this._currentRenderTarget = null;
  6395. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6396. this.setViewport(this._cachedViewport);
  6397. this.wipeCaches();
  6398. };
  6399. // VBOs
  6400. Engine.prototype._resetVertexBufferBinding = function () {
  6401. this.bindBuffer(null, this._gl.ARRAY_BUFFER);
  6402. this._cachedVertexBuffers = null;
  6403. };
  6404. Engine.prototype.createVertexBuffer = function (vertices) {
  6405. var vbo = this._gl.createBuffer();
  6406. this.bindBuffer(vbo, this._gl.ARRAY_BUFFER);
  6407. if (vertices instanceof Float32Array) {
  6408. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6409. }
  6410. else {
  6411. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6412. }
  6413. this._resetVertexBufferBinding();
  6414. vbo.references = 1;
  6415. return vbo;
  6416. };
  6417. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6418. var vbo = this._gl.createBuffer();
  6419. this.bindBuffer(vbo, this._gl.ARRAY_BUFFER);
  6420. if (vertices instanceof Float32Array) {
  6421. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6422. }
  6423. else {
  6424. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6425. }
  6426. this._resetVertexBufferBinding();
  6427. vbo.references = 1;
  6428. return vbo;
  6429. };
  6430. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6431. this.bindBuffer(vertexBuffer, this._gl.ARRAY_BUFFER);
  6432. if (offset === undefined) {
  6433. offset = 0;
  6434. }
  6435. if (count === undefined) {
  6436. if (vertices instanceof Float32Array) {
  6437. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6438. }
  6439. else {
  6440. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6441. }
  6442. }
  6443. else {
  6444. if (vertices instanceof Float32Array) {
  6445. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6446. }
  6447. else {
  6448. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6449. }
  6450. }
  6451. this._resetVertexBufferBinding();
  6452. };
  6453. Engine.prototype._resetIndexBufferBinding = function () {
  6454. this.bindBuffer(null, this._gl.ELEMENT_ARRAY_BUFFER);
  6455. this._cachedIndexBuffer = null;
  6456. };
  6457. Engine.prototype.createIndexBuffer = function (indices) {
  6458. var vbo = this._gl.createBuffer();
  6459. this.bindBuffer(vbo, this._gl.ELEMENT_ARRAY_BUFFER);
  6460. // Check for 32 bits indices
  6461. var arrayBuffer;
  6462. var need32Bits = false;
  6463. if (this._caps.uintIndices) {
  6464. for (var index = 0; index < indices.length; index++) {
  6465. if (indices[index] > 65535) {
  6466. need32Bits = true;
  6467. break;
  6468. }
  6469. }
  6470. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6471. }
  6472. else {
  6473. arrayBuffer = new Uint16Array(indices);
  6474. }
  6475. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6476. this._resetIndexBufferBinding();
  6477. vbo.references = 1;
  6478. vbo.is32Bits = need32Bits;
  6479. return vbo;
  6480. };
  6481. Engine.prototype.bindArrayBuffer = function (buffer) {
  6482. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6483. };
  6484. Engine.prototype.updateArrayBuffer = function (data) {
  6485. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6486. };
  6487. Engine.prototype.bindBuffer = function (buffer, target) {
  6488. if (this._currentBoundBuffer[target] !== buffer) {
  6489. this._gl.bindBuffer(target, buffer);
  6490. this._currentBoundBuffer[target] = buffer;
  6491. }
  6492. };
  6493. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6494. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6495. this._cachedVertexBuffers = vertexBuffer;
  6496. this._cachedEffectForVertexBuffers = effect;
  6497. this.bindBuffer(vertexBuffer, this._gl.ARRAY_BUFFER);
  6498. var offset = 0;
  6499. for (var index = 0; index < vertexDeclaration.length; index++) {
  6500. var order = effect.getAttributeLocation(index);
  6501. if (order >= 0) {
  6502. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6503. }
  6504. offset += vertexDeclaration[index] * 4;
  6505. }
  6506. }
  6507. if (this._cachedIndexBuffer !== indexBuffer) {
  6508. this._cachedIndexBuffer = indexBuffer;
  6509. this.bindBuffer(indexBuffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6510. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6511. }
  6512. };
  6513. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6514. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6515. this._cachedVertexBuffers = vertexBuffers;
  6516. this._cachedEffectForVertexBuffers = effect;
  6517. var attributes = effect.getAttributesNames();
  6518. for (var index = 0; index < attributes.length; index++) {
  6519. var order = effect.getAttributeLocation(index);
  6520. if (order >= 0) {
  6521. var vertexBuffer = vertexBuffers[attributes[index]];
  6522. if (!vertexBuffer) {
  6523. continue;
  6524. }
  6525. var buffer = vertexBuffer.getBuffer();
  6526. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6527. this._gl.vertexAttribPointer(order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6528. if (vertexBuffer.getIsInstanced()) {
  6529. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6530. this._currentInstanceLocations.push(order);
  6531. this._currentInstanceBuffers.push(buffer);
  6532. }
  6533. }
  6534. }
  6535. }
  6536. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6537. this._cachedIndexBuffer = indexBuffer;
  6538. this.bindBuffer(indexBuffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6539. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6540. }
  6541. };
  6542. Engine.prototype.unbindInstanceAttributes = function () {
  6543. var boundBuffer;
  6544. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6545. var instancesBuffer = this._currentInstanceBuffers[i];
  6546. if (boundBuffer != instancesBuffer) {
  6547. boundBuffer = instancesBuffer;
  6548. this.bindBuffer(instancesBuffer, this._gl.ARRAY_BUFFER);
  6549. }
  6550. var offsetLocation = this._currentInstanceLocations[i];
  6551. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6552. }
  6553. this._currentInstanceBuffers.length = 0;
  6554. this._currentInstanceLocations.length = 0;
  6555. };
  6556. Engine.prototype._releaseBuffer = function (buffer) {
  6557. buffer.references--;
  6558. if (buffer.references === 0) {
  6559. this._gl.deleteBuffer(buffer);
  6560. return true;
  6561. }
  6562. return false;
  6563. };
  6564. Engine.prototype.createInstancesBuffer = function (capacity) {
  6565. var buffer = this._gl.createBuffer();
  6566. buffer.capacity = capacity;
  6567. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6568. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6569. return buffer;
  6570. };
  6571. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6572. this._gl.deleteBuffer(buffer);
  6573. };
  6574. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6575. this.bindBuffer(instancesBuffer, this._gl.ARRAY_BUFFER);
  6576. if (data) {
  6577. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6578. }
  6579. if (offsetLocations[0].index !== undefined) {
  6580. var stride = 0;
  6581. for (var i = 0; i < offsetLocations.length; i++) {
  6582. var ai = offsetLocations[i];
  6583. stride += ai.attributeSize * 4;
  6584. }
  6585. for (var i = 0; i < offsetLocations.length; i++) {
  6586. var ai = offsetLocations[i];
  6587. this._gl.enableVertexAttribArray(ai.index);
  6588. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6589. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6590. this._currentInstanceLocations.push(ai.index);
  6591. this._currentInstanceBuffers.push(instancesBuffer);
  6592. }
  6593. }
  6594. else {
  6595. for (var index = 0; index < 4; index++) {
  6596. var offsetLocation = offsetLocations[index];
  6597. this._gl.enableVertexAttribArray(offsetLocation);
  6598. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6599. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6600. this._currentInstanceLocations.push(offsetLocation);
  6601. this._currentInstanceBuffers.push(instancesBuffer);
  6602. }
  6603. }
  6604. };
  6605. Engine.prototype.applyStates = function () {
  6606. this._depthCullingState.apply(this._gl);
  6607. this._alphaState.apply(this._gl);
  6608. };
  6609. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6610. // Apply states
  6611. this.applyStates();
  6612. this._drawCalls++;
  6613. // Render
  6614. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6615. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6616. if (instancesCount) {
  6617. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6618. return;
  6619. }
  6620. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6621. };
  6622. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6623. // Apply states
  6624. this.applyStates();
  6625. this._drawCalls++;
  6626. if (instancesCount) {
  6627. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6628. return;
  6629. }
  6630. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6631. };
  6632. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6633. // Apply states
  6634. this.applyStates();
  6635. this._drawCalls++;
  6636. if (instancesCount) {
  6637. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6638. return;
  6639. }
  6640. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6641. };
  6642. // Shaders
  6643. Engine.prototype._releaseEffect = function (effect) {
  6644. if (this._compiledEffects[effect._key]) {
  6645. delete this._compiledEffects[effect._key];
  6646. if (effect.getProgram()) {
  6647. this._gl.deleteProgram(effect.getProgram());
  6648. }
  6649. }
  6650. };
  6651. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6652. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6653. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6654. var name = vertex + "+" + fragment + "@" + defines;
  6655. if (this._compiledEffects[name]) {
  6656. return this._compiledEffects[name];
  6657. }
  6658. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6659. effect._key = name;
  6660. this._compiledEffects[name] = effect;
  6661. return effect;
  6662. };
  6663. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6664. if (uniformsNames === void 0) { uniformsNames = []; }
  6665. if (samplers === void 0) { samplers = []; }
  6666. if (defines === void 0) { defines = ""; }
  6667. return this.createEffect({
  6668. vertex: "particles",
  6669. fragmentElement: fragmentName
  6670. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6671. };
  6672. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6673. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6674. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6675. var shaderProgram = this._gl.createProgram();
  6676. this._gl.attachShader(shaderProgram, vertexShader);
  6677. this._gl.attachShader(shaderProgram, fragmentShader);
  6678. this._gl.linkProgram(shaderProgram);
  6679. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6680. if (!linked) {
  6681. var error = this._gl.getProgramInfoLog(shaderProgram);
  6682. if (error) {
  6683. throw new Error(error);
  6684. }
  6685. }
  6686. this._gl.deleteShader(vertexShader);
  6687. this._gl.deleteShader(fragmentShader);
  6688. return shaderProgram;
  6689. };
  6690. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6691. var results = [];
  6692. for (var index = 0; index < uniformsNames.length; index++) {
  6693. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6694. }
  6695. return results;
  6696. };
  6697. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6698. var results = [];
  6699. for (var index = 0; index < attributesNames.length; index++) {
  6700. try {
  6701. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6702. }
  6703. catch (e) {
  6704. results.push(-1);
  6705. }
  6706. }
  6707. return results;
  6708. };
  6709. Engine.prototype.enableEffect = function (effect) {
  6710. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6711. if (effect && effect.onBind) {
  6712. effect.onBind(effect);
  6713. }
  6714. return;
  6715. }
  6716. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6717. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6718. // Use program
  6719. this._gl.useProgram(effect.getProgram());
  6720. var i, ul;
  6721. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6722. this._vertexAttribArraysToUse[i] = false;
  6723. }
  6724. var attributesCount = effect.getAttributesCount();
  6725. for (i = 0; i < attributesCount; i++) {
  6726. // Attributes
  6727. var order = effect.getAttributeLocation(i);
  6728. if (order >= 0) {
  6729. this._vertexAttribArraysToUse[order] = true;
  6730. }
  6731. }
  6732. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6733. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6734. continue;
  6735. }
  6736. this._vertexAttribArraysEnabled[i] = false;
  6737. this._gl.disableVertexAttribArray(i);
  6738. }
  6739. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6740. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6741. this._vertexAttribArraysEnabled[i] = true;
  6742. this._gl.enableVertexAttribArray(i);
  6743. }
  6744. }
  6745. this._currentEffect = effect;
  6746. if (effect.onBind) {
  6747. effect.onBind(effect);
  6748. }
  6749. };
  6750. Engine.prototype.setArray = function (uniform, array) {
  6751. if (!uniform)
  6752. return;
  6753. this._gl.uniform1fv(uniform, array);
  6754. };
  6755. Engine.prototype.setArray2 = function (uniform, array) {
  6756. if (!uniform || array.length % 2 !== 0)
  6757. return;
  6758. this._gl.uniform2fv(uniform, array);
  6759. };
  6760. Engine.prototype.setArray3 = function (uniform, array) {
  6761. if (!uniform || array.length % 3 !== 0)
  6762. return;
  6763. this._gl.uniform3fv(uniform, array);
  6764. };
  6765. Engine.prototype.setArray4 = function (uniform, array) {
  6766. if (!uniform || array.length % 4 !== 0)
  6767. return;
  6768. this._gl.uniform4fv(uniform, array);
  6769. };
  6770. Engine.prototype.setMatrices = function (uniform, matrices) {
  6771. if (!uniform)
  6772. return;
  6773. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6774. };
  6775. Engine.prototype.setMatrix = function (uniform, matrix) {
  6776. if (!uniform)
  6777. return;
  6778. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6779. };
  6780. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6781. if (!uniform)
  6782. return;
  6783. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6784. };
  6785. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6786. if (!uniform)
  6787. return;
  6788. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6789. };
  6790. Engine.prototype.setFloat = function (uniform, value) {
  6791. if (!uniform)
  6792. return;
  6793. this._gl.uniform1f(uniform, value);
  6794. };
  6795. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6796. if (!uniform)
  6797. return;
  6798. this._gl.uniform2f(uniform, x, y);
  6799. };
  6800. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6801. if (!uniform)
  6802. return;
  6803. this._gl.uniform3f(uniform, x, y, z);
  6804. };
  6805. Engine.prototype.setBool = function (uniform, bool) {
  6806. if (!uniform)
  6807. return;
  6808. this._gl.uniform1i(uniform, bool);
  6809. };
  6810. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6811. if (!uniform)
  6812. return;
  6813. this._gl.uniform4f(uniform, x, y, z, w);
  6814. };
  6815. Engine.prototype.setColor3 = function (uniform, color3) {
  6816. if (!uniform)
  6817. return;
  6818. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6819. };
  6820. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6821. if (!uniform)
  6822. return;
  6823. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6824. };
  6825. // States
  6826. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6827. if (zOffset === void 0) { zOffset = 0; }
  6828. if (reverseSide === void 0) { reverseSide = false; }
  6829. // Culling
  6830. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6831. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6832. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6833. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6834. if (culling) {
  6835. this._depthCullingState.cullFace = cullFace;
  6836. this._depthCullingState.cull = true;
  6837. }
  6838. else {
  6839. this._depthCullingState.cull = false;
  6840. }
  6841. }
  6842. // Z offset
  6843. this._depthCullingState.zOffset = zOffset;
  6844. };
  6845. Engine.prototype.setDepthBuffer = function (enable) {
  6846. this._depthCullingState.depthTest = enable;
  6847. };
  6848. Engine.prototype.getDepthWrite = function () {
  6849. return this._depthCullingState.depthMask;
  6850. };
  6851. Engine.prototype.setDepthWrite = function (enable) {
  6852. this._depthCullingState.depthMask = enable;
  6853. };
  6854. Engine.prototype.setColorWrite = function (enable) {
  6855. this._gl.colorMask(enable, enable, enable, enable);
  6856. };
  6857. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  6858. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  6859. if (this._alphaMode === mode) {
  6860. return;
  6861. }
  6862. switch (mode) {
  6863. case Engine.ALPHA_DISABLE:
  6864. this._alphaState.alphaBlend = false;
  6865. break;
  6866. case Engine.ALPHA_COMBINE:
  6867. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6868. this._alphaState.alphaBlend = true;
  6869. break;
  6870. case Engine.ALPHA_ONEONE:
  6871. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6872. this._alphaState.alphaBlend = true;
  6873. break;
  6874. case Engine.ALPHA_ADD:
  6875. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6876. this._alphaState.alphaBlend = true;
  6877. break;
  6878. case Engine.ALPHA_SUBTRACT:
  6879. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6880. this._alphaState.alphaBlend = true;
  6881. break;
  6882. case Engine.ALPHA_MULTIPLY:
  6883. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6884. this._alphaState.alphaBlend = true;
  6885. break;
  6886. case Engine.ALPHA_MAXIMIZED:
  6887. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6888. this._alphaState.alphaBlend = true;
  6889. break;
  6890. }
  6891. if (!noDepthWriteChange) {
  6892. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  6893. }
  6894. this._alphaMode = mode;
  6895. };
  6896. Engine.prototype.getAlphaMode = function () {
  6897. return this._alphaMode;
  6898. };
  6899. Engine.prototype.setAlphaTesting = function (enable) {
  6900. this._alphaTest = enable;
  6901. };
  6902. Engine.prototype.getAlphaTesting = function () {
  6903. return this._alphaTest;
  6904. };
  6905. // Textures
  6906. Engine.prototype.wipeCaches = function () {
  6907. this.resetTextureCache();
  6908. this._currentEffect = null;
  6909. this._depthCullingState.reset();
  6910. this.setDepthFunctionToLessOrEqual();
  6911. this._alphaState.reset();
  6912. this._cachedVertexBuffers = null;
  6913. this._cachedIndexBuffer = null;
  6914. this._cachedEffectForVertexBuffers = null;
  6915. };
  6916. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6917. var gl = this._gl;
  6918. gl.bindTexture(gl.TEXTURE_2D, texture);
  6919. var magFilter = gl.NEAREST;
  6920. var minFilter = gl.NEAREST;
  6921. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6922. magFilter = gl.LINEAR;
  6923. minFilter = gl.LINEAR;
  6924. }
  6925. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6926. magFilter = gl.LINEAR;
  6927. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6928. }
  6929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6931. gl.bindTexture(gl.TEXTURE_2D, null);
  6932. texture.samplingMode = samplingMode;
  6933. };
  6934. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6935. var _this = this;
  6936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6937. if (onLoad === void 0) { onLoad = null; }
  6938. if (onError === void 0) { onError = null; }
  6939. if (buffer === void 0) { buffer = null; }
  6940. var texture = this._gl.createTexture();
  6941. var extension;
  6942. var fromData = false;
  6943. if (url.substr(0, 5) === "data:") {
  6944. fromData = true;
  6945. }
  6946. if (!fromData)
  6947. extension = url.substr(url.length - 4, 4).toLowerCase();
  6948. else {
  6949. var oldUrl = url;
  6950. fromData = oldUrl.split(':');
  6951. url = oldUrl;
  6952. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6953. }
  6954. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6955. var isTGA = (extension === ".tga");
  6956. scene._addPendingData(texture);
  6957. texture.url = url;
  6958. texture.noMipmap = noMipmap;
  6959. texture.references = 1;
  6960. texture.samplingMode = samplingMode;
  6961. this._loadedTexturesCache.push(texture);
  6962. var onerror = function () {
  6963. scene._removePendingData(texture);
  6964. if (onError) {
  6965. onError();
  6966. }
  6967. };
  6968. var callback;
  6969. if (isTGA) {
  6970. callback = function (arrayBuffer) {
  6971. var data = new Uint8Array(arrayBuffer);
  6972. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6973. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6974. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6975. }, onLoad, samplingMode);
  6976. };
  6977. if (!(fromData instanceof Array))
  6978. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6979. callback(arrayBuffer);
  6980. }, onerror, scene.database, true);
  6981. else
  6982. callback(buffer);
  6983. }
  6984. else if (isDDS) {
  6985. callback = function (data) {
  6986. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6987. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6988. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6989. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6990. }, onLoad, samplingMode);
  6991. };
  6992. if (!(fromData instanceof Array))
  6993. BABYLON.Tools.LoadFile(url, function (data) {
  6994. callback(data);
  6995. }, onerror, scene.database, true);
  6996. else
  6997. callback(buffer);
  6998. }
  6999. else {
  7000. var onload = function (img) {
  7001. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7002. var isPot = (img.width === potWidth && img.height === potHeight);
  7003. if (!isPot) {
  7004. _this._prepareWorkingCanvas();
  7005. _this._workingCanvas.width = potWidth;
  7006. _this._workingCanvas.height = potHeight;
  7007. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7008. _this._workingContext.imageSmoothingEnabled = false;
  7009. _this._workingContext.mozImageSmoothingEnabled = false;
  7010. _this._workingContext.oImageSmoothingEnabled = false;
  7011. _this._workingContext.webkitImageSmoothingEnabled = false;
  7012. _this._workingContext.msImageSmoothingEnabled = false;
  7013. }
  7014. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7015. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7016. _this._workingContext.imageSmoothingEnabled = true;
  7017. _this._workingContext.mozImageSmoothingEnabled = true;
  7018. _this._workingContext.oImageSmoothingEnabled = true;
  7019. _this._workingContext.webkitImageSmoothingEnabled = true;
  7020. _this._workingContext.msImageSmoothingEnabled = true;
  7021. }
  7022. }
  7023. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7024. }, onLoad, samplingMode);
  7025. };
  7026. if (!(fromData instanceof Array))
  7027. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7028. else
  7029. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7030. }
  7031. return texture;
  7032. };
  7033. Engine.prototype._getInternalFormat = function (format) {
  7034. var internalFormat = this._gl.RGBA;
  7035. switch (format) {
  7036. case Engine.TEXTUREFORMAT_ALPHA:
  7037. internalFormat = this._gl.ALPHA;
  7038. break;
  7039. case Engine.TEXTUREFORMAT_LUMINANCE:
  7040. internalFormat = this._gl.LUMINANCE;
  7041. break;
  7042. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7043. internalFormat = this._gl.LUMINANCE_ALPHA;
  7044. break;
  7045. case Engine.TEXTUREFORMAT_RGB:
  7046. internalFormat = this._gl.RGB;
  7047. break;
  7048. case Engine.TEXTUREFORMAT_RGBA:
  7049. internalFormat = this._gl.RGBA;
  7050. break;
  7051. }
  7052. return internalFormat;
  7053. };
  7054. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7055. if (compression === void 0) { compression = null; }
  7056. var internalFormat = this._getInternalFormat(format);
  7057. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7058. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7059. if (texture._width % 4 !== 0) {
  7060. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7061. }
  7062. if (compression) {
  7063. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7064. }
  7065. else {
  7066. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7067. }
  7068. if (texture.generateMipMaps) {
  7069. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7070. }
  7071. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7072. this.resetTextureCache();
  7073. texture.isReady = true;
  7074. };
  7075. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7076. if (compression === void 0) { compression = null; }
  7077. var texture = this._gl.createTexture();
  7078. texture._baseWidth = width;
  7079. texture._baseHeight = height;
  7080. texture._width = width;
  7081. texture._height = height;
  7082. texture.references = 1;
  7083. this.updateRawTexture(texture, data, format, invertY, compression);
  7084. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7085. // Filters
  7086. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7087. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7088. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7089. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7090. texture.samplingMode = samplingMode;
  7091. this._loadedTexturesCache.push(texture);
  7092. return texture;
  7093. };
  7094. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  7095. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  7096. var texture = this._gl.createTexture();
  7097. texture._baseWidth = width;
  7098. texture._baseHeight = height;
  7099. if (forceExponantOfTwo) {
  7100. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7101. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7102. }
  7103. this.resetTextureCache();
  7104. texture._width = width;
  7105. texture._height = height;
  7106. texture.isReady = false;
  7107. texture.generateMipMaps = generateMipMaps;
  7108. texture.references = 1;
  7109. texture.samplingMode = samplingMode;
  7110. this.updateTextureSamplingMode(samplingMode, texture);
  7111. this._loadedTexturesCache.push(texture);
  7112. return texture;
  7113. };
  7114. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7115. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7116. if (texture.isCube) {
  7117. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  7118. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7119. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7120. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7121. }
  7122. else {
  7123. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7124. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7125. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7126. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7127. }
  7128. };
  7129. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7130. if (premulAlpha === void 0) { premulAlpha = false; }
  7131. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7132. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7133. if (premulAlpha) {
  7134. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7135. }
  7136. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7137. if (texture.generateMipMaps) {
  7138. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7139. }
  7140. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7141. this.resetTextureCache();
  7142. texture.isReady = true;
  7143. };
  7144. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7145. if (texture._isDisabled) {
  7146. return;
  7147. }
  7148. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7149. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7150. try {
  7151. // Testing video texture support
  7152. if (this._videoTextureSupported === undefined) {
  7153. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7154. if (this._gl.getError() !== 0) {
  7155. this._videoTextureSupported = false;
  7156. }
  7157. else {
  7158. this._videoTextureSupported = true;
  7159. }
  7160. }
  7161. // Copy video through the current working canvas if video texture is not supported
  7162. if (!this._videoTextureSupported) {
  7163. if (!texture._workingCanvas) {
  7164. texture._workingCanvas = document.createElement("canvas");
  7165. texture._workingContext = texture._workingCanvas.getContext("2d");
  7166. texture._workingCanvas.width = texture._width;
  7167. texture._workingCanvas.height = texture._height;
  7168. }
  7169. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7170. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7171. }
  7172. else {
  7173. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7174. }
  7175. if (texture.generateMipMaps) {
  7176. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7177. }
  7178. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7179. this.resetTextureCache();
  7180. texture.isReady = true;
  7181. }
  7182. catch (ex) {
  7183. // Something unexpected
  7184. // Let's disable the texture
  7185. texture._isDisabled = true;
  7186. }
  7187. };
  7188. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7189. // old version had a "generateMipMaps" arg instead of options.
  7190. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7191. // in the same way, generateDepthBuffer is defaulted to true
  7192. var generateMipMaps = false;
  7193. var generateDepthBuffer = true;
  7194. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7195. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7196. if (options !== undefined) {
  7197. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7198. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7199. type = options.type === undefined ? type : options.type;
  7200. if (options.samplingMode !== undefined) {
  7201. samplingMode = options.samplingMode;
  7202. }
  7203. if (type === Engine.TEXTURETYPE_FLOAT) {
  7204. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7205. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7206. }
  7207. }
  7208. var gl = this._gl;
  7209. var texture = gl.createTexture();
  7210. gl.bindTexture(gl.TEXTURE_2D, texture);
  7211. var width = size.width || size;
  7212. var height = size.height || size;
  7213. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7214. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7215. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7216. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7217. }
  7218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); //filters.mag);
  7219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); //filters.min);
  7220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7222. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7223. var depthBuffer;
  7224. // Create the depth buffer
  7225. if (generateDepthBuffer) {
  7226. depthBuffer = gl.createRenderbuffer();
  7227. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7228. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7229. }
  7230. // Create the framebuffer
  7231. var framebuffer = gl.createFramebuffer();
  7232. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7233. if (generateDepthBuffer) {
  7234. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7235. }
  7236. if (generateMipMaps) {
  7237. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7238. }
  7239. // Unbind
  7240. gl.bindTexture(gl.TEXTURE_2D, null);
  7241. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7242. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7243. texture._framebuffer = framebuffer;
  7244. if (generateDepthBuffer) {
  7245. texture._depthBuffer = depthBuffer;
  7246. }
  7247. texture._baseWidth = width;
  7248. texture._baseHeight = height;
  7249. texture._width = width;
  7250. texture._height = height;
  7251. texture.isReady = true;
  7252. texture.generateMipMaps = generateMipMaps;
  7253. texture.references = 1;
  7254. texture.samplingMode = samplingMode;
  7255. this.resetTextureCache();
  7256. this._loadedTexturesCache.push(texture);
  7257. return texture;
  7258. };
  7259. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7260. var gl = this._gl;
  7261. var texture = gl.createTexture();
  7262. var generateMipMaps = true;
  7263. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7264. if (options !== undefined) {
  7265. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7266. if (options.samplingMode !== undefined) {
  7267. samplingMode = options.samplingMode;
  7268. }
  7269. }
  7270. texture.isCube = true;
  7271. texture.references = 1;
  7272. texture.generateMipMaps = generateMipMaps;
  7273. texture.references = 1;
  7274. texture.samplingMode = samplingMode;
  7275. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7276. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7277. for (var face = 0; face < 6; face++) {
  7278. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7279. }
  7280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7284. // Create the depth buffer
  7285. var depthBuffer = gl.createRenderbuffer();
  7286. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7287. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7288. // Create the framebuffer
  7289. var framebuffer = gl.createFramebuffer();
  7290. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7291. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7292. // Mipmaps
  7293. if (texture.generateMipMaps) {
  7294. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7295. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7296. }
  7297. // Unbind
  7298. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7299. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7300. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7301. texture._framebuffer = framebuffer;
  7302. texture._depthBuffer = depthBuffer;
  7303. this.resetTextureCache();
  7304. texture._width = size;
  7305. texture._height = size;
  7306. texture.isReady = true;
  7307. return texture;
  7308. };
  7309. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7310. var _this = this;
  7311. var gl = this._gl;
  7312. var texture = gl.createTexture();
  7313. texture.isCube = true;
  7314. texture.url = rootUrl;
  7315. texture.references = 1;
  7316. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7317. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7318. if (isDDS) {
  7319. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7320. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7321. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7322. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7323. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7324. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7325. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7326. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7327. }
  7328. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7329. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7331. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7332. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7333. _this.resetTextureCache();
  7334. texture._width = info.width;
  7335. texture._height = info.height;
  7336. texture.isReady = true;
  7337. }, null, null, true);
  7338. }
  7339. else {
  7340. cascadeLoad(rootUrl, scene, function (imgs) {
  7341. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7342. var height = width;
  7343. _this._prepareWorkingCanvas();
  7344. _this._workingCanvas.width = width;
  7345. _this._workingCanvas.height = height;
  7346. var faces = [
  7347. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7348. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7349. ];
  7350. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7351. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7352. for (var index = 0; index < faces.length; index++) {
  7353. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7354. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7355. }
  7356. if (!noMipmap) {
  7357. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7358. }
  7359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7363. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7364. _this.resetTextureCache();
  7365. texture._width = width;
  7366. texture._height = height;
  7367. texture.isReady = true;
  7368. }, files);
  7369. }
  7370. return texture;
  7371. };
  7372. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7373. texture._width = width;
  7374. texture._height = height;
  7375. texture._size = width * height;
  7376. texture._baseWidth = width;
  7377. texture._baseHeight = height;
  7378. };
  7379. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7380. var _this = this;
  7381. var gl = this._gl;
  7382. var texture = gl.createTexture();
  7383. scene._addPendingData(texture);
  7384. texture.isCube = true;
  7385. texture.references = 1;
  7386. texture.url = url;
  7387. var internalFormat = this._getInternalFormat(format);
  7388. var textureType = gl.UNSIGNED_BYTE;
  7389. if (type === Engine.TEXTURETYPE_FLOAT) {
  7390. textureType = gl.FLOAT;
  7391. }
  7392. var width = size;
  7393. var height = width;
  7394. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7395. texture._width = width;
  7396. texture._height = height;
  7397. var onerror = function () {
  7398. scene._removePendingData(texture);
  7399. };
  7400. var internalCallback = function (data) {
  7401. var rgbeDataArrays = callback(data);
  7402. var facesIndex = [
  7403. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7404. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7405. ];
  7406. width = texture._width;
  7407. height = texture._height;
  7408. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7409. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7410. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7411. if (!noMipmap && isPot) {
  7412. if (mipmmapGenerator) {
  7413. var arrayTemp = [];
  7414. // Data are known to be in +X +Y +Z -X -Y -Z
  7415. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7416. arrayTemp.push(rgbeDataArrays[0]); // +X
  7417. arrayTemp.push(rgbeDataArrays[3]); // -X
  7418. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7419. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7420. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7421. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7422. var mipData = mipmmapGenerator(arrayTemp);
  7423. for (var level = 0; level < mipData.length; level++) {
  7424. var mipSize = width >> level;
  7425. // mipData is order in +X -X +Y -Y +Z -Z
  7426. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7427. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7428. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7429. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7430. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7431. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7432. }
  7433. }
  7434. else {
  7435. // Data are known to be in +X +Y +Z -X -Y -Z
  7436. for (var index = 0; index < facesIndex.length; index++) {
  7437. var faceData = rgbeDataArrays[index];
  7438. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7439. }
  7440. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7441. }
  7442. }
  7443. else {
  7444. noMipmap = true;
  7445. }
  7446. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7449. }
  7450. else {
  7451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7453. }
  7454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7456. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7457. texture.isReady = true;
  7458. _this.resetTextureCache();
  7459. scene._removePendingData(texture);
  7460. };
  7461. BABYLON.Tools.LoadFile(url, function (data) {
  7462. internalCallback(data);
  7463. }, onerror, scene.database, true);
  7464. return texture;
  7465. };
  7466. ;
  7467. Engine.prototype._releaseTexture = function (texture) {
  7468. var gl = this._gl;
  7469. if (texture._framebuffer) {
  7470. gl.deleteFramebuffer(texture._framebuffer);
  7471. }
  7472. if (texture._depthBuffer) {
  7473. gl.deleteRenderbuffer(texture._depthBuffer);
  7474. }
  7475. gl.deleteTexture(texture);
  7476. // Unbind channels
  7477. this.unbindAllTextures();
  7478. var index = this._loadedTexturesCache.indexOf(texture);
  7479. if (index !== -1) {
  7480. this._loadedTexturesCache.splice(index, 1);
  7481. }
  7482. };
  7483. Engine.prototype.bindSamplers = function (effect) {
  7484. this._gl.useProgram(effect.getProgram());
  7485. var samplers = effect.getSamplers();
  7486. for (var index = 0; index < samplers.length; index++) {
  7487. var uniform = effect.getUniform(samplers[index]);
  7488. this._gl.uniform1i(uniform, index);
  7489. }
  7490. this._currentEffect = null;
  7491. };
  7492. Engine.prototype._bindTexture = function (channel, texture) {
  7493. if (channel < 0) {
  7494. return;
  7495. }
  7496. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7497. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7498. this._activeTexturesCache[channel] = null;
  7499. };
  7500. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7501. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7502. };
  7503. Engine.prototype.unbindAllTextures = function () {
  7504. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7505. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7506. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7507. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7508. this._activeTexturesCache[channel] = null;
  7509. }
  7510. };
  7511. Engine.prototype.setTexture = function (channel, texture) {
  7512. if (channel < 0) {
  7513. return;
  7514. }
  7515. // Not ready?
  7516. if (!texture || !texture.isReady()) {
  7517. if (this._activeTexturesCache[channel] != null) {
  7518. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7519. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7520. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7521. this._activeTexturesCache[channel] = null;
  7522. }
  7523. return;
  7524. }
  7525. // Video
  7526. var alreadyActivated = false;
  7527. if (texture instanceof BABYLON.VideoTexture) {
  7528. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7529. alreadyActivated = true;
  7530. texture.update();
  7531. }
  7532. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7533. texture.delayLoad();
  7534. return;
  7535. }
  7536. if (this._activeTexturesCache[channel] === texture) {
  7537. return;
  7538. }
  7539. this._activeTexturesCache[channel] = texture;
  7540. var internalTexture = texture.getInternalTexture();
  7541. if (!alreadyActivated) {
  7542. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7543. }
  7544. if (internalTexture.isCube) {
  7545. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7546. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7547. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7548. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7549. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7550. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7551. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7552. }
  7553. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7554. }
  7555. else {
  7556. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7557. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7558. internalTexture._cachedWrapU = texture.wrapU;
  7559. switch (texture.wrapU) {
  7560. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7561. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7562. break;
  7563. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7564. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7565. break;
  7566. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7567. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7568. break;
  7569. }
  7570. }
  7571. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7572. internalTexture._cachedWrapV = texture.wrapV;
  7573. switch (texture.wrapV) {
  7574. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7575. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7576. break;
  7577. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7578. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7579. break;
  7580. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7581. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7582. break;
  7583. }
  7584. }
  7585. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7586. }
  7587. };
  7588. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7589. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7590. var value = texture.anisotropicFilteringLevel;
  7591. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7592. value = 1;
  7593. }
  7594. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7595. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7596. texture._cachedAnisotropicFilteringLevel = value;
  7597. }
  7598. };
  7599. Engine.prototype.readPixels = function (x, y, width, height) {
  7600. var data = new Uint8Array(height * width * 4);
  7601. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7602. return data;
  7603. };
  7604. /**
  7605. * Add an externaly attached data from its key.
  7606. * This method call will fail and return false, if such key already exists.
  7607. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7608. * @param key the unique key that identifies the data
  7609. * @param data the data object to associate to the key for this Engine instance
  7610. * @return true if no such key were already present and the data was added successfully, false otherwise
  7611. */
  7612. Engine.prototype.addExternalData = function (key, data) {
  7613. return this._externalData.add(key, data);
  7614. };
  7615. /**
  7616. * Get an externaly attached data from its key
  7617. * @param key the unique key that identifies the data
  7618. * @return the associated data, if present (can be null), or undefined if not present
  7619. */
  7620. Engine.prototype.getExternalData = function (key) {
  7621. return this._externalData.get(key);
  7622. };
  7623. /**
  7624. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7625. * @param key the unique key that identifies the data
  7626. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7627. * @return the associated data, can be null if the factory returned null.
  7628. */
  7629. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7630. return this._externalData.getOrAddWithFactory(key, factory);
  7631. };
  7632. /**
  7633. * Remove an externaly attached data from the Engine instance
  7634. * @param key the unique key that identifies the data
  7635. * @return true if the data was successfully removed, false if it doesn't exist
  7636. */
  7637. Engine.prototype.removeExternalData = function (key) {
  7638. return this._externalData.remove(key);
  7639. };
  7640. Engine.prototype.releaseInternalTexture = function (texture) {
  7641. if (!texture) {
  7642. return;
  7643. }
  7644. texture.references--;
  7645. // Final reference ?
  7646. if (texture.references === 0) {
  7647. var texturesCache = this.getLoadedTexturesCache();
  7648. var index = texturesCache.indexOf(texture);
  7649. if (index > -1) {
  7650. texturesCache.splice(index, 1);
  7651. }
  7652. this._releaseTexture(texture);
  7653. }
  7654. };
  7655. // Dispose
  7656. Engine.prototype.dispose = function () {
  7657. this.hideLoadingUI();
  7658. this.stopRenderLoop();
  7659. // Release scenes
  7660. while (this.scenes.length) {
  7661. this.scenes[0].dispose();
  7662. }
  7663. // Release audio engine
  7664. Engine.audioEngine.dispose();
  7665. // Release effects
  7666. for (var name in this._compiledEffects) {
  7667. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7668. }
  7669. // Unbind
  7670. if (this._vertexAttribArraysEnabled) {
  7671. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7672. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7673. continue;
  7674. }
  7675. this._gl.disableVertexAttribArray(i);
  7676. }
  7677. }
  7678. this._gl = null;
  7679. // Events
  7680. window.removeEventListener("blur", this._onBlur);
  7681. window.removeEventListener("focus", this._onFocus);
  7682. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7683. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7684. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7685. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7686. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7687. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7688. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7689. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7690. };
  7691. // Loading screen
  7692. Engine.prototype.displayLoadingUI = function () {
  7693. this._loadingScreen.displayLoadingUI();
  7694. };
  7695. Engine.prototype.hideLoadingUI = function () {
  7696. this._loadingScreen.hideLoadingUI();
  7697. };
  7698. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7699. get: function () {
  7700. return this._loadingScreen;
  7701. },
  7702. set: function (loadingScreen) {
  7703. this._loadingScreen = loadingScreen;
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7709. set: function (text) {
  7710. this._loadingScreen.loadingUIText = text;
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7716. set: function (color) {
  7717. this._loadingScreen.loadingUIBackgroundColor = color;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. // FPS
  7723. Engine.prototype.getFps = function () {
  7724. return this.fps;
  7725. };
  7726. Engine.prototype.getDeltaTime = function () {
  7727. return this.deltaTime;
  7728. };
  7729. Engine.prototype._measureFps = function () {
  7730. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7731. var length = this.previousFramesDuration.length;
  7732. if (length >= 2) {
  7733. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7734. }
  7735. if (length >= this.fpsRange) {
  7736. if (length > this.fpsRange) {
  7737. this.previousFramesDuration.splice(0, 1);
  7738. length = this.previousFramesDuration.length;
  7739. }
  7740. var sum = 0;
  7741. for (var id = 0; id < length - 1; id++) {
  7742. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7743. }
  7744. this.fps = 1000.0 / (sum / (length - 1));
  7745. }
  7746. };
  7747. // Statics
  7748. Engine.isSupported = function () {
  7749. try {
  7750. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7751. if (navigator.isCocoonJS) {
  7752. return true;
  7753. }
  7754. var tempcanvas = document.createElement("canvas");
  7755. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7756. return gl != null && !!window.WebGLRenderingContext;
  7757. }
  7758. catch (e) {
  7759. return false;
  7760. }
  7761. };
  7762. // Const statics
  7763. Engine._ALPHA_DISABLE = 0;
  7764. Engine._ALPHA_ADD = 1;
  7765. Engine._ALPHA_COMBINE = 2;
  7766. Engine._ALPHA_SUBTRACT = 3;
  7767. Engine._ALPHA_MULTIPLY = 4;
  7768. Engine._ALPHA_MAXIMIZED = 5;
  7769. Engine._ALPHA_ONEONE = 6;
  7770. Engine._DELAYLOADSTATE_NONE = 0;
  7771. Engine._DELAYLOADSTATE_LOADED = 1;
  7772. Engine._DELAYLOADSTATE_LOADING = 2;
  7773. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7774. Engine._TEXTUREFORMAT_ALPHA = 0;
  7775. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7776. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7777. Engine._TEXTUREFORMAT_RGB = 4;
  7778. Engine._TEXTUREFORMAT_RGBA = 5;
  7779. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7780. Engine._TEXTURETYPE_FLOAT = 1;
  7781. // Updatable statics so stick with vars here
  7782. Engine.CollisionsEpsilon = 0.001;
  7783. Engine.CodeRepository = "src/";
  7784. Engine.ShadersRepository = "src/Shaders/";
  7785. return Engine;
  7786. })();
  7787. BABYLON.Engine = Engine;
  7788. })(BABYLON || (BABYLON = {}));
  7789. var BABYLON;
  7790. (function (BABYLON) {
  7791. /**
  7792. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7793. */
  7794. var Node = (function () {
  7795. /**
  7796. * @constructor
  7797. * @param {string} name - the name and id to be given to this node
  7798. * @param {BABYLON.Scene} the scene this node will be added to
  7799. */
  7800. function Node(name, scene) {
  7801. this.state = "";
  7802. this.animations = new Array();
  7803. this._ranges = {};
  7804. this._childrenFlag = -1;
  7805. this._isEnabled = true;
  7806. this._isReady = true;
  7807. this._currentRenderId = -1;
  7808. this._parentRenderId = -1;
  7809. this.name = name;
  7810. this.id = name;
  7811. this._scene = scene;
  7812. this._initCache();
  7813. }
  7814. Object.defineProperty(Node.prototype, "parent", {
  7815. get: function () {
  7816. return this._parentNode;
  7817. },
  7818. set: function (parent) {
  7819. if (this._parentNode === parent) {
  7820. return;
  7821. }
  7822. if (this._parentNode) {
  7823. var index = this._parentNode._children.indexOf(this);
  7824. if (index !== -1) {
  7825. this._parentNode._children.splice(index, 1);
  7826. }
  7827. }
  7828. this._parentNode = parent;
  7829. if (this._parentNode) {
  7830. if (!this._parentNode._children) {
  7831. this._parentNode._children = new Array();
  7832. }
  7833. this._parentNode._children.push(this);
  7834. }
  7835. },
  7836. enumerable: true,
  7837. configurable: true
  7838. });
  7839. Node.prototype.getScene = function () {
  7840. return this._scene;
  7841. };
  7842. Node.prototype.getEngine = function () {
  7843. return this._scene.getEngine();
  7844. };
  7845. // override it in derived class
  7846. Node.prototype.getWorldMatrix = function () {
  7847. return BABYLON.Matrix.Identity();
  7848. };
  7849. // override it in derived class if you add new variables to the cache
  7850. // and call the parent class method
  7851. Node.prototype._initCache = function () {
  7852. this._cache = {};
  7853. this._cache.parent = undefined;
  7854. };
  7855. Node.prototype.updateCache = function (force) {
  7856. if (!force && this.isSynchronized())
  7857. return;
  7858. this._cache.parent = this.parent;
  7859. this._updateCache();
  7860. };
  7861. // override it in derived class if you add new variables to the cache
  7862. // and call the parent class method if !ignoreParentClass
  7863. Node.prototype._updateCache = function (ignoreParentClass) {
  7864. };
  7865. // override it in derived class if you add new variables to the cache
  7866. Node.prototype._isSynchronized = function () {
  7867. return true;
  7868. };
  7869. Node.prototype._markSyncedWithParent = function () {
  7870. this._parentRenderId = this.parent._currentRenderId;
  7871. };
  7872. Node.prototype.isSynchronizedWithParent = function () {
  7873. if (!this.parent) {
  7874. return true;
  7875. }
  7876. if (this._parentRenderId !== this.parent._currentRenderId) {
  7877. return false;
  7878. }
  7879. return this.parent.isSynchronized();
  7880. };
  7881. Node.prototype.isSynchronized = function (updateCache) {
  7882. var check = this.hasNewParent();
  7883. check = check || !this.isSynchronizedWithParent();
  7884. check = check || !this._isSynchronized();
  7885. if (updateCache)
  7886. this.updateCache(true);
  7887. return !check;
  7888. };
  7889. Node.prototype.hasNewParent = function (update) {
  7890. if (this._cache.parent === this.parent)
  7891. return false;
  7892. if (update)
  7893. this._cache.parent = this.parent;
  7894. return true;
  7895. };
  7896. /**
  7897. * Is this node ready to be used/rendered
  7898. * @return {boolean} is it ready
  7899. */
  7900. Node.prototype.isReady = function () {
  7901. return this._isReady;
  7902. };
  7903. /**
  7904. * Is this node enabled.
  7905. * If the node has a parent and is enabled, the parent will be inspected as well.
  7906. * @return {boolean} whether this node (and its parent) is enabled.
  7907. * @see setEnabled
  7908. */
  7909. Node.prototype.isEnabled = function () {
  7910. if (!this._isEnabled) {
  7911. return false;
  7912. }
  7913. if (this.parent) {
  7914. return this.parent.isEnabled();
  7915. }
  7916. return true;
  7917. };
  7918. /**
  7919. * Set the enabled state of this node.
  7920. * @param {boolean} value - the new enabled state
  7921. * @see isEnabled
  7922. */
  7923. Node.prototype.setEnabled = function (value) {
  7924. this._isEnabled = value;
  7925. };
  7926. /**
  7927. * Is this node a descendant of the given node.
  7928. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7929. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7930. * @see parent
  7931. */
  7932. Node.prototype.isDescendantOf = function (ancestor) {
  7933. if (this.parent) {
  7934. if (this.parent === ancestor) {
  7935. return true;
  7936. }
  7937. return this.parent.isDescendantOf(ancestor);
  7938. }
  7939. return false;
  7940. };
  7941. /**
  7942. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7943. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7944. * @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.
  7945. * @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.
  7946. */
  7947. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7948. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7949. if (!this._children) {
  7950. return;
  7951. }
  7952. for (var index = 0; index < this._children.length; index++) {
  7953. var item = this._children[index];
  7954. if (!predicate || predicate(item)) {
  7955. results.push(item);
  7956. }
  7957. if (!directDescendantsOnly) {
  7958. item._getDescendants(results, false, predicate);
  7959. }
  7960. }
  7961. };
  7962. /**
  7963. * Will return all nodes that have this node as ascendant.
  7964. * @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.
  7965. * @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.
  7966. * @return {BABYLON.Node[]} all children nodes of all types.
  7967. */
  7968. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7969. var results = [];
  7970. this._getDescendants(results, directDescendantsOnly, predicate);
  7971. return results;
  7972. };
  7973. /**
  7974. * @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.
  7975. * @Deprecated, legacy support.
  7976. * use getDecendants instead.
  7977. */
  7978. Node.prototype.getChildren = function (predicate) {
  7979. return this.getDescendants(true, predicate);
  7980. };
  7981. /**
  7982. * Get all child-meshes of this node.
  7983. */
  7984. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7985. var results = [];
  7986. this._getDescendants(results, directDecendantsOnly, function (node) {
  7987. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7988. });
  7989. return results;
  7990. };
  7991. Node.prototype._setReady = function (state) {
  7992. if (state === this._isReady) {
  7993. return;
  7994. }
  7995. if (!state) {
  7996. this._isReady = false;
  7997. return;
  7998. }
  7999. this._isReady = true;
  8000. if (this.onReady) {
  8001. this.onReady(this);
  8002. }
  8003. };
  8004. Node.prototype.getAnimationByName = function (name) {
  8005. for (var i = 0; i < this.animations.length; i++) {
  8006. var animation = this.animations[i];
  8007. if (animation.name === name) {
  8008. return animation;
  8009. }
  8010. }
  8011. return null;
  8012. };
  8013. Node.prototype.createAnimationRange = function (name, from, to) {
  8014. // check name not already in use
  8015. if (!this._ranges[name]) {
  8016. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8017. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8018. if (this.animations[i]) {
  8019. this.animations[i].createRange(name, from, to);
  8020. }
  8021. }
  8022. }
  8023. };
  8024. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8025. if (deleteFrames === void 0) { deleteFrames = true; }
  8026. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8027. if (this.animations[i]) {
  8028. this.animations[i].deleteRange(name, deleteFrames);
  8029. }
  8030. }
  8031. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8032. };
  8033. Node.prototype.getAnimationRange = function (name) {
  8034. return this._ranges[name];
  8035. };
  8036. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8037. var range = this.getAnimationRange(name);
  8038. if (!range) {
  8039. return null;
  8040. }
  8041. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8042. };
  8043. Node.prototype.serializeAnimationRanges = function () {
  8044. var serializationRanges = [];
  8045. for (var name in this._ranges) {
  8046. var range = {};
  8047. range.name = name;
  8048. range.from = this._ranges[name].from;
  8049. range.to = this._ranges[name].to;
  8050. serializationRanges.push(range);
  8051. }
  8052. return serializationRanges;
  8053. };
  8054. Node.prototype.dispose = function () {
  8055. this.parent = null;
  8056. };
  8057. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8058. if (parsedNode.ranges) {
  8059. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8060. var data = parsedNode.ranges[index];
  8061. node.createAnimationRange(data.name, data.from, data.to);
  8062. }
  8063. }
  8064. };
  8065. __decorate([
  8066. BABYLON.serialize()
  8067. ], Node.prototype, "name", void 0);
  8068. __decorate([
  8069. BABYLON.serialize()
  8070. ], Node.prototype, "id", void 0);
  8071. __decorate([
  8072. BABYLON.serialize()
  8073. ], Node.prototype, "uniqueId", void 0);
  8074. __decorate([
  8075. BABYLON.serialize()
  8076. ], Node.prototype, "state", void 0);
  8077. return Node;
  8078. })();
  8079. BABYLON.Node = Node;
  8080. })(BABYLON || (BABYLON = {}));
  8081. var BABYLON;
  8082. (function (BABYLON) {
  8083. var FilesInput = (function () {
  8084. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8085. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8086. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8087. this._engine = p_engine;
  8088. this._canvas = p_canvas;
  8089. this._currentScene = p_scene;
  8090. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8091. this._progressCallback = p_progressCallback;
  8092. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8093. this._textureLoadingCallback = p_textureLoadingCallback;
  8094. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8095. }
  8096. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8097. var _this = this;
  8098. if (p_elementToMonitor) {
  8099. this._elementToMonitor = p_elementToMonitor;
  8100. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8101. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8102. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8103. }
  8104. };
  8105. FilesInput.prototype.renderFunction = function () {
  8106. if (this._additionnalRenderLoopLogicCallback) {
  8107. this._additionnalRenderLoopLogicCallback();
  8108. }
  8109. if (this._currentScene) {
  8110. if (this._textureLoadingCallback) {
  8111. var remaining = this._currentScene.getWaitingItemsCount();
  8112. if (remaining > 0) {
  8113. this._textureLoadingCallback(remaining);
  8114. }
  8115. }
  8116. this._currentScene.render();
  8117. }
  8118. };
  8119. FilesInput.prototype.drag = function (e) {
  8120. e.stopPropagation();
  8121. e.preventDefault();
  8122. };
  8123. FilesInput.prototype.drop = function (eventDrop) {
  8124. eventDrop.stopPropagation();
  8125. eventDrop.preventDefault();
  8126. this.loadFiles(eventDrop);
  8127. };
  8128. FilesInput.prototype.loadFiles = function (event) {
  8129. if (this._startingProcessingFilesCallback)
  8130. this._startingProcessingFilesCallback();
  8131. // Handling data transfer via drag'n'drop
  8132. if (event && event.dataTransfer && event.dataTransfer.files) {
  8133. this._filesToLoad = event.dataTransfer.files;
  8134. }
  8135. // Handling files from input files
  8136. if (event && event.target && event.target.files) {
  8137. this._filesToLoad = event.target.files;
  8138. }
  8139. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8140. for (var i = 0; i < this._filesToLoad.length; i++) {
  8141. switch (this._filesToLoad[i].type) {
  8142. case "image/jpeg":
  8143. case "image/png":
  8144. case "image/bmp":
  8145. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8146. break;
  8147. case "image/targa":
  8148. case "image/vnd.ms-dds":
  8149. case "audio/wav":
  8150. case "audio/x-wav":
  8151. case "audio/mp3":
  8152. case "audio/mpeg":
  8153. case "audio/mpeg3":
  8154. case "audio/x-mpeg-3":
  8155. case "audio/ogg":
  8156. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8157. break;
  8158. default:
  8159. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8160. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8161. }
  8162. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8163. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8164. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8165. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8166. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8167. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8168. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8169. this._sceneFileToLoad = this._filesToLoad[i];
  8170. }
  8171. break;
  8172. }
  8173. }
  8174. this.reload();
  8175. }
  8176. };
  8177. FilesInput.prototype.reload = function () {
  8178. var _this = this;
  8179. var that = this;
  8180. // If a ".babylon" file has been provided
  8181. if (this._sceneFileToLoad) {
  8182. if (this._currentScene) {
  8183. if (BABYLON.Tools.errorsCount > 0) {
  8184. BABYLON.Tools.ClearLogCache();
  8185. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8186. }
  8187. this._engine.stopRenderLoop();
  8188. this._currentScene.dispose();
  8189. }
  8190. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8191. that._currentScene = newScene;
  8192. // Wait for textures and shaders to be ready
  8193. that._currentScene.executeWhenReady(function () {
  8194. // Attach camera to canvas inputs
  8195. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8196. that._currentScene.createDefaultCameraOrLight();
  8197. }
  8198. that._currentScene.activeCamera.attachControl(that._canvas);
  8199. if (that._sceneLoadedCallback) {
  8200. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8201. }
  8202. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8203. });
  8204. }, function (progress) {
  8205. if (_this._progressCallback) {
  8206. _this._progressCallback(progress);
  8207. }
  8208. });
  8209. }
  8210. else {
  8211. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8212. }
  8213. };
  8214. FilesInput.FilesTextures = new Array();
  8215. FilesInput.FilesToLoad = new Array();
  8216. return FilesInput;
  8217. })();
  8218. BABYLON.FilesInput = FilesInput;
  8219. })(BABYLON || (BABYLON = {}));
  8220. var BABYLON;
  8221. (function (BABYLON) {
  8222. var IntersectionInfo = (function () {
  8223. function IntersectionInfo(bu, bv, distance) {
  8224. this.bu = bu;
  8225. this.bv = bv;
  8226. this.distance = distance;
  8227. this.faceId = 0;
  8228. this.subMeshId = 0;
  8229. }
  8230. return IntersectionInfo;
  8231. })();
  8232. BABYLON.IntersectionInfo = IntersectionInfo;
  8233. var PickingInfo = (function () {
  8234. function PickingInfo() {
  8235. this.hit = false;
  8236. this.distance = 0;
  8237. this.pickedPoint = null;
  8238. this.pickedMesh = null;
  8239. this.bu = 0;
  8240. this.bv = 0;
  8241. this.faceId = -1;
  8242. this.subMeshId = 0;
  8243. this.pickedSprite = null;
  8244. }
  8245. // Methods
  8246. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8247. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8248. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8249. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8250. return null;
  8251. }
  8252. var indices = this.pickedMesh.getIndices();
  8253. var result;
  8254. if (useVerticesNormals) {
  8255. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8256. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8257. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8258. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8259. normal0 = normal0.scale(this.bu);
  8260. normal1 = normal1.scale(this.bv);
  8261. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8262. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8263. }
  8264. else {
  8265. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8266. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8267. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8268. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8269. var p1p2 = vertex1.subtract(vertex2);
  8270. var p3p2 = vertex3.subtract(vertex2);
  8271. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8272. }
  8273. if (useWorldCoordinates) {
  8274. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8275. }
  8276. return BABYLON.Vector3.Normalize(result);
  8277. };
  8278. PickingInfo.prototype.getTextureCoordinates = function () {
  8279. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8280. return null;
  8281. }
  8282. var indices = this.pickedMesh.getIndices();
  8283. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8284. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8285. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8286. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8287. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8288. uv1 = uv1.scale(this.bu);
  8289. uv2 = uv2.scale(this.bv);
  8290. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8291. };
  8292. return PickingInfo;
  8293. })();
  8294. BABYLON.PickingInfo = PickingInfo;
  8295. })(BABYLON || (BABYLON = {}));
  8296. var BABYLON;
  8297. (function (BABYLON) {
  8298. var BoundingSphere = (function () {
  8299. function BoundingSphere(minimum, maximum) {
  8300. this.minimum = minimum;
  8301. this.maximum = maximum;
  8302. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8303. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8304. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8305. this.radius = distance * 0.5;
  8306. this.centerWorld = BABYLON.Vector3.Zero();
  8307. this._update(BABYLON.Matrix.Identity());
  8308. }
  8309. // Methods
  8310. BoundingSphere.prototype._update = function (world) {
  8311. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8312. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8313. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8314. };
  8315. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8316. for (var i = 0; i < 6; i++) {
  8317. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8318. return false;
  8319. }
  8320. return true;
  8321. };
  8322. BoundingSphere.prototype.intersectsPoint = function (point) {
  8323. var x = this.centerWorld.x - point.x;
  8324. var y = this.centerWorld.y - point.y;
  8325. var z = this.centerWorld.z - point.z;
  8326. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8327. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8328. return false;
  8329. return true;
  8330. };
  8331. // Statics
  8332. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8333. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8334. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8335. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8336. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8337. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8338. return false;
  8339. return true;
  8340. };
  8341. return BoundingSphere;
  8342. })();
  8343. BABYLON.BoundingSphere = BoundingSphere;
  8344. })(BABYLON || (BABYLON = {}));
  8345. var BABYLON;
  8346. (function (BABYLON) {
  8347. var BoundingBox = (function () {
  8348. function BoundingBox(minimum, maximum) {
  8349. this.minimum = minimum;
  8350. this.maximum = maximum;
  8351. this.vectors = new Array();
  8352. this.vectorsWorld = new Array();
  8353. // Bounding vectors
  8354. this.vectors.push(this.minimum.clone());
  8355. this.vectors.push(this.maximum.clone());
  8356. this.vectors.push(this.minimum.clone());
  8357. this.vectors[2].x = this.maximum.x;
  8358. this.vectors.push(this.minimum.clone());
  8359. this.vectors[3].y = this.maximum.y;
  8360. this.vectors.push(this.minimum.clone());
  8361. this.vectors[4].z = this.maximum.z;
  8362. this.vectors.push(this.maximum.clone());
  8363. this.vectors[5].z = this.minimum.z;
  8364. this.vectors.push(this.maximum.clone());
  8365. this.vectors[6].x = this.minimum.x;
  8366. this.vectors.push(this.maximum.clone());
  8367. this.vectors[7].y = this.minimum.y;
  8368. // OBB
  8369. this.center = this.maximum.add(this.minimum).scale(0.5);
  8370. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8371. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8372. // World
  8373. for (var index = 0; index < this.vectors.length; index++) {
  8374. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8375. }
  8376. this.minimumWorld = BABYLON.Vector3.Zero();
  8377. this.maximumWorld = BABYLON.Vector3.Zero();
  8378. this._update(BABYLON.Matrix.Identity());
  8379. }
  8380. // Methods
  8381. BoundingBox.prototype.getWorldMatrix = function () {
  8382. return this._worldMatrix;
  8383. };
  8384. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8385. this._worldMatrix.copyFrom(matrix);
  8386. return this;
  8387. };
  8388. BoundingBox.prototype._update = function (world) {
  8389. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8390. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8391. for (var index = 0; index < this.vectors.length; index++) {
  8392. var v = this.vectorsWorld[index];
  8393. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8394. if (v.x < this.minimumWorld.x)
  8395. this.minimumWorld.x = v.x;
  8396. if (v.y < this.minimumWorld.y)
  8397. this.minimumWorld.y = v.y;
  8398. if (v.z < this.minimumWorld.z)
  8399. this.minimumWorld.z = v.z;
  8400. if (v.x > this.maximumWorld.x)
  8401. this.maximumWorld.x = v.x;
  8402. if (v.y > this.maximumWorld.y)
  8403. this.maximumWorld.y = v.y;
  8404. if (v.z > this.maximumWorld.z)
  8405. this.maximumWorld.z = v.z;
  8406. }
  8407. // OBB
  8408. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8409. this.center.scaleInPlace(0.5);
  8410. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8411. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8412. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8413. this._worldMatrix = world;
  8414. };
  8415. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8416. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8417. };
  8418. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8419. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8420. };
  8421. BoundingBox.prototype.intersectsPoint = function (point) {
  8422. var delta = -BABYLON.Epsilon;
  8423. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8424. return false;
  8425. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8426. return false;
  8427. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8428. return false;
  8429. return true;
  8430. };
  8431. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8432. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8433. };
  8434. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8435. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8436. return false;
  8437. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8438. return false;
  8439. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8440. return false;
  8441. return true;
  8442. };
  8443. // Statics
  8444. BoundingBox.Intersects = function (box0, box1) {
  8445. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8446. return false;
  8447. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8448. return false;
  8449. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8450. return false;
  8451. return true;
  8452. };
  8453. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8454. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8455. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8456. return (num <= (sphereRadius * sphereRadius));
  8457. };
  8458. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8459. for (var p = 0; p < 6; p++) {
  8460. for (var i = 0; i < 8; i++) {
  8461. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8462. return false;
  8463. }
  8464. }
  8465. }
  8466. return true;
  8467. };
  8468. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8469. for (var p = 0; p < 6; p++) {
  8470. var inCount = 8;
  8471. for (var i = 0; i < 8; i++) {
  8472. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8473. --inCount;
  8474. }
  8475. else {
  8476. break;
  8477. }
  8478. }
  8479. if (inCount === 0)
  8480. return false;
  8481. }
  8482. return true;
  8483. };
  8484. return BoundingBox;
  8485. })();
  8486. BABYLON.BoundingBox = BoundingBox;
  8487. })(BABYLON || (BABYLON = {}));
  8488. var BABYLON;
  8489. (function (BABYLON) {
  8490. var computeBoxExtents = function (axis, box) {
  8491. var p = BABYLON.Vector3.Dot(box.center, axis);
  8492. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8493. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8494. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8495. var r = r0 + r1 + r2;
  8496. return {
  8497. min: p - r,
  8498. max: p + r
  8499. };
  8500. };
  8501. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8502. var axisOverlap = function (axis, box0, box1) {
  8503. var result0 = computeBoxExtents(axis, box0);
  8504. var result1 = computeBoxExtents(axis, box1);
  8505. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8506. };
  8507. var BoundingInfo = (function () {
  8508. function BoundingInfo(minimum, maximum) {
  8509. this.minimum = minimum;
  8510. this.maximum = maximum;
  8511. this._isLocked = false;
  8512. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8513. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8514. }
  8515. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8516. get: function () {
  8517. return this._isLocked;
  8518. },
  8519. set: function (value) {
  8520. this._isLocked = value;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. // Methods
  8526. BoundingInfo.prototype.update = function (world) {
  8527. if (this._isLocked) {
  8528. return;
  8529. }
  8530. this.boundingBox._update(world);
  8531. this.boundingSphere._update(world);
  8532. };
  8533. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8534. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8535. return false;
  8536. return this.boundingBox.isInFrustum(frustumPlanes);
  8537. };
  8538. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8539. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8540. };
  8541. BoundingInfo.prototype._checkCollision = function (collider) {
  8542. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8543. };
  8544. BoundingInfo.prototype.intersectsPoint = function (point) {
  8545. if (!this.boundingSphere.centerWorld) {
  8546. return false;
  8547. }
  8548. if (!this.boundingSphere.intersectsPoint(point)) {
  8549. return false;
  8550. }
  8551. if (!this.boundingBox.intersectsPoint(point)) {
  8552. return false;
  8553. }
  8554. return true;
  8555. };
  8556. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8557. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8558. return false;
  8559. }
  8560. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8561. return false;
  8562. }
  8563. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8564. return false;
  8565. }
  8566. if (!precise) {
  8567. return true;
  8568. }
  8569. var box0 = this.boundingBox;
  8570. var box1 = boundingInfo.boundingBox;
  8571. if (!axisOverlap(box0.directions[0], box0, box1))
  8572. return false;
  8573. if (!axisOverlap(box0.directions[1], box0, box1))
  8574. return false;
  8575. if (!axisOverlap(box0.directions[2], box0, box1))
  8576. return false;
  8577. if (!axisOverlap(box1.directions[0], box0, box1))
  8578. return false;
  8579. if (!axisOverlap(box1.directions[1], box0, box1))
  8580. return false;
  8581. if (!axisOverlap(box1.directions[2], box0, box1))
  8582. return false;
  8583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8584. return false;
  8585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8586. return false;
  8587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8588. return false;
  8589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8590. return false;
  8591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8592. return false;
  8593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8594. return false;
  8595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8596. return false;
  8597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8598. return false;
  8599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8600. return false;
  8601. return true;
  8602. };
  8603. return BoundingInfo;
  8604. })();
  8605. BABYLON.BoundingInfo = BoundingInfo;
  8606. })(BABYLON || (BABYLON = {}));
  8607. var BABYLON;
  8608. (function (BABYLON) {
  8609. var Ray = (function () {
  8610. function Ray(origin, direction, length) {
  8611. if (length === void 0) { length = Number.MAX_VALUE; }
  8612. this.origin = origin;
  8613. this.direction = direction;
  8614. this.length = length;
  8615. }
  8616. // Methods
  8617. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8618. var d = 0.0;
  8619. var maxValue = Number.MAX_VALUE;
  8620. var inv;
  8621. var min;
  8622. var max;
  8623. var temp;
  8624. if (Math.abs(this.direction.x) < 0.0000001) {
  8625. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8626. return false;
  8627. }
  8628. }
  8629. else {
  8630. inv = 1.0 / this.direction.x;
  8631. min = (minimum.x - this.origin.x) * inv;
  8632. max = (maximum.x - this.origin.x) * inv;
  8633. if (max === -Infinity) {
  8634. max = Infinity;
  8635. }
  8636. if (min > max) {
  8637. temp = min;
  8638. min = max;
  8639. max = temp;
  8640. }
  8641. d = Math.max(min, d);
  8642. maxValue = Math.min(max, maxValue);
  8643. if (d > maxValue) {
  8644. return false;
  8645. }
  8646. }
  8647. if (Math.abs(this.direction.y) < 0.0000001) {
  8648. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8649. return false;
  8650. }
  8651. }
  8652. else {
  8653. inv = 1.0 / this.direction.y;
  8654. min = (minimum.y - this.origin.y) * inv;
  8655. max = (maximum.y - this.origin.y) * inv;
  8656. if (max === -Infinity) {
  8657. max = Infinity;
  8658. }
  8659. if (min > max) {
  8660. temp = min;
  8661. min = max;
  8662. max = temp;
  8663. }
  8664. d = Math.max(min, d);
  8665. maxValue = Math.min(max, maxValue);
  8666. if (d > maxValue) {
  8667. return false;
  8668. }
  8669. }
  8670. if (Math.abs(this.direction.z) < 0.0000001) {
  8671. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8672. return false;
  8673. }
  8674. }
  8675. else {
  8676. inv = 1.0 / this.direction.z;
  8677. min = (minimum.z - this.origin.z) * inv;
  8678. max = (maximum.z - this.origin.z) * inv;
  8679. if (max === -Infinity) {
  8680. max = Infinity;
  8681. }
  8682. if (min > max) {
  8683. temp = min;
  8684. min = max;
  8685. max = temp;
  8686. }
  8687. d = Math.max(min, d);
  8688. maxValue = Math.min(max, maxValue);
  8689. if (d > maxValue) {
  8690. return false;
  8691. }
  8692. }
  8693. return true;
  8694. };
  8695. Ray.prototype.intersectsBox = function (box) {
  8696. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8697. };
  8698. Ray.prototype.intersectsSphere = function (sphere) {
  8699. var x = sphere.center.x - this.origin.x;
  8700. var y = sphere.center.y - this.origin.y;
  8701. var z = sphere.center.z - this.origin.z;
  8702. var pyth = (x * x) + (y * y) + (z * z);
  8703. var rr = sphere.radius * sphere.radius;
  8704. if (pyth <= rr) {
  8705. return true;
  8706. }
  8707. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8708. if (dot < 0.0) {
  8709. return false;
  8710. }
  8711. var temp = pyth - (dot * dot);
  8712. return temp <= rr;
  8713. };
  8714. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8715. if (!this._edge1) {
  8716. this._edge1 = BABYLON.Vector3.Zero();
  8717. this._edge2 = BABYLON.Vector3.Zero();
  8718. this._pvec = BABYLON.Vector3.Zero();
  8719. this._tvec = BABYLON.Vector3.Zero();
  8720. this._qvec = BABYLON.Vector3.Zero();
  8721. }
  8722. vertex1.subtractToRef(vertex0, this._edge1);
  8723. vertex2.subtractToRef(vertex0, this._edge2);
  8724. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8725. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8726. if (det === 0) {
  8727. return null;
  8728. }
  8729. var invdet = 1 / det;
  8730. this.origin.subtractToRef(vertex0, this._tvec);
  8731. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8732. if (bu < 0 || bu > 1.0) {
  8733. return null;
  8734. }
  8735. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8736. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8737. if (bv < 0 || bu + bv > 1.0) {
  8738. return null;
  8739. }
  8740. //check if the distance is longer than the predefined length.
  8741. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8742. if (distance > this.length) {
  8743. return null;
  8744. }
  8745. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8746. };
  8747. Ray.prototype.intersectsPlane = function (plane) {
  8748. var distance;
  8749. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8750. if (Math.abs(result1) < 9.99999997475243E-07) {
  8751. return null;
  8752. }
  8753. else {
  8754. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8755. distance = (-plane.d - result2) / result1;
  8756. if (distance < 0.0) {
  8757. if (distance < -9.99999997475243E-07) {
  8758. return null;
  8759. }
  8760. else {
  8761. return 0;
  8762. }
  8763. }
  8764. return distance;
  8765. }
  8766. };
  8767. /**
  8768. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8769. * @param sega the first point of the segment to test the intersection against
  8770. * @param segb the second point of the segment to test the intersection against
  8771. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8772. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8773. */
  8774. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8775. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8776. var u = segb.subtract(sega);
  8777. var v = rsegb.subtract(this.origin);
  8778. var w = sega.subtract(this.origin);
  8779. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8780. var b = BABYLON.Vector3.Dot(u, v);
  8781. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8782. var d = BABYLON.Vector3.Dot(u, w);
  8783. var e = BABYLON.Vector3.Dot(v, w);
  8784. var D = a * c - b * b; // always >= 0
  8785. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8786. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8787. // compute the line parameters of the two closest points
  8788. if (D < Ray.smallnum) {
  8789. sN = 0.0; // force using point P0 on segment S1
  8790. sD = 1.0; // to prevent possible division by 0.0 later
  8791. tN = e;
  8792. tD = c;
  8793. }
  8794. else {
  8795. sN = (b * e - c * d);
  8796. tN = (a * e - b * d);
  8797. if (sN < 0.0) {
  8798. sN = 0.0;
  8799. tN = e;
  8800. tD = c;
  8801. }
  8802. else if (sN > sD) {
  8803. sN = sD;
  8804. tN = e + b;
  8805. tD = c;
  8806. }
  8807. }
  8808. if (tN < 0.0) {
  8809. tN = 0.0;
  8810. // recompute sc for this edge
  8811. if (-d < 0.0) {
  8812. sN = 0.0;
  8813. }
  8814. else if (-d > a)
  8815. sN = sD;
  8816. else {
  8817. sN = -d;
  8818. sD = a;
  8819. }
  8820. }
  8821. else if (tN > tD) {
  8822. tN = tD;
  8823. // recompute sc for this edge
  8824. if ((-d + b) < 0.0) {
  8825. sN = 0;
  8826. }
  8827. else if ((-d + b) > a) {
  8828. sN = sD;
  8829. }
  8830. else {
  8831. sN = (-d + b);
  8832. sD = a;
  8833. }
  8834. }
  8835. // finally do the division to get sc and tc
  8836. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8837. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8838. // get the difference of the two closest points
  8839. var qtc = v.multiplyByFloats(tc, tc, tc);
  8840. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8841. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8842. if (isIntersected) {
  8843. return qtc.length();
  8844. }
  8845. return -1;
  8846. };
  8847. // Statics
  8848. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8849. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8850. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8851. var direction = end.subtract(start);
  8852. direction.normalize();
  8853. return new Ray(start, direction);
  8854. };
  8855. /**
  8856. * 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
  8857. * transformed to the given world matrix.
  8858. * @param origin The origin point
  8859. * @param end The end point
  8860. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8861. */
  8862. Ray.CreateNewFromTo = function (origin, end, world) {
  8863. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8864. var direction = end.subtract(origin);
  8865. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8866. direction.normalize();
  8867. return Ray.Transform(new Ray(origin, direction, length), world);
  8868. };
  8869. Ray.Transform = function (ray, matrix) {
  8870. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8871. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8872. newDirection.normalize();
  8873. return new Ray(newOrigin, newDirection, ray.length);
  8874. };
  8875. Ray.smallnum = 0.00000001;
  8876. Ray.rayl = 10e8;
  8877. return Ray;
  8878. })();
  8879. BABYLON.Ray = Ray;
  8880. })(BABYLON || (BABYLON = {}));
  8881. var BABYLON;
  8882. (function (BABYLON) {
  8883. var AbstractMesh = (function (_super) {
  8884. __extends(AbstractMesh, _super);
  8885. // Constructor
  8886. function AbstractMesh(name, scene) {
  8887. var _this = this;
  8888. _super.call(this, name, scene);
  8889. // Events
  8890. /**
  8891. * An event triggered when the mesh is disposed.
  8892. * @type {BABYLON.Observable}
  8893. */
  8894. this.onDisposeObservable = new BABYLON.Observable();
  8895. /**
  8896. * An event triggered when this mesh collides with another one
  8897. * @type {BABYLON.Observable}
  8898. */
  8899. this.onCollideObservable = new BABYLON.Observable();
  8900. /**
  8901. * An event triggered when the collision's position changes
  8902. * @type {BABYLON.Observable}
  8903. */
  8904. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8905. /**
  8906. * An event triggered after the world matrix is updated
  8907. * @type {BABYLON.Observable}
  8908. */
  8909. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8910. // Properties
  8911. this.definedFacingForward = true; // orientation for POV movement & rotation
  8912. this.position = new BABYLON.Vector3(0, 0, 0);
  8913. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8914. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8915. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8916. this.visibility = 1.0;
  8917. this.alphaIndex = Number.MAX_VALUE;
  8918. this.infiniteDistance = false;
  8919. this.isVisible = true;
  8920. this.isPickable = true;
  8921. this.showBoundingBox = false;
  8922. this.showSubMeshesBoundingBox = false;
  8923. this.isBlocker = false;
  8924. this.renderingGroupId = 0;
  8925. this.receiveShadows = false;
  8926. this.renderOutline = false;
  8927. this.outlineColor = BABYLON.Color3.Red();
  8928. this.outlineWidth = 0.02;
  8929. this.renderOverlay = false;
  8930. this.overlayColor = BABYLON.Color3.Red();
  8931. this.overlayAlpha = 0.5;
  8932. this.hasVertexAlpha = false;
  8933. this.useVertexColors = true;
  8934. this.applyFog = true;
  8935. this.computeBonesUsingShaders = true;
  8936. this.scalingDeterminant = 1;
  8937. this.numBoneInfluencers = 4;
  8938. this.useOctreeForRenderingSelection = true;
  8939. this.useOctreeForPicking = true;
  8940. this.useOctreeForCollisions = true;
  8941. this.layerMask = 0x0FFFFFFF;
  8942. this.alwaysSelectAsActiveMesh = false;
  8943. // Collisions
  8944. this._checkCollisions = false;
  8945. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8946. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8947. this._collider = new BABYLON.Collider();
  8948. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8949. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8950. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8951. // Edges
  8952. this.edgesWidth = 1;
  8953. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8954. // Cache
  8955. this._localWorld = BABYLON.Matrix.Zero();
  8956. this._worldMatrix = BABYLON.Matrix.Zero();
  8957. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8958. this._absolutePosition = BABYLON.Vector3.Zero();
  8959. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8960. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8961. this._isDirty = false;
  8962. this._pivotMatrix = BABYLON.Matrix.Identity();
  8963. this._isDisposed = false;
  8964. this._renderId = 0;
  8965. this._intersectionsInProgress = new Array();
  8966. this._isWorldMatrixFrozen = false;
  8967. this._unIndexed = false;
  8968. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8969. if (collidedMesh === void 0) { collidedMesh = null; }
  8970. //TODO move this to the collision coordinator!
  8971. if (_this.getScene().workerCollisions)
  8972. newPosition.multiplyInPlace(_this._collider.radius);
  8973. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8974. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8975. _this.position.addInPlace(_this._diffPositionForCollisions);
  8976. }
  8977. if (collidedMesh) {
  8978. _this.onCollideObservable.notifyObservers(collidedMesh);
  8979. }
  8980. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8981. };
  8982. scene.addMesh(this);
  8983. }
  8984. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8985. get: function () {
  8986. return AbstractMesh._BILLBOARDMODE_NONE;
  8987. },
  8988. enumerable: true,
  8989. configurable: true
  8990. });
  8991. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8992. get: function () {
  8993. return AbstractMesh._BILLBOARDMODE_X;
  8994. },
  8995. enumerable: true,
  8996. configurable: true
  8997. });
  8998. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8999. get: function () {
  9000. return AbstractMesh._BILLBOARDMODE_Y;
  9001. },
  9002. enumerable: true,
  9003. configurable: true
  9004. });
  9005. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9006. get: function () {
  9007. return AbstractMesh._BILLBOARDMODE_Z;
  9008. },
  9009. enumerable: true,
  9010. configurable: true
  9011. });
  9012. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9013. get: function () {
  9014. return AbstractMesh._BILLBOARDMODE_ALL;
  9015. },
  9016. enumerable: true,
  9017. configurable: true
  9018. });
  9019. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9020. set: function (callback) {
  9021. if (this._onDisposeObserver) {
  9022. this.onDisposeObservable.remove(this._onDisposeObserver);
  9023. }
  9024. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9030. set: function (callback) {
  9031. if (this._onCollideObserver) {
  9032. this.onCollideObservable.remove(this._onCollideObserver);
  9033. }
  9034. this._onCollideObserver = this.onCollideObservable.add(callback);
  9035. },
  9036. enumerable: true,
  9037. configurable: true
  9038. });
  9039. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9040. set: function (callback) {
  9041. if (this._onCollisionPositionChangeObserver) {
  9042. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9043. }
  9044. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9045. },
  9046. enumerable: true,
  9047. configurable: true
  9048. });
  9049. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9050. get: function () {
  9051. return this._skeleton;
  9052. },
  9053. set: function (value) {
  9054. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9055. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9056. }
  9057. if (value && value.needInitialSkinMatrix) {
  9058. value._registerMeshWithPoseMatrix(this);
  9059. }
  9060. this._skeleton = value;
  9061. if (!this._skeleton) {
  9062. this._bonesTransformMatrices = null;
  9063. }
  9064. },
  9065. enumerable: true,
  9066. configurable: true
  9067. });
  9068. /**
  9069. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9070. */
  9071. AbstractMesh.prototype.toString = function (fullDetails) {
  9072. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9073. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9074. if (this._skeleton) {
  9075. ret += ", skeleton: " + this._skeleton.name;
  9076. }
  9077. if (fullDetails) {
  9078. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9079. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9080. }
  9081. return ret;
  9082. };
  9083. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9084. /**
  9085. * Getting the rotation object.
  9086. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9087. */
  9088. get: function () {
  9089. return this._rotation;
  9090. },
  9091. set: function (newRotation) {
  9092. this._rotation = newRotation;
  9093. },
  9094. enumerable: true,
  9095. configurable: true
  9096. });
  9097. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9098. get: function () {
  9099. return this._scaling;
  9100. },
  9101. set: function (newScaling) {
  9102. this._scaling = newScaling;
  9103. if (this.physicsImpostor) {
  9104. this.physicsImpostor.forceUpdate();
  9105. }
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9111. get: function () {
  9112. return this._rotationQuaternion;
  9113. },
  9114. set: function (quaternion) {
  9115. this._rotationQuaternion = quaternion;
  9116. //reset the rotation vector.
  9117. if (quaternion && this.rotation.length()) {
  9118. this.rotation.copyFromFloats(0, 0, 0);
  9119. }
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. // Methods
  9125. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9126. this._poseMatrix.copyFrom(matrix);
  9127. };
  9128. AbstractMesh.prototype.getPoseMatrix = function () {
  9129. return this._poseMatrix;
  9130. };
  9131. AbstractMesh.prototype.disableEdgesRendering = function () {
  9132. if (this._edgesRenderer !== undefined) {
  9133. this._edgesRenderer.dispose();
  9134. this._edgesRenderer = undefined;
  9135. }
  9136. };
  9137. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9138. if (epsilon === void 0) { epsilon = 0.95; }
  9139. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9140. this.disableEdgesRendering();
  9141. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9142. };
  9143. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9144. get: function () {
  9145. return false;
  9146. },
  9147. enumerable: true,
  9148. configurable: true
  9149. });
  9150. AbstractMesh.prototype.getLOD = function (camera) {
  9151. return this;
  9152. };
  9153. AbstractMesh.prototype.getTotalVertices = function () {
  9154. return 0;
  9155. };
  9156. AbstractMesh.prototype.getIndices = function () {
  9157. return null;
  9158. };
  9159. AbstractMesh.prototype.getVerticesData = function (kind) {
  9160. return null;
  9161. };
  9162. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9163. return false;
  9164. };
  9165. AbstractMesh.prototype.getBoundingInfo = function () {
  9166. if (this._masterMesh) {
  9167. return this._masterMesh.getBoundingInfo();
  9168. }
  9169. if (!this._boundingInfo) {
  9170. this._updateBoundingInfo();
  9171. }
  9172. return this._boundingInfo;
  9173. };
  9174. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9175. get: function () {
  9176. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9177. },
  9178. enumerable: true,
  9179. configurable: true
  9180. });
  9181. AbstractMesh.prototype._preActivate = function () {
  9182. };
  9183. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9184. };
  9185. AbstractMesh.prototype._activate = function (renderId) {
  9186. this._renderId = renderId;
  9187. };
  9188. AbstractMesh.prototype.getWorldMatrix = function () {
  9189. if (this._masterMesh) {
  9190. return this._masterMesh.getWorldMatrix();
  9191. }
  9192. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9193. this.computeWorldMatrix();
  9194. }
  9195. return this._worldMatrix;
  9196. };
  9197. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9198. get: function () {
  9199. return this._worldMatrix;
  9200. },
  9201. enumerable: true,
  9202. configurable: true
  9203. });
  9204. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9205. get: function () {
  9206. return this._absolutePosition;
  9207. },
  9208. enumerable: true,
  9209. configurable: true
  9210. });
  9211. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9212. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9213. this.computeWorldMatrix(true);
  9214. this._isWorldMatrixFrozen = true;
  9215. };
  9216. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9217. this._isWorldMatrixFrozen = false;
  9218. this.computeWorldMatrix(true);
  9219. };
  9220. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9221. get: function () {
  9222. return this._isWorldMatrixFrozen;
  9223. },
  9224. enumerable: true,
  9225. configurable: true
  9226. });
  9227. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9228. axis.normalize();
  9229. if (!this.rotationQuaternion) {
  9230. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9231. this.rotation = BABYLON.Vector3.Zero();
  9232. }
  9233. var rotationQuaternion;
  9234. if (!space || space === BABYLON.Space.LOCAL) {
  9235. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9236. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9237. }
  9238. else {
  9239. if (this.parent) {
  9240. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9241. invertParentWorldMatrix.invert();
  9242. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9243. }
  9244. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9245. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9246. }
  9247. };
  9248. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9249. var displacementVector = axis.scale(distance);
  9250. if (!space || space === BABYLON.Space.LOCAL) {
  9251. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9252. this.setPositionWithLocalVector(tempV3);
  9253. }
  9254. else {
  9255. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9256. }
  9257. };
  9258. AbstractMesh.prototype.getAbsolutePosition = function () {
  9259. this.computeWorldMatrix();
  9260. return this._absolutePosition;
  9261. };
  9262. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9263. if (!absolutePosition) {
  9264. return;
  9265. }
  9266. var absolutePositionX;
  9267. var absolutePositionY;
  9268. var absolutePositionZ;
  9269. if (absolutePosition.x === undefined) {
  9270. if (arguments.length < 3) {
  9271. return;
  9272. }
  9273. absolutePositionX = arguments[0];
  9274. absolutePositionY = arguments[1];
  9275. absolutePositionZ = arguments[2];
  9276. }
  9277. else {
  9278. absolutePositionX = absolutePosition.x;
  9279. absolutePositionY = absolutePosition.y;
  9280. absolutePositionZ = absolutePosition.z;
  9281. }
  9282. if (this.parent) {
  9283. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9284. invertParentWorldMatrix.invert();
  9285. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9286. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9287. }
  9288. else {
  9289. this.position.x = absolutePositionX;
  9290. this.position.y = absolutePositionY;
  9291. this.position.z = absolutePositionZ;
  9292. }
  9293. };
  9294. // ================================== Point of View Movement =================================
  9295. /**
  9296. * Perform relative position change from the point of view of behind the front of the mesh.
  9297. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9298. * Supports definition of mesh facing forward or backward.
  9299. * @param {number} amountRight
  9300. * @param {number} amountUp
  9301. * @param {number} amountForward
  9302. */
  9303. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9304. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9305. };
  9306. /**
  9307. * Calculate relative position change from the point of view of behind the front of the mesh.
  9308. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9309. * Supports definition of mesh facing forward or backward.
  9310. * @param {number} amountRight
  9311. * @param {number} amountUp
  9312. * @param {number} amountForward
  9313. */
  9314. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9315. var rotMatrix = new BABYLON.Matrix();
  9316. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9317. rotQuaternion.toRotationMatrix(rotMatrix);
  9318. var translationDelta = BABYLON.Vector3.Zero();
  9319. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9320. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9321. return translationDelta;
  9322. };
  9323. // ================================== Point of View Rotation =================================
  9324. /**
  9325. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9326. * Supports definition of mesh facing forward or backward.
  9327. * @param {number} flipBack
  9328. * @param {number} twirlClockwise
  9329. * @param {number} tiltRight
  9330. */
  9331. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9332. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9333. };
  9334. /**
  9335. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9336. * Supports definition of mesh facing forward or backward.
  9337. * @param {number} flipBack
  9338. * @param {number} twirlClockwise
  9339. * @param {number} tiltRight
  9340. */
  9341. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9342. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9343. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9344. };
  9345. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9346. this._pivotMatrix = matrix;
  9347. this._cache.pivotMatrixUpdated = true;
  9348. };
  9349. AbstractMesh.prototype.getPivotMatrix = function () {
  9350. return this._pivotMatrix;
  9351. };
  9352. AbstractMesh.prototype._isSynchronized = function () {
  9353. if (this._isDirty) {
  9354. return false;
  9355. }
  9356. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9357. return false;
  9358. if (this._cache.pivotMatrixUpdated) {
  9359. return false;
  9360. }
  9361. if (this.infiniteDistance) {
  9362. return false;
  9363. }
  9364. if (!this._cache.position.equals(this.position))
  9365. return false;
  9366. if (this.rotationQuaternion) {
  9367. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9368. return false;
  9369. }
  9370. else {
  9371. if (!this._cache.rotation.equals(this.rotation))
  9372. return false;
  9373. }
  9374. if (!this._cache.scaling.equals(this.scaling))
  9375. return false;
  9376. return true;
  9377. };
  9378. AbstractMesh.prototype._initCache = function () {
  9379. _super.prototype._initCache.call(this);
  9380. this._cache.localMatrixUpdated = false;
  9381. this._cache.position = BABYLON.Vector3.Zero();
  9382. this._cache.scaling = BABYLON.Vector3.Zero();
  9383. this._cache.rotation = BABYLON.Vector3.Zero();
  9384. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9385. this._cache.billboardMode = -1;
  9386. };
  9387. AbstractMesh.prototype.markAsDirty = function (property) {
  9388. if (property === "rotation") {
  9389. this.rotationQuaternion = null;
  9390. }
  9391. this._currentRenderId = Number.MAX_VALUE;
  9392. this._isDirty = true;
  9393. };
  9394. AbstractMesh.prototype._updateBoundingInfo = function () {
  9395. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9396. this._boundingInfo.update(this.worldMatrixFromCache);
  9397. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9398. };
  9399. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9400. if (!this.subMeshes) {
  9401. return;
  9402. }
  9403. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9404. var subMesh = this.subMeshes[subIndex];
  9405. if (!subMesh.IsGlobal) {
  9406. subMesh.updateBoundingInfo(matrix);
  9407. }
  9408. }
  9409. };
  9410. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9411. if (this._isWorldMatrixFrozen) {
  9412. return this._worldMatrix;
  9413. }
  9414. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9415. this._currentRenderId = this.getScene().getRenderId();
  9416. return this._worldMatrix;
  9417. }
  9418. this._cache.position.copyFrom(this.position);
  9419. this._cache.scaling.copyFrom(this.scaling);
  9420. this._cache.pivotMatrixUpdated = false;
  9421. this._cache.billboardMode = this.billboardMode;
  9422. this._currentRenderId = this.getScene().getRenderId();
  9423. this._isDirty = false;
  9424. // Scaling
  9425. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9426. // Rotation
  9427. //rotate, if quaternion is set and rotation was used
  9428. if (this.rotationQuaternion) {
  9429. var len = this.rotation.length();
  9430. if (len) {
  9431. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9432. this.rotation.copyFromFloats(0, 0, 0);
  9433. }
  9434. }
  9435. if (this.rotationQuaternion) {
  9436. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9437. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9438. }
  9439. else {
  9440. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9441. this._cache.rotation.copyFrom(this.rotation);
  9442. }
  9443. // Translation
  9444. if (this.infiniteDistance && !this.parent) {
  9445. var camera = this.getScene().activeCamera;
  9446. if (camera) {
  9447. var cameraWorldMatrix = camera.getWorldMatrix();
  9448. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9449. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9450. }
  9451. }
  9452. else {
  9453. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9454. }
  9455. // Composing transformations
  9456. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9457. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9458. // Billboarding
  9459. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9460. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9461. var localPosition = BABYLON.Tmp.Vector3[0];
  9462. if (this.parent && this.parent.getWorldMatrix) {
  9463. this._markSyncedWithParent();
  9464. var parentMatrix;
  9465. if (this._meshToBoneReferal) {
  9466. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9467. parentMatrix = BABYLON.Tmp.Matrix[6];
  9468. }
  9469. else {
  9470. parentMatrix = this.parent.getWorldMatrix();
  9471. }
  9472. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9473. localPosition = BABYLON.Tmp.Vector3[1];
  9474. }
  9475. var zero = this.getScene().activeCamera.globalPosition.clone();
  9476. if (this.parent && this.parent.position) {
  9477. localPosition.addInPlace(this.parent.position);
  9478. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9479. }
  9480. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9481. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9482. zero.x = localPosition.x + BABYLON.Epsilon;
  9483. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9484. zero.y = localPosition.y + BABYLON.Epsilon;
  9485. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9486. zero.z = localPosition.z + BABYLON.Epsilon;
  9487. }
  9488. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9489. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9490. BABYLON.Tmp.Matrix[3].invert();
  9491. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9492. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9493. }
  9494. // Local world
  9495. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9496. // Parent
  9497. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9498. this._markSyncedWithParent();
  9499. if (this._meshToBoneReferal) {
  9500. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9501. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9502. }
  9503. else {
  9504. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9505. }
  9506. }
  9507. else {
  9508. this._worldMatrix.copyFrom(this._localWorld);
  9509. }
  9510. // Bounding info
  9511. this._updateBoundingInfo();
  9512. // Absolute position
  9513. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9514. // Callbacks
  9515. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9516. if (!this._poseMatrix) {
  9517. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9518. }
  9519. return this._worldMatrix;
  9520. };
  9521. /**
  9522. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9523. * @param func: callback function to add
  9524. */
  9525. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9526. this.onAfterWorldMatrixUpdateObservable.add(func);
  9527. };
  9528. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9529. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9530. };
  9531. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9532. this.computeWorldMatrix();
  9533. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9534. };
  9535. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9536. this.computeWorldMatrix();
  9537. var invLocalWorldMatrix = this._localWorld.clone();
  9538. invLocalWorldMatrix.invert();
  9539. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9540. };
  9541. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9542. this.computeWorldMatrix(true);
  9543. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9544. };
  9545. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9546. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9547. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9548. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9549. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9550. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9551. /// <returns>Mesh oriented towards targetMesh</returns>
  9552. yawCor = yawCor || 0; // default to zero if undefined
  9553. pitchCor = pitchCor || 0;
  9554. rollCor = rollCor || 0;
  9555. var dv = targetPoint.subtract(this.position);
  9556. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9557. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9558. var pitch = Math.atan2(dv.y, len);
  9559. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9560. };
  9561. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9562. this._meshToBoneReferal = affectedMesh;
  9563. this.parent = bone;
  9564. if (bone.getWorldMatrix().determinant() < 0) {
  9565. this.scalingDeterminant *= -1;
  9566. }
  9567. };
  9568. AbstractMesh.prototype.detachFromBone = function () {
  9569. if (this.parent.getWorldMatrix().determinant() < 0) {
  9570. this.scalingDeterminant *= -1;
  9571. }
  9572. this._meshToBoneReferal = null;
  9573. this.parent = null;
  9574. };
  9575. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9576. return this._boundingInfo.isInFrustum(frustumPlanes);
  9577. };
  9578. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9579. if (!camera) {
  9580. camera = this.getScene().activeCamera;
  9581. }
  9582. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9583. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9584. return false;
  9585. }
  9586. return true;
  9587. };
  9588. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9589. if (!this._boundingInfo || !mesh._boundingInfo) {
  9590. return false;
  9591. }
  9592. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9593. };
  9594. AbstractMesh.prototype.intersectsPoint = function (point) {
  9595. if (!this._boundingInfo) {
  9596. return false;
  9597. }
  9598. return this._boundingInfo.intersectsPoint(point);
  9599. };
  9600. // Physics
  9601. /**
  9602. * @Deprecated. Use new PhysicsImpostor instead.
  9603. * */
  9604. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9605. //legacy support
  9606. if (impostor.impostor) {
  9607. options = impostor;
  9608. impostor = impostor.impostor;
  9609. }
  9610. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9611. return this.physicsImpostor.physicsBody;
  9612. };
  9613. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9614. return this.physicsImpostor;
  9615. };
  9616. /**
  9617. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9618. */
  9619. AbstractMesh.prototype.getPhysicsMass = function () {
  9620. return this.physicsImpostor.getParam("mass");
  9621. };
  9622. /**
  9623. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9624. */
  9625. AbstractMesh.prototype.getPhysicsFriction = function () {
  9626. return this.physicsImpostor.getParam("friction");
  9627. };
  9628. /**
  9629. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9630. */
  9631. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9632. return this.physicsImpostor.getParam("resitution");
  9633. };
  9634. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9635. if (!camera) {
  9636. camera = this.getScene().activeCamera;
  9637. }
  9638. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9639. };
  9640. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9641. if (!camera) {
  9642. camera = this.getScene().activeCamera;
  9643. }
  9644. return this.absolutePosition.subtract(camera.position).length();
  9645. };
  9646. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9647. if (!this.physicsImpostor) {
  9648. return;
  9649. }
  9650. this.physicsImpostor.applyImpulse(force, contactPoint);
  9651. };
  9652. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9653. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9654. return;
  9655. }
  9656. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9657. mainPivot: pivot1,
  9658. connectedPivot: pivot2,
  9659. nativeParams: options
  9660. });
  9661. };
  9662. /**
  9663. * @Deprecated
  9664. */
  9665. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9666. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9667. this.updatePhysicsBody();
  9668. };
  9669. /**
  9670. * @Deprecated
  9671. * Calling this function is not needed anymore.
  9672. * The physics engine takes care of transofmration automatically.
  9673. */
  9674. AbstractMesh.prototype.updatePhysicsBody = function () {
  9675. //Unneeded
  9676. };
  9677. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9678. // Collisions
  9679. get: function () {
  9680. return this._checkCollisions;
  9681. },
  9682. set: function (collisionEnabled) {
  9683. this._checkCollisions = collisionEnabled;
  9684. if (this.getScene().workerCollisions) {
  9685. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9686. }
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9692. var globalPosition = this.getAbsolutePosition();
  9693. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9694. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9695. this._collider.radius = this.ellipsoid;
  9696. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9697. };
  9698. // Submeshes octree
  9699. /**
  9700. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9701. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9702. */
  9703. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9704. if (maxCapacity === void 0) { maxCapacity = 64; }
  9705. if (maxDepth === void 0) { maxDepth = 2; }
  9706. if (!this._submeshesOctree) {
  9707. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9708. }
  9709. this.computeWorldMatrix(true);
  9710. // Update octree
  9711. var bbox = this.getBoundingInfo().boundingBox;
  9712. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9713. return this._submeshesOctree;
  9714. };
  9715. // Collisions
  9716. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9717. this._generatePointsArray();
  9718. // Transformation
  9719. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9720. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9721. subMesh._lastColliderWorldVertices = [];
  9722. subMesh._trianglePlanes = [];
  9723. var start = subMesh.verticesStart;
  9724. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9725. for (var i = start; i < end; i++) {
  9726. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9727. }
  9728. }
  9729. // Collide
  9730. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9731. if (collider.collisionFound) {
  9732. collider.collidedMesh = this;
  9733. }
  9734. };
  9735. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9736. var subMeshes;
  9737. var len;
  9738. // Octrees
  9739. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9740. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9741. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9742. len = intersections.length;
  9743. subMeshes = intersections.data;
  9744. }
  9745. else {
  9746. subMeshes = this.subMeshes;
  9747. len = subMeshes.length;
  9748. }
  9749. for (var index = 0; index < len; index++) {
  9750. var subMesh = subMeshes[index];
  9751. // Bounding test
  9752. if (len > 1 && !subMesh._checkCollision(collider))
  9753. continue;
  9754. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9755. }
  9756. };
  9757. AbstractMesh.prototype._checkCollision = function (collider) {
  9758. // Bounding box test
  9759. if (!this._boundingInfo._checkCollision(collider))
  9760. return;
  9761. // Transformation matrix
  9762. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9763. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9764. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9765. };
  9766. // Picking
  9767. AbstractMesh.prototype._generatePointsArray = function () {
  9768. return false;
  9769. };
  9770. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9771. var pickingInfo = new BABYLON.PickingInfo();
  9772. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9773. return pickingInfo;
  9774. }
  9775. if (!this._generatePointsArray()) {
  9776. return pickingInfo;
  9777. }
  9778. var intersectInfo = null;
  9779. // Octrees
  9780. var subMeshes;
  9781. var len;
  9782. if (this._submeshesOctree && this.useOctreeForPicking) {
  9783. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9784. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9785. len = intersections.length;
  9786. subMeshes = intersections.data;
  9787. }
  9788. else {
  9789. subMeshes = this.subMeshes;
  9790. len = subMeshes.length;
  9791. }
  9792. for (var index = 0; index < len; index++) {
  9793. var subMesh = subMeshes[index];
  9794. // Bounding test
  9795. if (len > 1 && !subMesh.canIntersects(ray))
  9796. continue;
  9797. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9798. if (currentIntersectInfo) {
  9799. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9800. intersectInfo = currentIntersectInfo;
  9801. intersectInfo.subMeshId = index;
  9802. if (fastCheck) {
  9803. break;
  9804. }
  9805. }
  9806. }
  9807. }
  9808. if (intersectInfo) {
  9809. // Get picked point
  9810. var world = this.getWorldMatrix();
  9811. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9812. var direction = ray.direction.clone();
  9813. direction = direction.scale(intersectInfo.distance);
  9814. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9815. var pickedPoint = worldOrigin.add(worldDirection);
  9816. // Return result
  9817. pickingInfo.hit = true;
  9818. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9819. pickingInfo.pickedPoint = pickedPoint;
  9820. pickingInfo.pickedMesh = this;
  9821. pickingInfo.bu = intersectInfo.bu;
  9822. pickingInfo.bv = intersectInfo.bv;
  9823. pickingInfo.faceId = intersectInfo.faceId;
  9824. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9825. return pickingInfo;
  9826. }
  9827. return pickingInfo;
  9828. };
  9829. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9830. return null;
  9831. };
  9832. AbstractMesh.prototype.releaseSubMeshes = function () {
  9833. if (this.subMeshes) {
  9834. while (this.subMeshes.length) {
  9835. this.subMeshes[0].dispose();
  9836. }
  9837. }
  9838. else {
  9839. this.subMeshes = new Array();
  9840. }
  9841. };
  9842. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9843. var _this = this;
  9844. var index;
  9845. // Action manager
  9846. if (this.actionManager) {
  9847. this.actionManager.dispose();
  9848. this.actionManager = null;
  9849. }
  9850. // Skeleton
  9851. this.skeleton = null;
  9852. // Animations
  9853. this.getScene().stopAnimation(this);
  9854. // Physics
  9855. if (this.physicsImpostor) {
  9856. this.physicsImpostor.dispose();
  9857. }
  9858. // Intersections in progress
  9859. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9860. var other = this._intersectionsInProgress[index];
  9861. var pos = other._intersectionsInProgress.indexOf(this);
  9862. other._intersectionsInProgress.splice(pos, 1);
  9863. }
  9864. this._intersectionsInProgress = [];
  9865. // Lights
  9866. var lights = this.getScene().lights;
  9867. lights.forEach(function (light) {
  9868. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9869. if (meshIndex !== -1) {
  9870. light.includedOnlyMeshes.splice(meshIndex, 1);
  9871. }
  9872. meshIndex = light.excludedMeshes.indexOf(_this);
  9873. if (meshIndex !== -1) {
  9874. light.excludedMeshes.splice(meshIndex, 1);
  9875. }
  9876. });
  9877. // Edges
  9878. if (this._edgesRenderer) {
  9879. this._edgesRenderer.dispose();
  9880. this._edgesRenderer = null;
  9881. }
  9882. // SubMeshes
  9883. this.releaseSubMeshes();
  9884. // Remove from scene
  9885. this.getScene().removeMesh(this);
  9886. if (!doNotRecurse) {
  9887. // Particles
  9888. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9889. if (this.getScene().particleSystems[index].emitter === this) {
  9890. this.getScene().particleSystems[index].dispose();
  9891. index--;
  9892. }
  9893. }
  9894. // Children
  9895. var objects = this.getDescendants(true);
  9896. for (index = 0; index < objects.length; index++) {
  9897. objects[index].dispose();
  9898. }
  9899. }
  9900. else {
  9901. var childMeshes = this.getChildMeshes(true);
  9902. for (index = 0; index < childMeshes.length; index++) {
  9903. var child = childMeshes[index];
  9904. child.parent = null;
  9905. child.computeWorldMatrix(true);
  9906. }
  9907. }
  9908. _super.prototype.dispose.call(this);
  9909. this.onAfterWorldMatrixUpdateObservable.clear();
  9910. this.onCollideObservable.clear();
  9911. this.onCollisionPositionChangeObservable.clear();
  9912. this._isDisposed = true;
  9913. // Callback
  9914. this.onDisposeObservable.notifyObservers(this);
  9915. this.onDisposeObservable.clear();
  9916. };
  9917. // Statics
  9918. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9919. AbstractMesh._BILLBOARDMODE_X = 1;
  9920. AbstractMesh._BILLBOARDMODE_Y = 2;
  9921. AbstractMesh._BILLBOARDMODE_Z = 4;
  9922. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9923. return AbstractMesh;
  9924. })(BABYLON.Node);
  9925. BABYLON.AbstractMesh = AbstractMesh;
  9926. })(BABYLON || (BABYLON = {}));
  9927. var BABYLON;
  9928. (function (BABYLON) {
  9929. var Light = (function (_super) {
  9930. __extends(Light, _super);
  9931. function Light(name, scene) {
  9932. _super.call(this, name, scene);
  9933. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9934. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9935. this.intensity = 1.0;
  9936. this.range = Number.MAX_VALUE;
  9937. this.includeOnlyWithLayerMask = 0;
  9938. this.includedOnlyMeshes = new Array();
  9939. this.excludedMeshes = new Array();
  9940. this.excludeWithLayerMask = 0;
  9941. // PBR Properties.
  9942. this.radius = 0.00001;
  9943. this._excludedMeshesIds = new Array();
  9944. this._includedOnlyMeshesIds = new Array();
  9945. scene.addLight(this);
  9946. }
  9947. /**
  9948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9949. */
  9950. Light.prototype.toString = function (fullDetails) {
  9951. var ret = "Name: " + this.name;
  9952. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9953. if (this.animations) {
  9954. for (var i = 0; i < this.animations.length; i++) {
  9955. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9956. }
  9957. }
  9958. if (fullDetails) {
  9959. }
  9960. return ret;
  9961. };
  9962. Light.prototype.getShadowGenerator = function () {
  9963. return this._shadowGenerator;
  9964. };
  9965. Light.prototype.getAbsolutePosition = function () {
  9966. return BABYLON.Vector3.Zero();
  9967. };
  9968. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9969. };
  9970. Light.prototype._getWorldMatrix = function () {
  9971. return BABYLON.Matrix.Identity();
  9972. };
  9973. Light.prototype.canAffectMesh = function (mesh) {
  9974. if (!mesh) {
  9975. return true;
  9976. }
  9977. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9978. return false;
  9979. }
  9980. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9981. return false;
  9982. }
  9983. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9984. return false;
  9985. }
  9986. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9987. return false;
  9988. }
  9989. return true;
  9990. };
  9991. Light.prototype.getWorldMatrix = function () {
  9992. this._currentRenderId = this.getScene().getRenderId();
  9993. var worldMatrix = this._getWorldMatrix();
  9994. if (this.parent && this.parent.getWorldMatrix) {
  9995. if (!this._parentedWorldMatrix) {
  9996. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9997. }
  9998. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9999. this._markSyncedWithParent();
  10000. return this._parentedWorldMatrix;
  10001. }
  10002. return worldMatrix;
  10003. };
  10004. Light.prototype.dispose = function () {
  10005. if (this._shadowGenerator) {
  10006. this._shadowGenerator.dispose();
  10007. this._shadowGenerator = null;
  10008. }
  10009. // Animations
  10010. this.getScene().stopAnimation(this);
  10011. // Remove from scene
  10012. this.getScene().removeLight(this);
  10013. _super.prototype.dispose.call(this);
  10014. };
  10015. Light.prototype.getTypeID = function () {
  10016. return 0;
  10017. };
  10018. Light.prototype.clone = function (name) {
  10019. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10020. };
  10021. Light.prototype.serialize = function () {
  10022. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10023. // Type
  10024. serializationObject.type = this.getTypeID();
  10025. // Parent
  10026. if (this.parent) {
  10027. serializationObject.parentId = this.parent.id;
  10028. }
  10029. // Inclusion / exclusions
  10030. if (this.excludedMeshes.length > 0) {
  10031. serializationObject.excludedMeshesIds = [];
  10032. this.excludedMeshes.forEach(function (mesh) {
  10033. serializationObject.excludedMeshesIds.push(mesh.id);
  10034. });
  10035. }
  10036. if (this.includedOnlyMeshes.length > 0) {
  10037. serializationObject.includedOnlyMeshesIds = [];
  10038. this.includedOnlyMeshes.forEach(function (mesh) {
  10039. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10040. });
  10041. }
  10042. // Animations
  10043. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10044. serializationObject.ranges = this.serializeAnimationRanges();
  10045. return serializationObject;
  10046. };
  10047. Light.GetConstructorFromName = function (type, name, scene) {
  10048. switch (type) {
  10049. case 0:
  10050. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10051. case 1:
  10052. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10053. case 2:
  10054. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10055. case 3:
  10056. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10057. }
  10058. };
  10059. Light.Parse = function (parsedLight, scene) {
  10060. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10061. // Inclusion / exclusions
  10062. if (parsedLight.excludedMeshesIds) {
  10063. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10064. }
  10065. if (parsedLight.includedOnlyMeshesIds) {
  10066. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10067. }
  10068. // Parent
  10069. if (parsedLight.parentId) {
  10070. light._waitingParentId = parsedLight.parentId;
  10071. }
  10072. // Animations
  10073. if (parsedLight.animations) {
  10074. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10075. var parsedAnimation = parsedLight.animations[animationIndex];
  10076. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10077. }
  10078. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10079. }
  10080. if (parsedLight.autoAnimate) {
  10081. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10082. }
  10083. return light;
  10084. };
  10085. __decorate([
  10086. BABYLON.serializeAsColor3()
  10087. ], Light.prototype, "diffuse", void 0);
  10088. __decorate([
  10089. BABYLON.serializeAsColor3()
  10090. ], Light.prototype, "specular", void 0);
  10091. __decorate([
  10092. BABYLON.serialize()
  10093. ], Light.prototype, "intensity", void 0);
  10094. __decorate([
  10095. BABYLON.serialize()
  10096. ], Light.prototype, "range", void 0);
  10097. __decorate([
  10098. BABYLON.serialize()
  10099. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10100. __decorate([
  10101. BABYLON.serialize()
  10102. ], Light.prototype, "excludeWithLayerMask", void 0);
  10103. __decorate([
  10104. BABYLON.serialize()
  10105. ], Light.prototype, "radius", void 0);
  10106. return Light;
  10107. })(BABYLON.Node);
  10108. BABYLON.Light = Light;
  10109. })(BABYLON || (BABYLON = {}));
  10110. var BABYLON;
  10111. (function (BABYLON) {
  10112. var PointLight = (function (_super) {
  10113. __extends(PointLight, _super);
  10114. function PointLight(name, position, scene) {
  10115. _super.call(this, name, scene);
  10116. this.position = position;
  10117. }
  10118. PointLight.prototype.getAbsolutePosition = function () {
  10119. return this.transformedPosition ? this.transformedPosition : this.position;
  10120. };
  10121. PointLight.prototype.computeTransformedPosition = function () {
  10122. if (this.parent && this.parent.getWorldMatrix) {
  10123. if (!this.transformedPosition) {
  10124. this.transformedPosition = BABYLON.Vector3.Zero();
  10125. }
  10126. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10127. return true;
  10128. }
  10129. return false;
  10130. };
  10131. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10132. if (this.parent && this.parent.getWorldMatrix) {
  10133. this.computeTransformedPosition();
  10134. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10135. return;
  10136. }
  10137. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10138. };
  10139. PointLight.prototype.needCube = function () {
  10140. return true;
  10141. };
  10142. PointLight.prototype.supportsVSM = function () {
  10143. return false;
  10144. };
  10145. PointLight.prototype.needRefreshPerFrame = function () {
  10146. return false;
  10147. };
  10148. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10149. switch (faceIndex) {
  10150. case 0:
  10151. return new BABYLON.Vector3(1, 0, 0);
  10152. case 1:
  10153. return new BABYLON.Vector3(-1, 0, 0);
  10154. case 2:
  10155. return new BABYLON.Vector3(0, -1, 0);
  10156. case 3:
  10157. return new BABYLON.Vector3(0, 1, 0);
  10158. case 4:
  10159. return new BABYLON.Vector3(0, 0, 1);
  10160. case 5:
  10161. return new BABYLON.Vector3(0, 0, -1);
  10162. }
  10163. return BABYLON.Vector3.Zero();
  10164. };
  10165. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10166. var activeCamera = this.getScene().activeCamera;
  10167. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10168. };
  10169. PointLight.prototype._getWorldMatrix = function () {
  10170. if (!this._worldMatrix) {
  10171. this._worldMatrix = BABYLON.Matrix.Identity();
  10172. }
  10173. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10174. return this._worldMatrix;
  10175. };
  10176. PointLight.prototype.getTypeID = function () {
  10177. return 0;
  10178. };
  10179. __decorate([
  10180. BABYLON.serializeAsVector3()
  10181. ], PointLight.prototype, "position", void 0);
  10182. return PointLight;
  10183. })(BABYLON.Light);
  10184. BABYLON.PointLight = PointLight;
  10185. })(BABYLON || (BABYLON = {}));
  10186. var BABYLON;
  10187. (function (BABYLON) {
  10188. var SpotLight = (function (_super) {
  10189. __extends(SpotLight, _super);
  10190. function SpotLight(name, position, direction, angle, exponent, scene) {
  10191. _super.call(this, name, scene);
  10192. this.position = position;
  10193. this.direction = direction;
  10194. this.angle = angle;
  10195. this.exponent = exponent;
  10196. }
  10197. SpotLight.prototype.getAbsolutePosition = function () {
  10198. return this.transformedPosition ? this.transformedPosition : this.position;
  10199. };
  10200. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10201. var activeCamera = this.getScene().activeCamera;
  10202. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10203. };
  10204. SpotLight.prototype.needCube = function () {
  10205. return false;
  10206. };
  10207. SpotLight.prototype.supportsVSM = function () {
  10208. return true;
  10209. };
  10210. SpotLight.prototype.needRefreshPerFrame = function () {
  10211. return false;
  10212. };
  10213. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10214. return this.direction;
  10215. };
  10216. SpotLight.prototype.setDirectionToTarget = function (target) {
  10217. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10218. return this.direction;
  10219. };
  10220. SpotLight.prototype.computeTransformedPosition = function () {
  10221. if (this.parent && this.parent.getWorldMatrix) {
  10222. if (!this.transformedPosition) {
  10223. this.transformedPosition = BABYLON.Vector3.Zero();
  10224. }
  10225. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10226. return true;
  10227. }
  10228. return false;
  10229. };
  10230. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10231. var normalizeDirection;
  10232. if (this.parent && this.parent.getWorldMatrix) {
  10233. if (!this._transformedDirection) {
  10234. this._transformedDirection = BABYLON.Vector3.Zero();
  10235. }
  10236. this.computeTransformedPosition();
  10237. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10238. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10239. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10240. }
  10241. else {
  10242. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10243. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10244. }
  10245. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10246. };
  10247. SpotLight.prototype._getWorldMatrix = function () {
  10248. if (!this._worldMatrix) {
  10249. this._worldMatrix = BABYLON.Matrix.Identity();
  10250. }
  10251. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10252. return this._worldMatrix;
  10253. };
  10254. SpotLight.prototype.getTypeID = function () {
  10255. return 2;
  10256. };
  10257. __decorate([
  10258. BABYLON.serializeAsVector3()
  10259. ], SpotLight.prototype, "position", void 0);
  10260. __decorate([
  10261. BABYLON.serializeAsVector3()
  10262. ], SpotLight.prototype, "direction", void 0);
  10263. __decorate([
  10264. BABYLON.serialize()
  10265. ], SpotLight.prototype, "angle", void 0);
  10266. __decorate([
  10267. BABYLON.serialize()
  10268. ], SpotLight.prototype, "exponent", void 0);
  10269. return SpotLight;
  10270. })(BABYLON.Light);
  10271. BABYLON.SpotLight = SpotLight;
  10272. })(BABYLON || (BABYLON = {}));
  10273. var BABYLON;
  10274. (function (BABYLON) {
  10275. var HemisphericLight = (function (_super) {
  10276. __extends(HemisphericLight, _super);
  10277. function HemisphericLight(name, direction, scene) {
  10278. _super.call(this, name, scene);
  10279. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10280. this.direction = direction;
  10281. }
  10282. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10283. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10284. return this.direction;
  10285. };
  10286. HemisphericLight.prototype.getShadowGenerator = function () {
  10287. return null;
  10288. };
  10289. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10290. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10291. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10292. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10293. };
  10294. HemisphericLight.prototype._getWorldMatrix = function () {
  10295. if (!this._worldMatrix) {
  10296. this._worldMatrix = BABYLON.Matrix.Identity();
  10297. }
  10298. return this._worldMatrix;
  10299. };
  10300. HemisphericLight.prototype.getTypeID = function () {
  10301. return 3;
  10302. };
  10303. __decorate([
  10304. BABYLON.serializeAsColor3()
  10305. ], HemisphericLight.prototype, "groundColor", void 0);
  10306. __decorate([
  10307. BABYLON.serializeAsVector3()
  10308. ], HemisphericLight.prototype, "direction", void 0);
  10309. return HemisphericLight;
  10310. })(BABYLON.Light);
  10311. BABYLON.HemisphericLight = HemisphericLight;
  10312. })(BABYLON || (BABYLON = {}));
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. var DirectionalLight = (function (_super) {
  10316. __extends(DirectionalLight, _super);
  10317. function DirectionalLight(name, direction, scene) {
  10318. _super.call(this, name, scene);
  10319. this.shadowOrthoScale = 0.5;
  10320. this.autoUpdateExtends = true;
  10321. // Cache
  10322. this._orthoLeft = Number.MAX_VALUE;
  10323. this._orthoRight = Number.MIN_VALUE;
  10324. this._orthoTop = Number.MIN_VALUE;
  10325. this._orthoBottom = Number.MAX_VALUE;
  10326. this.position = direction.scale(-1);
  10327. this.direction = direction;
  10328. }
  10329. DirectionalLight.prototype.getAbsolutePosition = function () {
  10330. return this.transformedPosition ? this.transformedPosition : this.position;
  10331. };
  10332. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10333. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10334. return this.direction;
  10335. };
  10336. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10337. var activeCamera = this.getScene().activeCamera;
  10338. // Check extends
  10339. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10340. var tempVector3 = BABYLON.Vector3.Zero();
  10341. this._orthoLeft = Number.MAX_VALUE;
  10342. this._orthoRight = Number.MIN_VALUE;
  10343. this._orthoTop = Number.MIN_VALUE;
  10344. this._orthoBottom = Number.MAX_VALUE;
  10345. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10346. var mesh = renderList[meshIndex];
  10347. if (!mesh) {
  10348. continue;
  10349. }
  10350. var boundingInfo = mesh.getBoundingInfo();
  10351. if (!boundingInfo) {
  10352. continue;
  10353. }
  10354. var boundingBox = boundingInfo.boundingBox;
  10355. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10356. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10357. if (tempVector3.x < this._orthoLeft)
  10358. this._orthoLeft = tempVector3.x;
  10359. if (tempVector3.y < this._orthoBottom)
  10360. this._orthoBottom = tempVector3.y;
  10361. if (tempVector3.x > this._orthoRight)
  10362. this._orthoRight = tempVector3.x;
  10363. if (tempVector3.y > this._orthoTop)
  10364. this._orthoTop = tempVector3.y;
  10365. }
  10366. }
  10367. }
  10368. var xOffset = this._orthoRight - this._orthoLeft;
  10369. var yOffset = this._orthoTop - this._orthoBottom;
  10370. 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);
  10371. };
  10372. DirectionalLight.prototype.supportsVSM = function () {
  10373. return true;
  10374. };
  10375. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10376. return true;
  10377. };
  10378. DirectionalLight.prototype.needCube = function () {
  10379. return false;
  10380. };
  10381. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10382. return this.direction;
  10383. };
  10384. DirectionalLight.prototype.computeTransformedPosition = function () {
  10385. if (this.parent && this.parent.getWorldMatrix) {
  10386. if (!this.transformedPosition) {
  10387. this.transformedPosition = BABYLON.Vector3.Zero();
  10388. }
  10389. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10390. return true;
  10391. }
  10392. return false;
  10393. };
  10394. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10395. if (this.parent && this.parent.getWorldMatrix) {
  10396. if (!this._transformedDirection) {
  10397. this._transformedDirection = BABYLON.Vector3.Zero();
  10398. }
  10399. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10400. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10401. return;
  10402. }
  10403. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10404. };
  10405. DirectionalLight.prototype._getWorldMatrix = function () {
  10406. if (!this._worldMatrix) {
  10407. this._worldMatrix = BABYLON.Matrix.Identity();
  10408. }
  10409. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10410. return this._worldMatrix;
  10411. };
  10412. DirectionalLight.prototype.getTypeID = function () {
  10413. return 1;
  10414. };
  10415. __decorate([
  10416. BABYLON.serializeAsVector3()
  10417. ], DirectionalLight.prototype, "position", void 0);
  10418. __decorate([
  10419. BABYLON.serializeAsVector3()
  10420. ], DirectionalLight.prototype, "direction", void 0);
  10421. __decorate([
  10422. BABYLON.serialize()
  10423. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10424. __decorate([
  10425. BABYLON.serialize()
  10426. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10427. return DirectionalLight;
  10428. })(BABYLON.Light);
  10429. BABYLON.DirectionalLight = DirectionalLight;
  10430. })(BABYLON || (BABYLON = {}));
  10431. var BABYLON;
  10432. (function (BABYLON) {
  10433. var ShadowGenerator = (function () {
  10434. function ShadowGenerator(mapSize, light) {
  10435. var _this = this;
  10436. // Members
  10437. this._filter = ShadowGenerator.FILTER_NONE;
  10438. this.blurScale = 2;
  10439. this._blurBoxOffset = 0;
  10440. this._bias = 0.00005;
  10441. this._lightDirection = BABYLON.Vector3.Zero();
  10442. this.forceBackFacesOnly = false;
  10443. this._darkness = 0;
  10444. this._transparencyShadow = false;
  10445. this._viewMatrix = BABYLON.Matrix.Zero();
  10446. this._projectionMatrix = BABYLON.Matrix.Zero();
  10447. this._transformMatrix = BABYLON.Matrix.Zero();
  10448. this._worldViewProjection = BABYLON.Matrix.Zero();
  10449. this._currentFaceIndex = 0;
  10450. this._currentFaceIndexCache = 0;
  10451. this._light = light;
  10452. this._scene = light.getScene();
  10453. this._mapSize = mapSize;
  10454. light._shadowGenerator = this;
  10455. // Render target
  10456. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10457. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10458. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10459. this._shadowMap.anisotropicFilteringLevel = 1;
  10460. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10461. this._shadowMap.renderParticles = false;
  10462. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10463. _this._currentFaceIndex = faceIndex;
  10464. });
  10465. this._shadowMap.onAfterUnbindObservable.add(function () {
  10466. if (!_this.useBlurVarianceShadowMap) {
  10467. return;
  10468. }
  10469. if (!_this._shadowMap2) {
  10470. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10471. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10472. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10473. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10474. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10475. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10476. effect.setTexture("textureSampler", _this._shadowMap);
  10477. });
  10478. _this.blurBoxOffset = 1;
  10479. }
  10480. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10481. });
  10482. // Custom render function
  10483. var renderSubMesh = function (subMesh) {
  10484. var mesh = subMesh.getRenderingMesh();
  10485. var scene = _this._scene;
  10486. var engine = scene.getEngine();
  10487. // Culling
  10488. engine.setState(subMesh.getMaterial().backFaceCulling);
  10489. // Managing instances
  10490. var batch = mesh._getInstancesRenderList(subMesh._id);
  10491. if (batch.mustReturn) {
  10492. return;
  10493. }
  10494. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10495. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10496. engine.enableEffect(_this._effect);
  10497. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10498. var material = subMesh.getMaterial();
  10499. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10500. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10501. if (_this.getLight().needCube()) {
  10502. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10503. }
  10504. // Alpha test
  10505. if (material && material.needAlphaTesting()) {
  10506. var alphaTexture = material.getAlphaTestTexture();
  10507. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10508. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10509. }
  10510. // Bones
  10511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10512. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10513. }
  10514. if (_this.forceBackFacesOnly) {
  10515. engine.setState(true, 0, false, true);
  10516. }
  10517. // Draw
  10518. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10519. if (_this.forceBackFacesOnly) {
  10520. engine.setState(true, 0, false, false);
  10521. }
  10522. }
  10523. else {
  10524. // Need to reset refresh rate of the shadowMap
  10525. _this._shadowMap.resetRefreshCounter();
  10526. }
  10527. };
  10528. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10529. var index;
  10530. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10531. renderSubMesh(opaqueSubMeshes.data[index]);
  10532. }
  10533. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10534. renderSubMesh(alphaTestSubMeshes.data[index]);
  10535. }
  10536. if (_this._transparencyShadow) {
  10537. for (index = 0; index < transparentSubMeshes.length; index++) {
  10538. renderSubMesh(transparentSubMeshes.data[index]);
  10539. }
  10540. }
  10541. };
  10542. this._shadowMap.onClearObservable.add(function (engine) {
  10543. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10544. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10545. }
  10546. else {
  10547. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10548. }
  10549. });
  10550. }
  10551. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10552. // Static
  10553. get: function () {
  10554. return ShadowGenerator._FILTER_NONE;
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10560. get: function () {
  10561. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10562. },
  10563. enumerable: true,
  10564. configurable: true
  10565. });
  10566. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10567. get: function () {
  10568. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10574. get: function () {
  10575. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10581. get: function () {
  10582. return this._bias;
  10583. },
  10584. set: function (bias) {
  10585. this._bias = bias;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10591. get: function () {
  10592. return this._blurBoxOffset;
  10593. },
  10594. set: function (value) {
  10595. var _this = this;
  10596. if (this._blurBoxOffset === value) {
  10597. return;
  10598. }
  10599. this._blurBoxOffset = value;
  10600. if (this._boxBlurPostprocess) {
  10601. this._boxBlurPostprocess.dispose();
  10602. }
  10603. 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);
  10604. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10605. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10606. });
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10612. get: function () {
  10613. return this._filter;
  10614. },
  10615. set: function (value) {
  10616. if (this._filter === value) {
  10617. return;
  10618. }
  10619. this._filter = value;
  10620. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10621. this._shadowMap.anisotropicFilteringLevel = 16;
  10622. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10623. }
  10624. else {
  10625. this._shadowMap.anisotropicFilteringLevel = 1;
  10626. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10627. }
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10633. get: function () {
  10634. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10635. },
  10636. set: function (value) {
  10637. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10643. get: function () {
  10644. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10645. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10646. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10647. },
  10648. set: function (value) {
  10649. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10655. get: function () {
  10656. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10657. },
  10658. set: function (value) {
  10659. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10665. var defines = [];
  10666. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10667. defines.push("#define VSM");
  10668. }
  10669. if (this.getLight().needCube()) {
  10670. defines.push("#define CUBEMAP");
  10671. }
  10672. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10673. var mesh = subMesh.getMesh();
  10674. var material = subMesh.getMaterial();
  10675. // Alpha test
  10676. if (material && material.needAlphaTesting()) {
  10677. defines.push("#define ALPHATEST");
  10678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10679. attribs.push(BABYLON.VertexBuffer.UVKind);
  10680. defines.push("#define UV1");
  10681. }
  10682. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10683. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10684. defines.push("#define UV2");
  10685. }
  10686. }
  10687. // Bones
  10688. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10691. if (mesh.numBoneInfluencers > 4) {
  10692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10694. }
  10695. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10696. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10697. }
  10698. else {
  10699. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10700. }
  10701. // Instances
  10702. if (useInstances) {
  10703. defines.push("#define INSTANCES");
  10704. attribs.push("world0");
  10705. attribs.push("world1");
  10706. attribs.push("world2");
  10707. attribs.push("world3");
  10708. }
  10709. // Get correct effect
  10710. var join = defines.join("\n");
  10711. if (this._cachedDefines !== join) {
  10712. this._cachedDefines = join;
  10713. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10714. }
  10715. return this._effect.isReady();
  10716. };
  10717. ShadowGenerator.prototype.getShadowMap = function () {
  10718. return this._shadowMap;
  10719. };
  10720. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10721. if (this._shadowMap2) {
  10722. return this._shadowMap2;
  10723. }
  10724. return this._shadowMap;
  10725. };
  10726. ShadowGenerator.prototype.getLight = function () {
  10727. return this._light;
  10728. };
  10729. // Methods
  10730. ShadowGenerator.prototype.getTransformMatrix = function () {
  10731. var scene = this._scene;
  10732. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10733. return this._transformMatrix;
  10734. }
  10735. this._currentRenderID = scene.getRenderId();
  10736. this._currentFaceIndexCache = this._currentFaceIndex;
  10737. var lightPosition = this._light.position;
  10738. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10739. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10740. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10741. }
  10742. if (this._light.computeTransformedPosition()) {
  10743. lightPosition = this._light.transformedPosition;
  10744. }
  10745. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10746. this._cachedPosition = lightPosition.clone();
  10747. this._cachedDirection = this._lightDirection.clone();
  10748. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10749. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10750. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10751. }
  10752. return this._transformMatrix;
  10753. };
  10754. ShadowGenerator.prototype.getDarkness = function () {
  10755. return this._darkness;
  10756. };
  10757. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10758. if (darkness >= 1.0)
  10759. this._darkness = 1.0;
  10760. else if (darkness <= 0.0)
  10761. this._darkness = 0.0;
  10762. else
  10763. this._darkness = darkness;
  10764. };
  10765. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10766. this._transparencyShadow = hasShadow;
  10767. };
  10768. ShadowGenerator.prototype._packHalf = function (depth) {
  10769. var scale = depth * 255.0;
  10770. var fract = scale - Math.floor(scale);
  10771. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10772. };
  10773. ShadowGenerator.prototype.dispose = function () {
  10774. this._shadowMap.dispose();
  10775. if (this._shadowMap2) {
  10776. this._shadowMap2.dispose();
  10777. }
  10778. if (this._downSamplePostprocess) {
  10779. this._downSamplePostprocess.dispose();
  10780. }
  10781. if (this._boxBlurPostprocess) {
  10782. this._boxBlurPostprocess.dispose();
  10783. }
  10784. };
  10785. ShadowGenerator.prototype.serialize = function () {
  10786. var serializationObject = {};
  10787. serializationObject.lightId = this._light.id;
  10788. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10789. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10790. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10791. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10792. serializationObject.renderList = [];
  10793. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10794. var mesh = this.getShadowMap().renderList[meshIndex];
  10795. serializationObject.renderList.push(mesh.id);
  10796. }
  10797. return serializationObject;
  10798. };
  10799. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10800. //casting to point light, as light is missing the position attr and typescript complains.
  10801. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10802. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10803. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10804. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10805. meshes.forEach(function (mesh) {
  10806. shadowGenerator.getShadowMap().renderList.push(mesh);
  10807. });
  10808. }
  10809. if (parsedShadowGenerator.usePoissonSampling) {
  10810. shadowGenerator.usePoissonSampling = true;
  10811. }
  10812. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10813. shadowGenerator.useVarianceShadowMap = true;
  10814. }
  10815. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10816. shadowGenerator.useBlurVarianceShadowMap = true;
  10817. if (parsedShadowGenerator.blurScale) {
  10818. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10819. }
  10820. if (parsedShadowGenerator.blurBoxOffset) {
  10821. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10822. }
  10823. }
  10824. if (parsedShadowGenerator.bias !== undefined) {
  10825. shadowGenerator.bias = parsedShadowGenerator.bias;
  10826. }
  10827. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10828. return shadowGenerator;
  10829. };
  10830. ShadowGenerator._FILTER_NONE = 0;
  10831. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10832. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10833. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10834. return ShadowGenerator;
  10835. })();
  10836. BABYLON.ShadowGenerator = ShadowGenerator;
  10837. })(BABYLON || (BABYLON = {}));
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10841. if (boxMin.x > sphereCenter.x + sphereRadius)
  10842. return false;
  10843. if (sphereCenter.x - sphereRadius > boxMax.x)
  10844. return false;
  10845. if (boxMin.y > sphereCenter.y + sphereRadius)
  10846. return false;
  10847. if (sphereCenter.y - sphereRadius > boxMax.y)
  10848. return false;
  10849. if (boxMin.z > sphereCenter.z + sphereRadius)
  10850. return false;
  10851. if (sphereCenter.z - sphereRadius > boxMax.z)
  10852. return false;
  10853. return true;
  10854. };
  10855. var getLowestRoot = function (a, b, c, maxR) {
  10856. var determinant = b * b - 4.0 * a * c;
  10857. var result = { root: 0, found: false };
  10858. if (determinant < 0)
  10859. return result;
  10860. var sqrtD = Math.sqrt(determinant);
  10861. var r1 = (-b - sqrtD) / (2.0 * a);
  10862. var r2 = (-b + sqrtD) / (2.0 * a);
  10863. if (r1 > r2) {
  10864. var temp = r2;
  10865. r2 = r1;
  10866. r1 = temp;
  10867. }
  10868. if (r1 > 0 && r1 < maxR) {
  10869. result.root = r1;
  10870. result.found = true;
  10871. return result;
  10872. }
  10873. if (r2 > 0 && r2 < maxR) {
  10874. result.root = r2;
  10875. result.found = true;
  10876. return result;
  10877. }
  10878. return result;
  10879. };
  10880. var Collider = (function () {
  10881. function Collider() {
  10882. this.radius = new BABYLON.Vector3(1, 1, 1);
  10883. this.retry = 0;
  10884. this.basePointWorld = BABYLON.Vector3.Zero();
  10885. this.velocityWorld = BABYLON.Vector3.Zero();
  10886. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10887. this._collisionPoint = BABYLON.Vector3.Zero();
  10888. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10889. this._tempVector = BABYLON.Vector3.Zero();
  10890. this._tempVector2 = BABYLON.Vector3.Zero();
  10891. this._tempVector3 = BABYLON.Vector3.Zero();
  10892. this._tempVector4 = BABYLON.Vector3.Zero();
  10893. this._edge = BABYLON.Vector3.Zero();
  10894. this._baseToVertex = BABYLON.Vector3.Zero();
  10895. this._destinationPoint = BABYLON.Vector3.Zero();
  10896. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10897. this._displacementVector = BABYLON.Vector3.Zero();
  10898. }
  10899. // Methods
  10900. Collider.prototype._initialize = function (source, dir, e) {
  10901. this.velocity = dir;
  10902. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10903. this.basePoint = source;
  10904. source.multiplyToRef(this.radius, this.basePointWorld);
  10905. dir.multiplyToRef(this.radius, this.velocityWorld);
  10906. this.velocityWorldLength = this.velocityWorld.length();
  10907. this.epsilon = e;
  10908. this.collisionFound = false;
  10909. };
  10910. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10911. pa.subtractToRef(point, this._tempVector);
  10912. pb.subtractToRef(point, this._tempVector2);
  10913. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10914. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10915. if (d < 0)
  10916. return false;
  10917. pc.subtractToRef(point, this._tempVector3);
  10918. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10919. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10920. if (d < 0)
  10921. return false;
  10922. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10923. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10924. return d >= 0;
  10925. };
  10926. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10927. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10928. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10929. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10930. return false;
  10931. }
  10932. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10933. return false;
  10934. return true;
  10935. };
  10936. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10937. var t0;
  10938. var embeddedInPlane = false;
  10939. //defensive programming, actually not needed.
  10940. if (!trianglePlaneArray) {
  10941. trianglePlaneArray = [];
  10942. }
  10943. if (!trianglePlaneArray[faceIndex]) {
  10944. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10945. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10946. }
  10947. var trianglePlane = trianglePlaneArray[faceIndex];
  10948. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10949. return;
  10950. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10951. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10952. if (normalDotVelocity == 0) {
  10953. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10954. return;
  10955. embeddedInPlane = true;
  10956. t0 = 0;
  10957. }
  10958. else {
  10959. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10960. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10961. if (t0 > t1) {
  10962. var temp = t1;
  10963. t1 = t0;
  10964. t0 = temp;
  10965. }
  10966. if (t0 > 1.0 || t1 < 0.0)
  10967. return;
  10968. if (t0 < 0)
  10969. t0 = 0;
  10970. if (t0 > 1.0)
  10971. t0 = 1.0;
  10972. }
  10973. this._collisionPoint.copyFromFloats(0, 0, 0);
  10974. var found = false;
  10975. var t = 1.0;
  10976. if (!embeddedInPlane) {
  10977. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10978. this.velocity.scaleToRef(t0, this._tempVector);
  10979. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10980. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10981. found = true;
  10982. t = t0;
  10983. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10984. }
  10985. }
  10986. if (!found) {
  10987. var velocitySquaredLength = this.velocity.lengthSquared();
  10988. var a = velocitySquaredLength;
  10989. this.basePoint.subtractToRef(p1, this._tempVector);
  10990. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10991. var c = this._tempVector.lengthSquared() - 1.0;
  10992. var lowestRoot = getLowestRoot(a, b, c, t);
  10993. if (lowestRoot.found) {
  10994. t = lowestRoot.root;
  10995. found = true;
  10996. this._collisionPoint.copyFrom(p1);
  10997. }
  10998. this.basePoint.subtractToRef(p2, this._tempVector);
  10999. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11000. c = this._tempVector.lengthSquared() - 1.0;
  11001. lowestRoot = getLowestRoot(a, b, c, t);
  11002. if (lowestRoot.found) {
  11003. t = lowestRoot.root;
  11004. found = true;
  11005. this._collisionPoint.copyFrom(p2);
  11006. }
  11007. this.basePoint.subtractToRef(p3, this._tempVector);
  11008. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11009. c = this._tempVector.lengthSquared() - 1.0;
  11010. lowestRoot = getLowestRoot(a, b, c, t);
  11011. if (lowestRoot.found) {
  11012. t = lowestRoot.root;
  11013. found = true;
  11014. this._collisionPoint.copyFrom(p3);
  11015. }
  11016. p2.subtractToRef(p1, this._edge);
  11017. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11018. var edgeSquaredLength = this._edge.lengthSquared();
  11019. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11020. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11021. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11022. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11023. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11024. lowestRoot = getLowestRoot(a, b, c, t);
  11025. if (lowestRoot.found) {
  11026. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11027. if (f >= 0.0 && f <= 1.0) {
  11028. t = lowestRoot.root;
  11029. found = true;
  11030. this._edge.scaleInPlace(f);
  11031. p1.addToRef(this._edge, this._collisionPoint);
  11032. }
  11033. }
  11034. p3.subtractToRef(p2, this._edge);
  11035. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11036. edgeSquaredLength = this._edge.lengthSquared();
  11037. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11038. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11039. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11040. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11041. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11042. lowestRoot = getLowestRoot(a, b, c, t);
  11043. if (lowestRoot.found) {
  11044. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11045. if (f >= 0.0 && f <= 1.0) {
  11046. t = lowestRoot.root;
  11047. found = true;
  11048. this._edge.scaleInPlace(f);
  11049. p2.addToRef(this._edge, this._collisionPoint);
  11050. }
  11051. }
  11052. p1.subtractToRef(p3, this._edge);
  11053. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11054. edgeSquaredLength = this._edge.lengthSquared();
  11055. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11056. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11057. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11058. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11059. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11060. lowestRoot = getLowestRoot(a, b, c, t);
  11061. if (lowestRoot.found) {
  11062. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11063. if (f >= 0.0 && f <= 1.0) {
  11064. t = lowestRoot.root;
  11065. found = true;
  11066. this._edge.scaleInPlace(f);
  11067. p3.addToRef(this._edge, this._collisionPoint);
  11068. }
  11069. }
  11070. }
  11071. if (found) {
  11072. var distToCollision = t * this.velocity.length();
  11073. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11074. if (!this.intersectionPoint) {
  11075. this.intersectionPoint = this._collisionPoint.clone();
  11076. }
  11077. else {
  11078. this.intersectionPoint.copyFrom(this._collisionPoint);
  11079. }
  11080. this.nearestDistance = distToCollision;
  11081. this.collisionFound = true;
  11082. }
  11083. }
  11084. };
  11085. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11086. for (var i = indexStart; i < indexEnd; i += 3) {
  11087. var p1 = pts[indices[i] - decal];
  11088. var p2 = pts[indices[i + 1] - decal];
  11089. var p3 = pts[indices[i + 2] - decal];
  11090. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11091. }
  11092. };
  11093. Collider.prototype._getResponse = function (pos, vel) {
  11094. pos.addToRef(vel, this._destinationPoint);
  11095. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11096. this.basePoint.addToRef(vel, pos);
  11097. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11098. this._slidePlaneNormal.normalize();
  11099. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11100. pos.addInPlace(this._displacementVector);
  11101. this.intersectionPoint.addInPlace(this._displacementVector);
  11102. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11103. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11104. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11105. };
  11106. return Collider;
  11107. })();
  11108. BABYLON.Collider = Collider;
  11109. })(BABYLON || (BABYLON = {}));
  11110. var BABYLON;
  11111. (function (BABYLON) {
  11112. //WebWorker code will be inserted to this variable.
  11113. BABYLON.CollisionWorker = "";
  11114. (function (WorkerTaskType) {
  11115. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11116. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11117. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11118. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11119. var WorkerTaskType = BABYLON.WorkerTaskType;
  11120. (function (WorkerReplyType) {
  11121. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11122. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11123. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11124. var WorkerReplyType = BABYLON.WorkerReplyType;
  11125. var CollisionCoordinatorWorker = (function () {
  11126. function CollisionCoordinatorWorker() {
  11127. var _this = this;
  11128. this._scaledPosition = BABYLON.Vector3.Zero();
  11129. this._scaledVelocity = BABYLON.Vector3.Zero();
  11130. this.onMeshUpdated = function (mesh) {
  11131. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11132. };
  11133. this.onGeometryUpdated = function (geometry) {
  11134. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11135. };
  11136. this._afterRender = function () {
  11137. if (!_this._init)
  11138. return;
  11139. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11140. return;
  11141. }
  11142. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11143. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11144. if (_this._runningUpdated > 4) {
  11145. return;
  11146. }
  11147. ++_this._runningUpdated;
  11148. var payload = {
  11149. updatedMeshes: _this._addUpdateMeshesList,
  11150. updatedGeometries: _this._addUpdateGeometriesList,
  11151. removedGeometries: _this._toRemoveGeometryArray,
  11152. removedMeshes: _this._toRemoveMeshesArray
  11153. };
  11154. var message = {
  11155. payload: payload,
  11156. taskType: WorkerTaskType.UPDATE
  11157. };
  11158. var serializable = [];
  11159. for (var id in payload.updatedGeometries) {
  11160. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11161. //prepare transferables
  11162. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11163. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11164. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11165. }
  11166. }
  11167. _this._worker.postMessage(message, serializable);
  11168. _this._addUpdateMeshesList = {};
  11169. _this._addUpdateGeometriesList = {};
  11170. _this._toRemoveGeometryArray = [];
  11171. _this._toRemoveMeshesArray = [];
  11172. };
  11173. this._onMessageFromWorker = function (e) {
  11174. var returnData = e.data;
  11175. if (returnData.error != WorkerReplyType.SUCCESS) {
  11176. //TODO what errors can be returned from the worker?
  11177. BABYLON.Tools.Warn("error returned from worker!");
  11178. return;
  11179. }
  11180. switch (returnData.taskType) {
  11181. case WorkerTaskType.INIT:
  11182. _this._init = true;
  11183. //Update the worked with ALL of the scene's current state
  11184. _this._scene.meshes.forEach(function (mesh) {
  11185. _this.onMeshAdded(mesh);
  11186. });
  11187. _this._scene.getGeometries().forEach(function (geometry) {
  11188. _this.onGeometryAdded(geometry);
  11189. });
  11190. break;
  11191. case WorkerTaskType.UPDATE:
  11192. _this._runningUpdated--;
  11193. break;
  11194. case WorkerTaskType.COLLIDE:
  11195. _this._runningCollisionTask = false;
  11196. var returnPayload = returnData.payload;
  11197. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11198. return;
  11199. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11200. //cleanup
  11201. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11202. break;
  11203. }
  11204. };
  11205. this._collisionsCallbackArray = [];
  11206. this._init = false;
  11207. this._runningUpdated = 0;
  11208. this._runningCollisionTask = false;
  11209. this._addUpdateMeshesList = {};
  11210. this._addUpdateGeometriesList = {};
  11211. this._toRemoveGeometryArray = [];
  11212. this._toRemoveMeshesArray = [];
  11213. }
  11214. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11215. if (!this._init)
  11216. return;
  11217. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11218. return;
  11219. position.divideToRef(collider.radius, this._scaledPosition);
  11220. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11221. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11222. var payload = {
  11223. collider: {
  11224. position: this._scaledPosition.asArray(),
  11225. velocity: this._scaledVelocity.asArray(),
  11226. radius: collider.radius.asArray()
  11227. },
  11228. collisionId: collisionIndex,
  11229. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11230. maximumRetry: maximumRetry
  11231. };
  11232. var message = {
  11233. payload: payload,
  11234. taskType: WorkerTaskType.COLLIDE
  11235. };
  11236. this._worker.postMessage(message);
  11237. };
  11238. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11239. this._scene = scene;
  11240. this._scene.registerAfterRender(this._afterRender);
  11241. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11242. this._worker = new Worker(workerUrl);
  11243. this._worker.onmessage = this._onMessageFromWorker;
  11244. var message = {
  11245. payload: {},
  11246. taskType: WorkerTaskType.INIT
  11247. };
  11248. this._worker.postMessage(message);
  11249. };
  11250. CollisionCoordinatorWorker.prototype.destroy = function () {
  11251. this._scene.unregisterAfterRender(this._afterRender);
  11252. this._worker.terminate();
  11253. };
  11254. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11255. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11256. this.onMeshUpdated(mesh);
  11257. };
  11258. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11259. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11260. };
  11261. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11262. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11263. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11264. this.onGeometryUpdated(geometry);
  11265. };
  11266. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11267. this._toRemoveGeometryArray.push(geometry.id);
  11268. };
  11269. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11270. var submeshes = [];
  11271. if (mesh.subMeshes) {
  11272. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11273. return {
  11274. position: idx,
  11275. verticesStart: sm.verticesStart,
  11276. verticesCount: sm.verticesCount,
  11277. indexStart: sm.indexStart,
  11278. indexCount: sm.indexCount,
  11279. hasMaterial: !!sm.getMaterial(),
  11280. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11281. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11282. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11283. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11284. };
  11285. });
  11286. }
  11287. var geometryId = null;
  11288. if (mesh instanceof BABYLON.Mesh) {
  11289. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11290. }
  11291. else if (mesh instanceof BABYLON.InstancedMesh) {
  11292. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11293. }
  11294. return {
  11295. uniqueId: mesh.uniqueId,
  11296. id: mesh.id,
  11297. name: mesh.name,
  11298. geometryId: geometryId,
  11299. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11300. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11301. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11302. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11303. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11304. subMeshes: submeshes,
  11305. checkCollisions: mesh.checkCollisions
  11306. };
  11307. };
  11308. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11309. return {
  11310. id: geometry.id,
  11311. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11312. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11313. indices: new Int32Array(geometry.getIndices() || []),
  11314. };
  11315. };
  11316. return CollisionCoordinatorWorker;
  11317. })();
  11318. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11319. var CollisionCoordinatorLegacy = (function () {
  11320. function CollisionCoordinatorLegacy() {
  11321. this._scaledPosition = BABYLON.Vector3.Zero();
  11322. this._scaledVelocity = BABYLON.Vector3.Zero();
  11323. this._finalPosition = BABYLON.Vector3.Zero();
  11324. }
  11325. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11326. position.divideToRef(collider.radius, this._scaledPosition);
  11327. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11328. collider.collidedMesh = null;
  11329. collider.retry = 0;
  11330. collider.initialVelocity = this._scaledVelocity;
  11331. collider.initialPosition = this._scaledPosition;
  11332. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11333. this._finalPosition.multiplyInPlace(collider.radius);
  11334. //run the callback
  11335. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11336. };
  11337. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11338. this._scene = scene;
  11339. };
  11340. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11341. //Legacy need no destruction method.
  11342. };
  11343. //No update in legacy mode
  11344. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11345. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11346. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11347. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11348. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11349. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11350. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11351. if (excludedMesh === void 0) { excludedMesh = null; }
  11352. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11353. if (collider.retry >= maximumRetry) {
  11354. finalPosition.copyFrom(position);
  11355. return;
  11356. }
  11357. collider._initialize(position, velocity, closeDistance);
  11358. // Check all meshes
  11359. for (var index = 0; index < this._scene.meshes.length; index++) {
  11360. var mesh = this._scene.meshes[index];
  11361. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11362. mesh._checkCollision(collider);
  11363. }
  11364. }
  11365. if (!collider.collisionFound) {
  11366. position.addToRef(velocity, finalPosition);
  11367. return;
  11368. }
  11369. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11370. collider._getResponse(position, velocity);
  11371. }
  11372. if (velocity.length() <= closeDistance) {
  11373. finalPosition.copyFrom(position);
  11374. return;
  11375. }
  11376. collider.retry++;
  11377. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11378. };
  11379. return CollisionCoordinatorLegacy;
  11380. })();
  11381. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11382. })(BABYLON || (BABYLON = {}));
  11383. var BABYLON;
  11384. (function (BABYLON) {
  11385. var Camera = (function (_super) {
  11386. __extends(Camera, _super);
  11387. function Camera(name, position, scene) {
  11388. _super.call(this, name, scene);
  11389. this.upVector = BABYLON.Vector3.Up();
  11390. this.orthoLeft = null;
  11391. this.orthoRight = null;
  11392. this.orthoBottom = null;
  11393. this.orthoTop = null;
  11394. this.fov = 0.8;
  11395. this.minZ = 1.0;
  11396. this.maxZ = 10000.0;
  11397. this.inertia = 0.9;
  11398. this.mode = Camera.PERSPECTIVE_CAMERA;
  11399. this.isIntermediate = false;
  11400. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11401. this.layerMask = 0x0FFFFFFF;
  11402. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11403. // Camera rig members
  11404. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11405. this._rigCameras = new Array();
  11406. // Cache
  11407. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11408. this._projectionMatrix = new BABYLON.Matrix();
  11409. this._postProcesses = new Array();
  11410. this._activeMeshes = new BABYLON.SmartArray(256);
  11411. this._globalPosition = BABYLON.Vector3.Zero();
  11412. scene.addCamera(this);
  11413. if (!scene.activeCamera) {
  11414. scene.activeCamera = this;
  11415. }
  11416. this.position = position;
  11417. }
  11418. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11419. get: function () {
  11420. return Camera._PERSPECTIVE_CAMERA;
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11426. get: function () {
  11427. return Camera._ORTHOGRAPHIC_CAMERA;
  11428. },
  11429. enumerable: true,
  11430. configurable: true
  11431. });
  11432. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11433. get: function () {
  11434. return Camera._FOVMODE_VERTICAL_FIXED;
  11435. },
  11436. enumerable: true,
  11437. configurable: true
  11438. });
  11439. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11440. get: function () {
  11441. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11442. },
  11443. enumerable: true,
  11444. configurable: true
  11445. });
  11446. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11447. get: function () {
  11448. return Camera._RIG_MODE_NONE;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11454. get: function () {
  11455. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11461. get: function () {
  11462. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11468. get: function () {
  11469. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11475. get: function () {
  11476. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11482. get: function () {
  11483. return Camera._RIG_MODE_VR;
  11484. },
  11485. enumerable: true,
  11486. configurable: true
  11487. });
  11488. /**
  11489. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11490. */
  11491. Camera.prototype.toString = function (fullDetails) {
  11492. var ret = "Name: " + this.name;
  11493. ret += ", type: " + this.getTypeName();
  11494. if (this.animations) {
  11495. for (var i = 0; i < this.animations.length; i++) {
  11496. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11497. }
  11498. }
  11499. if (fullDetails) {
  11500. }
  11501. return ret;
  11502. };
  11503. Object.defineProperty(Camera.prototype, "globalPosition", {
  11504. get: function () {
  11505. return this._globalPosition;
  11506. },
  11507. enumerable: true,
  11508. configurable: true
  11509. });
  11510. Camera.prototype.getActiveMeshes = function () {
  11511. return this._activeMeshes;
  11512. };
  11513. Camera.prototype.isActiveMesh = function (mesh) {
  11514. return (this._activeMeshes.indexOf(mesh) !== -1);
  11515. };
  11516. //Cache
  11517. Camera.prototype._initCache = function () {
  11518. _super.prototype._initCache.call(this);
  11519. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11520. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11521. this._cache.mode = undefined;
  11522. this._cache.minZ = undefined;
  11523. this._cache.maxZ = undefined;
  11524. this._cache.fov = undefined;
  11525. this._cache.aspectRatio = undefined;
  11526. this._cache.orthoLeft = undefined;
  11527. this._cache.orthoRight = undefined;
  11528. this._cache.orthoBottom = undefined;
  11529. this._cache.orthoTop = undefined;
  11530. this._cache.renderWidth = undefined;
  11531. this._cache.renderHeight = undefined;
  11532. };
  11533. Camera.prototype._updateCache = function (ignoreParentClass) {
  11534. if (!ignoreParentClass) {
  11535. _super.prototype._updateCache.call(this);
  11536. }
  11537. var engine = this.getEngine();
  11538. this._cache.position.copyFrom(this.position);
  11539. this._cache.upVector.copyFrom(this.upVector);
  11540. this._cache.mode = this.mode;
  11541. this._cache.minZ = this.minZ;
  11542. this._cache.maxZ = this.maxZ;
  11543. this._cache.fov = this.fov;
  11544. this._cache.aspectRatio = engine.getAspectRatio(this);
  11545. this._cache.orthoLeft = this.orthoLeft;
  11546. this._cache.orthoRight = this.orthoRight;
  11547. this._cache.orthoBottom = this.orthoBottom;
  11548. this._cache.orthoTop = this.orthoTop;
  11549. this._cache.renderWidth = engine.getRenderWidth();
  11550. this._cache.renderHeight = engine.getRenderHeight();
  11551. };
  11552. Camera.prototype._updateFromScene = function () {
  11553. this.updateCache();
  11554. this._update();
  11555. };
  11556. // Synchronized
  11557. Camera.prototype._isSynchronized = function () {
  11558. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11559. };
  11560. Camera.prototype._isSynchronizedViewMatrix = function () {
  11561. if (!_super.prototype._isSynchronized.call(this))
  11562. return false;
  11563. return this._cache.position.equals(this.position)
  11564. && this._cache.upVector.equals(this.upVector)
  11565. && this.isSynchronizedWithParent();
  11566. };
  11567. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11568. var check = this._cache.mode === this.mode
  11569. && this._cache.minZ === this.minZ
  11570. && this._cache.maxZ === this.maxZ;
  11571. if (!check) {
  11572. return false;
  11573. }
  11574. var engine = this.getEngine();
  11575. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11576. check = this._cache.fov === this.fov
  11577. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11578. }
  11579. else {
  11580. check = this._cache.orthoLeft === this.orthoLeft
  11581. && this._cache.orthoRight === this.orthoRight
  11582. && this._cache.orthoBottom === this.orthoBottom
  11583. && this._cache.orthoTop === this.orthoTop
  11584. && this._cache.renderWidth === engine.getRenderWidth()
  11585. && this._cache.renderHeight === engine.getRenderHeight();
  11586. }
  11587. return check;
  11588. };
  11589. // Controls
  11590. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11591. };
  11592. Camera.prototype.detachControl = function (element) {
  11593. };
  11594. Camera.prototype._update = function () {
  11595. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11596. this._updateRigCameras();
  11597. }
  11598. this._checkInputs();
  11599. };
  11600. Camera.prototype._checkInputs = function () {
  11601. };
  11602. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11603. // invalidate framebuffer
  11604. if (this._postProcesses.length > 0) {
  11605. this._postProcesses[0].markTextureDirty();
  11606. }
  11607. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11608. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11609. var cam = this._rigCameras[i];
  11610. var rigPostProcess = cam._rigPostProcess;
  11611. // for VR rig, there does not have to be a post process
  11612. if (rigPostProcess) {
  11613. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11614. if (isPass) {
  11615. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11616. cam.isIntermediate = this._postProcesses.length === 0;
  11617. }
  11618. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11619. rigPostProcess.markTextureDirty();
  11620. }
  11621. else {
  11622. cam._postProcesses = this._postProcesses.slice(0);
  11623. }
  11624. }
  11625. };
  11626. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11627. if (insertAt === void 0) { insertAt = null; }
  11628. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11629. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11630. return 0;
  11631. }
  11632. if (insertAt == null || insertAt < 0) {
  11633. this._postProcesses.push(postProcess);
  11634. }
  11635. else {
  11636. this._postProcesses.splice(insertAt, 0, postProcess);
  11637. }
  11638. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11639. return this._postProcesses.indexOf(postProcess);
  11640. };
  11641. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11642. if (atIndices === void 0) { atIndices = null; }
  11643. var result = [];
  11644. var i;
  11645. var index;
  11646. if (!atIndices) {
  11647. var idx = this._postProcesses.indexOf(postProcess);
  11648. if (idx !== -1) {
  11649. this._postProcesses.splice(idx, 1);
  11650. }
  11651. }
  11652. else {
  11653. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11654. // iterate descending, so can just splice as we go
  11655. for (i = atIndices.length - 1; i >= 0; i--) {
  11656. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11657. result.push(i);
  11658. continue;
  11659. }
  11660. this._postProcesses.splice(index, 1);
  11661. }
  11662. }
  11663. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11664. return result;
  11665. };
  11666. Camera.prototype.getWorldMatrix = function () {
  11667. if (!this._worldMatrix) {
  11668. this._worldMatrix = BABYLON.Matrix.Identity();
  11669. }
  11670. var viewMatrix = this.getViewMatrix();
  11671. viewMatrix.invertToRef(this._worldMatrix);
  11672. return this._worldMatrix;
  11673. };
  11674. Camera.prototype._getViewMatrix = function () {
  11675. return BABYLON.Matrix.Identity();
  11676. };
  11677. Camera.prototype.getViewMatrix = function (force) {
  11678. this._computedViewMatrix = this._computeViewMatrix(force);
  11679. if (!force && this._isSynchronizedViewMatrix()) {
  11680. return this._computedViewMatrix;
  11681. }
  11682. if (!this.parent || !this.parent.getWorldMatrix) {
  11683. this._globalPosition.copyFrom(this.position);
  11684. }
  11685. else {
  11686. if (!this._worldMatrix) {
  11687. this._worldMatrix = BABYLON.Matrix.Identity();
  11688. }
  11689. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11690. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11691. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11692. this._computedViewMatrix.invert();
  11693. this._markSyncedWithParent();
  11694. }
  11695. this._currentRenderId = this.getScene().getRenderId();
  11696. return this._computedViewMatrix;
  11697. };
  11698. Camera.prototype._computeViewMatrix = function (force) {
  11699. if (!force && this._isSynchronizedViewMatrix()) {
  11700. return this._computedViewMatrix;
  11701. }
  11702. this._computedViewMatrix = this._getViewMatrix();
  11703. this._currentRenderId = this.getScene().getRenderId();
  11704. return this._computedViewMatrix;
  11705. };
  11706. Camera.prototype.getProjectionMatrix = function (force) {
  11707. if (!force && this._isSynchronizedProjectionMatrix()) {
  11708. return this._projectionMatrix;
  11709. }
  11710. var engine = this.getEngine();
  11711. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11712. if (this.minZ <= 0) {
  11713. this.minZ = 0.1;
  11714. }
  11715. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11716. return this._projectionMatrix;
  11717. }
  11718. var halfWidth = engine.getRenderWidth() / 2.0;
  11719. var halfHeight = engine.getRenderHeight() / 2.0;
  11720. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11721. return this._projectionMatrix;
  11722. };
  11723. Camera.prototype.dispose = function () {
  11724. // Animations
  11725. this.getScene().stopAnimation(this);
  11726. // Remove from scene
  11727. this.getScene().removeCamera(this);
  11728. while (this._rigCameras.length > 0) {
  11729. this._rigCameras.pop().dispose();
  11730. }
  11731. // Postprocesses
  11732. for (var i = 0; i < this._postProcesses.length; ++i) {
  11733. this._postProcesses[i].dispose(this);
  11734. }
  11735. _super.prototype.dispose.call(this);
  11736. };
  11737. // ---- Camera rigs section ----
  11738. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11739. while (this._rigCameras.length > 0) {
  11740. this._rigCameras.pop().dispose();
  11741. }
  11742. this.cameraRigMode = mode;
  11743. this._cameraRigParams = {};
  11744. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11745. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11746. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11747. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11748. // create the rig cameras, unless none
  11749. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11750. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11751. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11752. }
  11753. switch (this.cameraRigMode) {
  11754. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11755. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11756. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  11757. break;
  11758. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11759. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11760. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11761. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11762. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11763. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  11764. break;
  11765. case Camera.RIG_MODE_VR:
  11766. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11767. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11768. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11769. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11770. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11771. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11772. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11773. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  11774. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11775. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11776. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11777. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11778. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11779. if (metrics.compensateDistortion) {
  11780. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  11781. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  11782. }
  11783. break;
  11784. }
  11785. this._cascadePostProcessesToRigCams();
  11786. this._update();
  11787. };
  11788. Camera.prototype._getVRProjectionMatrix = function () {
  11789. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11790. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11791. return this._projectionMatrix;
  11792. };
  11793. Camera.prototype.setCameraRigParameter = function (name, value) {
  11794. if (!this._cameraRigParams) {
  11795. this._cameraRigParams = {};
  11796. }
  11797. this._cameraRigParams[name] = value;
  11798. //provisionnally:
  11799. if (name === "interaxialDistance") {
  11800. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11801. }
  11802. };
  11803. /**
  11804. * needs to be overridden by children so sub has required properties to be copied
  11805. */
  11806. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11807. return null;
  11808. };
  11809. /**
  11810. * May need to be overridden by children
  11811. */
  11812. Camera.prototype._updateRigCameras = function () {
  11813. for (var i = 0; i < this._rigCameras.length; i++) {
  11814. this._rigCameras[i].minZ = this.minZ;
  11815. this._rigCameras[i].maxZ = this.maxZ;
  11816. this._rigCameras[i].fov = this.fov;
  11817. }
  11818. // only update viewport when ANAGLYPH
  11819. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11820. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11821. }
  11822. };
  11823. Camera.prototype._setupInputs = function () {
  11824. };
  11825. Camera.prototype.serialize = function () {
  11826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11827. // Type
  11828. serializationObject.type = this.getTypeName();
  11829. // Parent
  11830. if (this.parent) {
  11831. serializationObject.parentId = this.parent.id;
  11832. }
  11833. if (this.inputs) {
  11834. this.inputs.serialize(serializationObject);
  11835. }
  11836. // Animations
  11837. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11838. serializationObject.ranges = this.serializeAnimationRanges();
  11839. return serializationObject;
  11840. };
  11841. Camera.prototype.getTypeName = function () {
  11842. return "Camera";
  11843. };
  11844. Camera.prototype.clone = function (name) {
  11845. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11846. };
  11847. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11848. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11849. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11850. switch (type) {
  11851. case "ArcRotateCamera":
  11852. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11853. case "DeviceOrientationCamera":
  11854. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11855. case "FollowCamera":
  11856. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11857. case "ArcFollowCamera":
  11858. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11859. case "GamepadCamera":
  11860. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11861. case "TouchCamera":
  11862. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11863. case "VirtualJoysticksCamera":
  11864. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11865. case "WebVRFreeCamera":
  11866. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11867. case "VRDeviceOrientationFreeCamera":
  11868. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11869. case "AnaglyphArcRotateCamera":
  11870. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11871. case "AnaglyphFreeCamera":
  11872. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11873. case "AnaglyphGamepadCamera":
  11874. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11875. case "AnaglyphUniversalCamera":
  11876. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11877. case "StereoscopicArcRotateCamera":
  11878. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11879. case "StereoscopicFreeCamera":
  11880. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11881. case "StereoscopicGamepadCamera":
  11882. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11883. case "StereoscopicUniversalCamera":
  11884. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11885. case "FreeCamera":
  11886. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11887. default:
  11888. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11889. }
  11890. };
  11891. Camera.Parse = function (parsedCamera, scene) {
  11892. var type = parsedCamera.type;
  11893. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11894. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11895. // Parent
  11896. if (parsedCamera.parentId) {
  11897. camera._waitingParentId = parsedCamera.parentId;
  11898. }
  11899. //If camera has an input manager, let it parse inputs settings
  11900. if (camera.inputs) {
  11901. camera.inputs.parse(parsedCamera);
  11902. camera._setupInputs();
  11903. }
  11904. // Target
  11905. if (parsedCamera.target) {
  11906. if (camera.setTarget) {
  11907. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11908. }
  11909. }
  11910. // Apply 3d rig, when found
  11911. if (parsedCamera.cameraRigMode) {
  11912. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11913. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11914. }
  11915. // Animations
  11916. if (parsedCamera.animations) {
  11917. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11918. var parsedAnimation = parsedCamera.animations[animationIndex];
  11919. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11920. }
  11921. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11922. }
  11923. if (parsedCamera.autoAnimate) {
  11924. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11925. }
  11926. return camera;
  11927. };
  11928. // Statics
  11929. Camera._PERSPECTIVE_CAMERA = 0;
  11930. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11931. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11932. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11933. Camera._RIG_MODE_NONE = 0;
  11934. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11935. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11936. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11937. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11938. Camera._RIG_MODE_VR = 20;
  11939. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11940. __decorate([
  11941. BABYLON.serializeAsVector3()
  11942. ], Camera.prototype, "position", void 0);
  11943. __decorate([
  11944. BABYLON.serializeAsVector3()
  11945. ], Camera.prototype, "upVector", void 0);
  11946. __decorate([
  11947. BABYLON.serialize()
  11948. ], Camera.prototype, "orthoLeft", void 0);
  11949. __decorate([
  11950. BABYLON.serialize()
  11951. ], Camera.prototype, "orthoRight", void 0);
  11952. __decorate([
  11953. BABYLON.serialize()
  11954. ], Camera.prototype, "orthoBottom", void 0);
  11955. __decorate([
  11956. BABYLON.serialize()
  11957. ], Camera.prototype, "orthoTop", void 0);
  11958. __decorate([
  11959. BABYLON.serialize()
  11960. ], Camera.prototype, "fov", void 0);
  11961. __decorate([
  11962. BABYLON.serialize()
  11963. ], Camera.prototype, "minZ", void 0);
  11964. __decorate([
  11965. BABYLON.serialize()
  11966. ], Camera.prototype, "maxZ", void 0);
  11967. __decorate([
  11968. BABYLON.serialize()
  11969. ], Camera.prototype, "inertia", void 0);
  11970. __decorate([
  11971. BABYLON.serialize()
  11972. ], Camera.prototype, "mode", void 0);
  11973. __decorate([
  11974. BABYLON.serialize()
  11975. ], Camera.prototype, "layerMask", void 0);
  11976. __decorate([
  11977. BABYLON.serialize()
  11978. ], Camera.prototype, "fovMode", void 0);
  11979. __decorate([
  11980. BABYLON.serialize()
  11981. ], Camera.prototype, "cameraRigMode", void 0);
  11982. __decorate([
  11983. BABYLON.serialize()
  11984. ], Camera.prototype, "interaxialDistance", void 0);
  11985. __decorate([
  11986. BABYLON.serialize()
  11987. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11988. return Camera;
  11989. })(BABYLON.Node);
  11990. BABYLON.Camera = Camera;
  11991. })(BABYLON || (BABYLON = {}));
  11992. var BABYLON;
  11993. (function (BABYLON) {
  11994. BABYLON.CameraInputTypes = {};
  11995. var CameraInputsManager = (function () {
  11996. function CameraInputsManager(camera) {
  11997. this.attached = {};
  11998. this.camera = camera;
  11999. this.checkInputs = function () { };
  12000. }
  12001. CameraInputsManager.prototype.add = function (input) {
  12002. var type = input.getSimpleName();
  12003. if (this.attached[type]) {
  12004. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12005. return;
  12006. }
  12007. this.attached[type] = input;
  12008. input.camera = this.camera;
  12009. //for checkInputs, we are dynamically creating a function
  12010. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12011. if (input.checkInputs) {
  12012. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12013. }
  12014. if (this.attachedElement) {
  12015. input.attachControl(this.attachedElement);
  12016. }
  12017. };
  12018. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12019. for (var cam in this.attached) {
  12020. var input = this.attached[cam];
  12021. if (input === inputToRemove) {
  12022. input.detachControl(this.attachedElement);
  12023. delete this.attached[cam];
  12024. this.rebuildInputCheck();
  12025. }
  12026. }
  12027. };
  12028. CameraInputsManager.prototype.removeByType = function (inputType) {
  12029. for (var cam in this.attached) {
  12030. var input = this.attached[cam];
  12031. if (input.getTypeName() === inputType) {
  12032. input.detachControl(this.attachedElement);
  12033. delete this.attached[cam];
  12034. this.rebuildInputCheck();
  12035. }
  12036. }
  12037. };
  12038. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12039. var current = this.checkInputs;
  12040. return function () {
  12041. current();
  12042. fn();
  12043. };
  12044. };
  12045. CameraInputsManager.prototype.attachInput = function (input) {
  12046. input.attachControl(this.attachedElement, this.noPreventDefault);
  12047. };
  12048. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12049. if (this.attachedElement) {
  12050. return;
  12051. }
  12052. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12053. this.attachedElement = element;
  12054. this.noPreventDefault = noPreventDefault;
  12055. for (var cam in this.attached) {
  12056. var input = this.attached[cam];
  12057. this.attached[cam].attachControl(element, noPreventDefault);
  12058. }
  12059. };
  12060. CameraInputsManager.prototype.detachElement = function (element) {
  12061. if (this.attachedElement !== element) {
  12062. return;
  12063. }
  12064. for (var cam in this.attached) {
  12065. var input = this.attached[cam];
  12066. this.attached[cam].detachControl(element);
  12067. }
  12068. this.attachedElement = null;
  12069. };
  12070. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12071. this.checkInputs = function () { };
  12072. for (var cam in this.attached) {
  12073. var input = this.attached[cam];
  12074. if (input.checkInputs) {
  12075. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12076. }
  12077. }
  12078. };
  12079. CameraInputsManager.prototype.clear = function () {
  12080. if (this.attachedElement) {
  12081. this.detachElement(this.attachedElement);
  12082. }
  12083. this.attached = {};
  12084. this.attachedElement = null;
  12085. this.checkInputs = function () { };
  12086. };
  12087. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12088. var inputs = {};
  12089. for (var cam in this.attached) {
  12090. var input = this.attached[cam];
  12091. var res = BABYLON.SerializationHelper.Serialize(input);
  12092. inputs[input.getTypeName()] = res;
  12093. }
  12094. serializedCamera.inputsmgr = inputs;
  12095. };
  12096. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12097. var parsedInputs = parsedCamera.inputsmgr;
  12098. if (parsedInputs) {
  12099. this.clear();
  12100. for (var n in parsedInputs) {
  12101. var construct = BABYLON.CameraInputTypes[n];
  12102. if (construct) {
  12103. var parsedinput = parsedInputs[n];
  12104. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12105. this.add(input);
  12106. }
  12107. }
  12108. }
  12109. else {
  12110. //2016-03-08 this part is for managing backward compatibility
  12111. for (var n in this.attached) {
  12112. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12113. if (construct) {
  12114. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12115. this.remove(this.attached[n]);
  12116. this.add(input);
  12117. }
  12118. }
  12119. }
  12120. };
  12121. return CameraInputsManager;
  12122. })();
  12123. BABYLON.CameraInputsManager = CameraInputsManager;
  12124. })(BABYLON || (BABYLON = {}));
  12125. var BABYLON;
  12126. (function (BABYLON) {
  12127. var FreeCameraMouseInput = (function () {
  12128. function FreeCameraMouseInput(touchEnabled) {
  12129. if (touchEnabled === void 0) { touchEnabled = true; }
  12130. this.touchEnabled = touchEnabled;
  12131. this.angularSensibility = 2000.0;
  12132. }
  12133. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12134. var _this = this;
  12135. if (!this._pointerInput) {
  12136. var camera = this.camera;
  12137. var engine = this.camera.getEngine();
  12138. this._pointerInput = function (p, s) {
  12139. var evt = p.event;
  12140. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12141. return;
  12142. }
  12143. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12144. try {
  12145. evt.srcElement.setPointerCapture(evt.pointerId);
  12146. }
  12147. catch (e) {
  12148. }
  12149. _this.previousPosition = {
  12150. x: evt.clientX,
  12151. y: evt.clientY
  12152. };
  12153. if (!noPreventDefault) {
  12154. evt.preventDefault();
  12155. }
  12156. }
  12157. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12158. try {
  12159. evt.srcElement.releasePointerCapture(evt.pointerId);
  12160. }
  12161. catch (e) {
  12162. }
  12163. _this.previousPosition = null;
  12164. if (!noPreventDefault) {
  12165. evt.preventDefault();
  12166. }
  12167. }
  12168. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12169. if (!_this.previousPosition && !engine.isPointerLock) {
  12170. return;
  12171. }
  12172. var offsetX;
  12173. var offsetY;
  12174. if (!engine.isPointerLock) {
  12175. offsetX = evt.clientX - _this.previousPosition.x;
  12176. offsetY = evt.clientY - _this.previousPosition.y;
  12177. }
  12178. else {
  12179. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12180. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12181. }
  12182. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12183. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12184. _this.previousPosition = {
  12185. x: evt.clientX,
  12186. y: evt.clientY
  12187. };
  12188. if (!noPreventDefault) {
  12189. evt.preventDefault();
  12190. }
  12191. }
  12192. };
  12193. }
  12194. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12195. };
  12196. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12197. if (this._observer && element) {
  12198. this.camera.getScene().onPointerObservable.remove(this._observer);
  12199. this._observer = null;
  12200. this.previousPosition = null;
  12201. }
  12202. };
  12203. FreeCameraMouseInput.prototype.getTypeName = function () {
  12204. return "FreeCameraMouseInput";
  12205. };
  12206. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12207. return "mouse";
  12208. };
  12209. __decorate([
  12210. BABYLON.serialize()
  12211. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12212. return FreeCameraMouseInput;
  12213. })();
  12214. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12215. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12216. })(BABYLON || (BABYLON = {}));
  12217. var BABYLON;
  12218. (function (BABYLON) {
  12219. var FreeCameraKeyboardMoveInput = (function () {
  12220. function FreeCameraKeyboardMoveInput() {
  12221. this._keys = [];
  12222. this.keysUp = [38];
  12223. this.keysDown = [40];
  12224. this.keysLeft = [37];
  12225. this.keysRight = [39];
  12226. }
  12227. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12228. var _this = this;
  12229. if (!this._onKeyDown) {
  12230. this._onKeyDown = function (evt) {
  12231. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12232. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12233. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12234. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12235. var index = _this._keys.indexOf(evt.keyCode);
  12236. if (index === -1) {
  12237. _this._keys.push(evt.keyCode);
  12238. }
  12239. if (!noPreventDefault) {
  12240. evt.preventDefault();
  12241. }
  12242. }
  12243. };
  12244. this._onKeyUp = function (evt) {
  12245. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12246. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12247. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12248. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12249. var index = _this._keys.indexOf(evt.keyCode);
  12250. if (index >= 0) {
  12251. _this._keys.splice(index, 1);
  12252. }
  12253. if (!noPreventDefault) {
  12254. evt.preventDefault();
  12255. }
  12256. }
  12257. };
  12258. BABYLON.Tools.RegisterTopRootEvents([
  12259. { name: "keydown", handler: this._onKeyDown },
  12260. { name: "keyup", handler: this._onKeyUp },
  12261. { name: "blur", handler: this._onLostFocus }
  12262. ]);
  12263. }
  12264. };
  12265. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12266. if (this._onKeyDown) {
  12267. BABYLON.Tools.UnregisterTopRootEvents([
  12268. { name: "keydown", handler: this._onKeyDown },
  12269. { name: "keyup", handler: this._onKeyUp },
  12270. { name: "blur", handler: this._onLostFocus }
  12271. ]);
  12272. this._keys = [];
  12273. this._onKeyDown = null;
  12274. this._onKeyUp = null;
  12275. }
  12276. };
  12277. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12278. if (this._onKeyDown) {
  12279. var camera = this.camera;
  12280. // Keyboard
  12281. for (var index = 0; index < this._keys.length; index++) {
  12282. var keyCode = this._keys[index];
  12283. var speed = camera._computeLocalCameraSpeed();
  12284. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12285. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12286. }
  12287. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12288. camera._localDirection.copyFromFloats(0, 0, speed);
  12289. }
  12290. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12291. camera._localDirection.copyFromFloats(speed, 0, 0);
  12292. }
  12293. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12294. camera._localDirection.copyFromFloats(0, 0, -speed);
  12295. }
  12296. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12297. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12298. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12299. }
  12300. }
  12301. };
  12302. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12303. return "FreeCameraKeyboardMoveInput";
  12304. };
  12305. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12306. this._keys = [];
  12307. };
  12308. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12309. return "keyboard";
  12310. };
  12311. __decorate([
  12312. BABYLON.serialize()
  12313. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12314. __decorate([
  12315. BABYLON.serialize()
  12316. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12317. __decorate([
  12318. BABYLON.serialize()
  12319. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12320. __decorate([
  12321. BABYLON.serialize()
  12322. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12323. return FreeCameraKeyboardMoveInput;
  12324. })();
  12325. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12326. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12327. })(BABYLON || (BABYLON = {}));
  12328. var BABYLON;
  12329. (function (BABYLON) {
  12330. var FreeCameraTouchInput = (function () {
  12331. function FreeCameraTouchInput() {
  12332. this._offsetX = null;
  12333. this._offsetY = null;
  12334. this._pointerCount = 0;
  12335. this._pointerPressed = [];
  12336. this.touchAngularSensibility = 200000.0;
  12337. this.touchMoveSensibility = 250.0;
  12338. }
  12339. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12340. var _this = this;
  12341. var previousPosition;
  12342. if (this._pointerInput === undefined) {
  12343. this._onLostFocus = function (evt) {
  12344. _this._offsetX = null;
  12345. _this._offsetY = null;
  12346. };
  12347. this._pointerInput = function (p, s) {
  12348. var evt = p.event;
  12349. if (evt.pointerType === "mouse") {
  12350. return;
  12351. }
  12352. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12353. if (!noPreventDefault) {
  12354. evt.preventDefault();
  12355. }
  12356. _this._pointerPressed.push(evt.pointerId);
  12357. if (_this._pointerPressed.length !== 1) {
  12358. return;
  12359. }
  12360. previousPosition = {
  12361. x: evt.clientX,
  12362. y: evt.clientY
  12363. };
  12364. }
  12365. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12366. if (!noPreventDefault) {
  12367. evt.preventDefault();
  12368. }
  12369. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12370. if (index === -1) {
  12371. return;
  12372. }
  12373. _this._pointerPressed.splice(index, 1);
  12374. if (index != 0) {
  12375. return;
  12376. }
  12377. previousPosition = null;
  12378. _this._offsetX = null;
  12379. _this._offsetY = null;
  12380. }
  12381. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12382. if (!noPreventDefault) {
  12383. evt.preventDefault();
  12384. }
  12385. if (!previousPosition) {
  12386. return;
  12387. }
  12388. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12389. if (index != 0) {
  12390. return;
  12391. }
  12392. _this._offsetX = evt.clientX - previousPosition.x;
  12393. _this._offsetY = -(evt.clientY - previousPosition.y);
  12394. }
  12395. };
  12396. }
  12397. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12398. element.addEventListener("blur", this._onLostFocus);
  12399. };
  12400. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12401. if (this._pointerInput && element) {
  12402. this.camera.getScene().onPointerObservable.remove(this._observer);
  12403. this._observer = null;
  12404. element.removeEventListener("blur", this._onLostFocus);
  12405. this._onLostFocus = null;
  12406. this._pointerPressed = [];
  12407. this._offsetX = null;
  12408. this._offsetY = null;
  12409. this._pointerCount = 0;
  12410. }
  12411. };
  12412. FreeCameraTouchInput.prototype.checkInputs = function () {
  12413. if (this._offsetX) {
  12414. var camera = this.camera;
  12415. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12416. if (this._pointerPressed.length > 1) {
  12417. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12418. }
  12419. else {
  12420. var speed = camera._computeLocalCameraSpeed();
  12421. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12422. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12423. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12424. }
  12425. }
  12426. };
  12427. FreeCameraTouchInput.prototype.getTypeName = function () {
  12428. return "FreeCameraTouchInput";
  12429. };
  12430. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12431. return "touch";
  12432. };
  12433. __decorate([
  12434. BABYLON.serialize()
  12435. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12436. __decorate([
  12437. BABYLON.serialize()
  12438. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12439. return FreeCameraTouchInput;
  12440. })();
  12441. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12442. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12443. })(BABYLON || (BABYLON = {}));
  12444. var BABYLON;
  12445. (function (BABYLON) {
  12446. var FreeCameraDeviceOrientationInput = (function () {
  12447. function FreeCameraDeviceOrientationInput() {
  12448. var _this = this;
  12449. this._screenOrientationAngle = 0;
  12450. this._screenQuaternion = new BABYLON.Quaternion();
  12451. this._alpha = 0;
  12452. this._beta = 0;
  12453. this._gamma = 0;
  12454. this._orientationChanged = function () {
  12455. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12456. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12457. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12458. };
  12459. this._deviceOrientation = function (evt) {
  12460. _this._alpha = evt.alpha;
  12461. _this._beta = evt.beta;
  12462. _this._gamma = evt.gamma;
  12463. };
  12464. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12465. this._orientationChanged();
  12466. }
  12467. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12468. get: function () {
  12469. return this._camera;
  12470. },
  12471. set: function (camera) {
  12472. this._camera = camera;
  12473. if (!this._camera.rotationQuaternion)
  12474. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12480. window.addEventListener("orientationchange", this._orientationChanged);
  12481. window.addEventListener("deviceorientation", this._deviceOrientation);
  12482. };
  12483. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12484. window.removeEventListener("orientationchange", this._orientationChanged);
  12485. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12486. };
  12487. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12488. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12489. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12490. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12491. //Mirror on XY Plane
  12492. this._camera.rotationQuaternion.z *= -1;
  12493. this._camera.rotationQuaternion.w *= -1;
  12494. };
  12495. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12496. return "FreeCameraDeviceOrientationInput";
  12497. };
  12498. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12499. return "deviceOrientation";
  12500. };
  12501. return FreeCameraDeviceOrientationInput;
  12502. })();
  12503. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12504. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12505. })(BABYLON || (BABYLON = {}));
  12506. var BABYLON;
  12507. (function (BABYLON) {
  12508. var FreeCameraVRDeviceOrientationInput = (function () {
  12509. function FreeCameraVRDeviceOrientationInput() {
  12510. this.alphaCorrection = 1;
  12511. this.betaCorrection = 1;
  12512. this.gammaCorrection = 1;
  12513. this._alpha = 0;
  12514. this._beta = 0;
  12515. this._gamma = 0;
  12516. this._dirty = false;
  12517. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12518. }
  12519. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12520. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12521. };
  12522. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12523. var camera = this.camera;
  12524. this._alpha = evt.alpha;
  12525. this._beta = evt.beta;
  12526. this._gamma = evt.gamma;
  12527. this._dirty = true;
  12528. };
  12529. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12530. if (this._dirty) {
  12531. this._dirty = false;
  12532. var rotationX = this._gamma;
  12533. if (rotationX < 0) {
  12534. rotationX = 90 + rotationX;
  12535. }
  12536. else {
  12537. // Incline it in the correct angle.
  12538. rotationX = 270 - rotationX;
  12539. }
  12540. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12541. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12542. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12543. }
  12544. };
  12545. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12546. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12547. };
  12548. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12549. return "FreeCameraVRDeviceOrientationInput";
  12550. };
  12551. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12552. return "VRDeviceOrientation";
  12553. };
  12554. return FreeCameraVRDeviceOrientationInput;
  12555. })();
  12556. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12557. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12558. })(BABYLON || (BABYLON = {}));
  12559. var BABYLON;
  12560. (function (BABYLON) {
  12561. var FreeCameraGamepadInput = (function () {
  12562. function FreeCameraGamepadInput() {
  12563. this.gamepadAngularSensibility = 200;
  12564. this.gamepadMoveSensibility = 40;
  12565. }
  12566. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12567. var _this = this;
  12568. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12569. };
  12570. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12571. if (this._gamepads) {
  12572. this._gamepads.dispose();
  12573. }
  12574. this.gamepad = null;
  12575. };
  12576. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12577. if (this.gamepad) {
  12578. var camera = this.camera;
  12579. var LSValues = this.gamepad.leftStick;
  12580. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12581. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12582. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12583. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12584. var RSValues = this.gamepad.rightStick;
  12585. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12586. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12587. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12588. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12589. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12590. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12591. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12592. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12593. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12594. }
  12595. };
  12596. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12597. // Only the first gamepad can control the camera
  12598. if (gamepad.index === 0) {
  12599. this.gamepad = gamepad;
  12600. }
  12601. };
  12602. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12603. return "FreeCameraGamepadInput";
  12604. };
  12605. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12606. return "gamepad";
  12607. };
  12608. __decorate([
  12609. BABYLON.serialize()
  12610. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12611. __decorate([
  12612. BABYLON.serialize()
  12613. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12614. return FreeCameraGamepadInput;
  12615. })();
  12616. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12617. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12618. })(BABYLON || (BABYLON = {}));
  12619. var BABYLON;
  12620. (function (BABYLON) {
  12621. var ArcRotateCameraKeyboardMoveInput = (function () {
  12622. function ArcRotateCameraKeyboardMoveInput() {
  12623. this._keys = [];
  12624. this.keysUp = [38];
  12625. this.keysDown = [40];
  12626. this.keysLeft = [37];
  12627. this.keysRight = [39];
  12628. }
  12629. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12630. var _this = this;
  12631. this._onKeyDown = function (evt) {
  12632. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12633. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12634. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12635. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12636. var index = _this._keys.indexOf(evt.keyCode);
  12637. if (index === -1) {
  12638. _this._keys.push(evt.keyCode);
  12639. }
  12640. if (evt.preventDefault) {
  12641. if (!noPreventDefault) {
  12642. evt.preventDefault();
  12643. }
  12644. }
  12645. }
  12646. };
  12647. this._onKeyUp = function (evt) {
  12648. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12649. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12650. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12651. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12652. var index = _this._keys.indexOf(evt.keyCode);
  12653. if (index >= 0) {
  12654. _this._keys.splice(index, 1);
  12655. }
  12656. if (evt.preventDefault) {
  12657. if (!noPreventDefault) {
  12658. evt.preventDefault();
  12659. }
  12660. }
  12661. }
  12662. };
  12663. this._onLostFocus = function () {
  12664. _this._keys = [];
  12665. };
  12666. BABYLON.Tools.RegisterTopRootEvents([
  12667. { name: "keydown", handler: this._onKeyDown },
  12668. { name: "keyup", handler: this._onKeyUp },
  12669. { name: "blur", handler: this._onLostFocus }
  12670. ]);
  12671. };
  12672. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12673. BABYLON.Tools.UnregisterTopRootEvents([
  12674. { name: "keydown", handler: this._onKeyDown },
  12675. { name: "keyup", handler: this._onKeyUp },
  12676. { name: "blur", handler: this._onLostFocus }
  12677. ]);
  12678. this._keys = [];
  12679. this._onKeyDown = null;
  12680. this._onKeyUp = null;
  12681. this._onLostFocus = null;
  12682. };
  12683. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12684. if (this._onKeyDown) {
  12685. var camera = this.camera;
  12686. for (var index = 0; index < this._keys.length; index++) {
  12687. var keyCode = this._keys[index];
  12688. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12689. camera.inertialAlphaOffset -= 0.01;
  12690. }
  12691. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12692. camera.inertialBetaOffset -= 0.01;
  12693. }
  12694. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12695. camera.inertialAlphaOffset += 0.01;
  12696. }
  12697. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12698. camera.inertialBetaOffset += 0.01;
  12699. }
  12700. }
  12701. }
  12702. };
  12703. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12704. return "ArcRotateCameraKeyboardMoveInput";
  12705. };
  12706. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12707. return "keyboard";
  12708. };
  12709. __decorate([
  12710. BABYLON.serialize()
  12711. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12712. __decorate([
  12713. BABYLON.serialize()
  12714. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12715. __decorate([
  12716. BABYLON.serialize()
  12717. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12718. __decorate([
  12719. BABYLON.serialize()
  12720. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12721. return ArcRotateCameraKeyboardMoveInput;
  12722. })();
  12723. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12724. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12725. })(BABYLON || (BABYLON = {}));
  12726. var BABYLON;
  12727. (function (BABYLON) {
  12728. var ArcRotateCameraMouseWheelInput = (function () {
  12729. function ArcRotateCameraMouseWheelInput() {
  12730. this.wheelPrecision = 3.0;
  12731. }
  12732. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12733. var _this = this;
  12734. this._wheel = function (p, s) {
  12735. //sanity check - this should be a PointerWheel event.
  12736. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12737. return;
  12738. var event = p.event;
  12739. var delta = 0;
  12740. if (event.wheelDelta) {
  12741. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12742. }
  12743. else if (event.detail) {
  12744. delta = -event.detail / _this.wheelPrecision;
  12745. }
  12746. if (delta)
  12747. _this.camera.inertialRadiusOffset += delta;
  12748. if (event.preventDefault) {
  12749. if (!noPreventDefault) {
  12750. event.preventDefault();
  12751. }
  12752. }
  12753. };
  12754. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12755. };
  12756. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12757. if (this._observer && element) {
  12758. this.camera.getScene().onPointerObservable.remove(this._observer);
  12759. this._observer = null;
  12760. this._wheel = null;
  12761. }
  12762. };
  12763. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12764. return "ArcRotateCameraMouseWheelInput";
  12765. };
  12766. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12767. return "mousewheel";
  12768. };
  12769. __decorate([
  12770. BABYLON.serialize()
  12771. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12772. return ArcRotateCameraMouseWheelInput;
  12773. })();
  12774. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12775. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12776. })(BABYLON || (BABYLON = {}));
  12777. var BABYLON;
  12778. (function (BABYLON) {
  12779. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12780. var ArcRotateCameraPointersInput = (function () {
  12781. function ArcRotateCameraPointersInput() {
  12782. this.angularSensibilityX = 1000.0;
  12783. this.angularSensibilityY = 1000.0;
  12784. this.pinchPrecision = 6.0;
  12785. this.panningSensibility = 50.0;
  12786. this._isRightClick = false;
  12787. this._isCtrlPushed = false;
  12788. this.pinchInwards = true;
  12789. }
  12790. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12791. var _this = this;
  12792. var engine = this.camera.getEngine();
  12793. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12794. var pointA, pointB;
  12795. var previousPinchDistance = 0;
  12796. this._pointerInput = function (p, s) {
  12797. var evt = p.event;
  12798. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12799. try {
  12800. evt.srcElement.setPointerCapture(evt.pointerId);
  12801. }
  12802. catch (e) {
  12803. }
  12804. // Manage panning with right click
  12805. _this._isRightClick = evt.button === 2;
  12806. // manage pointers
  12807. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12808. if (pointA === undefined) {
  12809. pointA = cacheSoloPointer;
  12810. }
  12811. else if (pointB === undefined) {
  12812. pointB = cacheSoloPointer;
  12813. }
  12814. if (!noPreventDefault) {
  12815. evt.preventDefault();
  12816. }
  12817. }
  12818. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12819. try {
  12820. evt.srcElement.releasePointerCapture(evt.pointerId);
  12821. }
  12822. catch (e) {
  12823. }
  12824. cacheSoloPointer = null;
  12825. previousPinchDistance = 0;
  12826. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12827. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12828. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12829. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12830. pointA = pointB = undefined;
  12831. if (!noPreventDefault) {
  12832. evt.preventDefault();
  12833. }
  12834. }
  12835. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12836. if (!noPreventDefault) {
  12837. evt.preventDefault();
  12838. }
  12839. // One button down
  12840. if (pointA && pointB === undefined) {
  12841. if (_this.panningSensibility !== 0 &&
  12842. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12843. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12844. _this.camera
  12845. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12846. _this.camera
  12847. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12848. }
  12849. else {
  12850. var offsetX = evt.clientX - cacheSoloPointer.x;
  12851. var offsetY = evt.clientY - cacheSoloPointer.y;
  12852. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12853. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12854. }
  12855. cacheSoloPointer.x = evt.clientX;
  12856. cacheSoloPointer.y = evt.clientY;
  12857. }
  12858. else if (pointA && pointB) {
  12859. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12860. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12861. ed.x = evt.clientX;
  12862. ed.y = evt.clientY;
  12863. var direction = _this.pinchInwards ? 1 : -1;
  12864. var distX = pointA.x - pointB.x;
  12865. var distY = pointA.y - pointB.y;
  12866. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12867. if (previousPinchDistance === 0) {
  12868. previousPinchDistance = pinchSquaredDistance;
  12869. return;
  12870. }
  12871. if (pinchSquaredDistance !== previousPinchDistance) {
  12872. _this.camera
  12873. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12874. (_this.pinchPrecision *
  12875. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12876. direction);
  12877. previousPinchDistance = pinchSquaredDistance;
  12878. }
  12879. }
  12880. }
  12881. };
  12882. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12883. this._onContextMenu = function (evt) {
  12884. evt.preventDefault();
  12885. };
  12886. if (!this.camera._useCtrlForPanning) {
  12887. element.addEventListener("contextmenu", this._onContextMenu, false);
  12888. }
  12889. this._onLostFocus = function () {
  12890. //this._keys = [];
  12891. pointA = pointB = undefined;
  12892. previousPinchDistance = 0;
  12893. cacheSoloPointer = null;
  12894. };
  12895. this._onKeyDown = function (evt) {
  12896. _this._isCtrlPushed = evt.ctrlKey;
  12897. };
  12898. this._onKeyUp = function (evt) {
  12899. _this._isCtrlPushed = evt.ctrlKey;
  12900. };
  12901. this._onMouseMove = function (evt) {
  12902. if (!engine.isPointerLock) {
  12903. return;
  12904. }
  12905. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12906. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12907. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12908. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12909. if (!noPreventDefault) {
  12910. evt.preventDefault();
  12911. }
  12912. };
  12913. this._onGestureStart = function (e) {
  12914. if (window.MSGesture === undefined) {
  12915. return;
  12916. }
  12917. if (!_this._MSGestureHandler) {
  12918. _this._MSGestureHandler = new MSGesture();
  12919. _this._MSGestureHandler.target = element;
  12920. }
  12921. _this._MSGestureHandler.addPointer(e.pointerId);
  12922. };
  12923. this._onGesture = function (e) {
  12924. _this.camera.radius *= e.scale;
  12925. if (e.preventDefault) {
  12926. if (!noPreventDefault) {
  12927. e.stopPropagation();
  12928. e.preventDefault();
  12929. }
  12930. }
  12931. };
  12932. element.addEventListener("mousemove", this._onMouseMove, false);
  12933. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12934. element.addEventListener("MSGestureChange", this._onGesture, false);
  12935. BABYLON.Tools.RegisterTopRootEvents([
  12936. { name: "keydown", handler: this._onKeyDown },
  12937. { name: "keyup", handler: this._onKeyUp },
  12938. { name: "blur", handler: this._onLostFocus }
  12939. ]);
  12940. };
  12941. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12942. if (element && this._observer) {
  12943. this.camera.getScene().onPointerObservable.remove(this._observer);
  12944. this._observer = null;
  12945. element.removeEventListener("contextmenu", this._onContextMenu);
  12946. element.removeEventListener("mousemove", this._onMouseMove);
  12947. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12948. element.removeEventListener("MSGestureChange", this._onGesture);
  12949. this._isRightClick = false;
  12950. this._isCtrlPushed = false;
  12951. this.pinchInwards = true;
  12952. this._onKeyDown = null;
  12953. this._onKeyUp = null;
  12954. this._onMouseMove = null;
  12955. this._onGestureStart = null;
  12956. this._onGesture = null;
  12957. this._MSGestureHandler = null;
  12958. this._onLostFocus = null;
  12959. this._onContextMenu = null;
  12960. }
  12961. BABYLON.Tools.UnregisterTopRootEvents([
  12962. { name: "keydown", handler: this._onKeyDown },
  12963. { name: "keyup", handler: this._onKeyUp },
  12964. { name: "blur", handler: this._onLostFocus }
  12965. ]);
  12966. };
  12967. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12968. return "ArcRotateCameraPointersInput";
  12969. };
  12970. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12971. return "pointers";
  12972. };
  12973. __decorate([
  12974. BABYLON.serialize()
  12975. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12976. __decorate([
  12977. BABYLON.serialize()
  12978. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12979. __decorate([
  12980. BABYLON.serialize()
  12981. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12982. __decorate([
  12983. BABYLON.serialize()
  12984. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12985. return ArcRotateCameraPointersInput;
  12986. })();
  12987. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12988. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12989. })(BABYLON || (BABYLON = {}));
  12990. var BABYLON;
  12991. (function (BABYLON) {
  12992. var ArcRotateCameraGamepadInput = (function () {
  12993. function ArcRotateCameraGamepadInput() {
  12994. this.gamepadRotationSensibility = 80;
  12995. this.gamepadMoveSensibility = 40;
  12996. }
  12997. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12998. var _this = this;
  12999. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13000. };
  13001. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13002. if (this._gamepads) {
  13003. this._gamepads.dispose();
  13004. }
  13005. this.gamepad = null;
  13006. };
  13007. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13008. if (this.gamepad) {
  13009. var camera = this.camera;
  13010. var RSValues = this.gamepad.rightStick;
  13011. if (RSValues.x != 0) {
  13012. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13013. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13014. camera.inertialAlphaOffset += normalizedRX;
  13015. }
  13016. }
  13017. if (RSValues.y != 0) {
  13018. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13019. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13020. camera.inertialBetaOffset += normalizedRY;
  13021. }
  13022. }
  13023. var LSValues = this.gamepad.leftStick;
  13024. if (LSValues.y != 0) {
  13025. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13026. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13027. this.camera.inertialRadiusOffset -= normalizedLY;
  13028. }
  13029. }
  13030. }
  13031. };
  13032. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13033. // Only the first gamepad can control the camera
  13034. if (gamepad.index === 0) {
  13035. this.gamepad = gamepad;
  13036. }
  13037. };
  13038. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13039. return "ArcRotateCameraGamepadInput";
  13040. };
  13041. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13042. return "gamepad";
  13043. };
  13044. __decorate([
  13045. BABYLON.serialize()
  13046. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13047. __decorate([
  13048. BABYLON.serialize()
  13049. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13050. return ArcRotateCameraGamepadInput;
  13051. })();
  13052. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13053. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13054. })(BABYLON || (BABYLON = {}));
  13055. var BABYLON;
  13056. (function (BABYLON) {
  13057. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13058. function ArcRotateCameraVRDeviceOrientationInput() {
  13059. this.alphaCorrection = 1;
  13060. this.betaCorrection = 1;
  13061. this.gammaCorrection = 1;
  13062. this._alpha = 0;
  13063. this._beta = 0;
  13064. this._gamma = 0;
  13065. this._dirty = false;
  13066. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13067. }
  13068. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13069. this.camera.attachControl(element, noPreventDefault);
  13070. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13071. };
  13072. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13073. var camera = this.camera;
  13074. this._alpha = +evt.alpha | 0;
  13075. this._beta = +evt.beta | 0;
  13076. this._gamma = +evt.gamma | 0;
  13077. this._dirty = true;
  13078. };
  13079. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13080. if (this._dirty) {
  13081. this._dirty = false;
  13082. if (this._gamma < 0) {
  13083. this._gamma = 180 + this._gamma;
  13084. }
  13085. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13086. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13087. }
  13088. };
  13089. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13090. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13091. };
  13092. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13093. return "ArcRotateCameraVRDeviceOrientationInput";
  13094. };
  13095. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13096. return "VRDeviceOrientation";
  13097. };
  13098. return ArcRotateCameraVRDeviceOrientationInput;
  13099. })();
  13100. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13101. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13102. })(BABYLON || (BABYLON = {}));
  13103. var BABYLON;
  13104. (function (BABYLON) {
  13105. var TargetCamera = (function (_super) {
  13106. __extends(TargetCamera, _super);
  13107. function TargetCamera(name, position, scene) {
  13108. _super.call(this, name, position, scene);
  13109. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13110. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13111. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13112. this.speed = 2.0;
  13113. this.noRotationConstraint = false;
  13114. this.lockedTarget = null;
  13115. this._currentTarget = BABYLON.Vector3.Zero();
  13116. this._viewMatrix = BABYLON.Matrix.Zero();
  13117. this._camMatrix = BABYLON.Matrix.Zero();
  13118. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13119. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13120. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13121. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13122. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13123. this._lookAtTemp = BABYLON.Matrix.Zero();
  13124. this._tempMatrix = BABYLON.Matrix.Zero();
  13125. }
  13126. TargetCamera.prototype.getFrontPosition = function (distance) {
  13127. var direction = this.getTarget().subtract(this.position);
  13128. direction.normalize();
  13129. direction.scaleInPlace(distance);
  13130. return this.globalPosition.add(direction);
  13131. };
  13132. TargetCamera.prototype._getLockedTargetPosition = function () {
  13133. if (!this.lockedTarget) {
  13134. return null;
  13135. }
  13136. return this.lockedTarget.position || this.lockedTarget;
  13137. };
  13138. // Cache
  13139. TargetCamera.prototype._initCache = function () {
  13140. _super.prototype._initCache.call(this);
  13141. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13142. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13143. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13144. };
  13145. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13146. if (!ignoreParentClass) {
  13147. _super.prototype._updateCache.call(this);
  13148. }
  13149. var lockedTargetPosition = this._getLockedTargetPosition();
  13150. if (!lockedTargetPosition) {
  13151. this._cache.lockedTarget = null;
  13152. }
  13153. else {
  13154. if (!this._cache.lockedTarget) {
  13155. this._cache.lockedTarget = lockedTargetPosition.clone();
  13156. }
  13157. else {
  13158. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13159. }
  13160. }
  13161. this._cache.rotation.copyFrom(this.rotation);
  13162. if (this.rotationQuaternion)
  13163. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13164. };
  13165. // Synchronized
  13166. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13167. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13168. return false;
  13169. }
  13170. var lockedTargetPosition = this._getLockedTargetPosition();
  13171. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13172. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13173. };
  13174. // Methods
  13175. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13176. var engine = this.getEngine();
  13177. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  13178. };
  13179. // Target
  13180. TargetCamera.prototype.setTarget = function (target) {
  13181. this.upVector.normalize();
  13182. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13183. this._camMatrix.invert();
  13184. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13185. var vDir = target.subtract(this.position);
  13186. if (vDir.x >= 0.0) {
  13187. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13188. }
  13189. else {
  13190. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13191. }
  13192. this.rotation.z = 0;
  13193. if (isNaN(this.rotation.x)) {
  13194. this.rotation.x = 0;
  13195. }
  13196. if (isNaN(this.rotation.y)) {
  13197. this.rotation.y = 0;
  13198. }
  13199. if (isNaN(this.rotation.z)) {
  13200. this.rotation.z = 0;
  13201. }
  13202. if (this.rotationQuaternion) {
  13203. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13204. }
  13205. };
  13206. TargetCamera.prototype.getTarget = function () {
  13207. return this._currentTarget;
  13208. };
  13209. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13210. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13211. };
  13212. TargetCamera.prototype._updatePosition = function () {
  13213. this.position.addInPlace(this.cameraDirection);
  13214. };
  13215. TargetCamera.prototype._checkInputs = function () {
  13216. var needToMove = this._decideIfNeedsToMove();
  13217. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13218. // Move
  13219. if (needToMove) {
  13220. this._updatePosition();
  13221. }
  13222. // Rotate
  13223. if (needToRotate) {
  13224. this.rotation.x += this.cameraRotation.x;
  13225. this.rotation.y += this.cameraRotation.y;
  13226. if (!this.noRotationConstraint) {
  13227. var limit = (Math.PI / 2) * 0.95;
  13228. if (this.rotation.x > limit)
  13229. this.rotation.x = limit;
  13230. if (this.rotation.x < -limit)
  13231. this.rotation.x = -limit;
  13232. }
  13233. }
  13234. // Inertia
  13235. if (needToMove) {
  13236. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13237. this.cameraDirection.x = 0;
  13238. }
  13239. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13240. this.cameraDirection.y = 0;
  13241. }
  13242. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13243. this.cameraDirection.z = 0;
  13244. }
  13245. this.cameraDirection.scaleInPlace(this.inertia);
  13246. }
  13247. if (needToRotate) {
  13248. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13249. this.cameraRotation.x = 0;
  13250. }
  13251. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13252. this.cameraRotation.y = 0;
  13253. }
  13254. this.cameraRotation.scaleInPlace(this.inertia);
  13255. }
  13256. _super.prototype._checkInputs.call(this);
  13257. };
  13258. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13259. if (this.rotationQuaternion) {
  13260. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13261. //update the up vector!
  13262. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13263. }
  13264. else {
  13265. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13266. }
  13267. };
  13268. TargetCamera.prototype._getViewMatrix = function () {
  13269. if (!this.lockedTarget) {
  13270. // Compute
  13271. this._updateCameraRotationMatrix();
  13272. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13273. // Computing target and final matrix
  13274. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13275. }
  13276. else {
  13277. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13278. }
  13279. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13280. return this._viewMatrix;
  13281. };
  13282. TargetCamera.prototype._getVRViewMatrix = function () {
  13283. this._updateCameraRotationMatrix();
  13284. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13285. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  13286. // Computing target and final matrix
  13287. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13288. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  13289. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  13290. return this._viewMatrix;
  13291. };
  13292. /**
  13293. * @override
  13294. * Override Camera.createRigCamera
  13295. */
  13296. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13297. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13298. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13299. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13300. if (!this.rotationQuaternion) {
  13301. this.rotationQuaternion = new BABYLON.Quaternion();
  13302. }
  13303. rigCamera._cameraRigParams = {};
  13304. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  13305. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  13306. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13307. }
  13308. return rigCamera;
  13309. }
  13310. return null;
  13311. };
  13312. /**
  13313. * @override
  13314. * Override Camera._updateRigCameras
  13315. */
  13316. TargetCamera.prototype._updateRigCameras = function () {
  13317. var camLeft = this._rigCameras[0];
  13318. var camRight = this._rigCameras[1];
  13319. switch (this.cameraRigMode) {
  13320. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13321. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13322. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13323. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13324. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13325. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13326. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13327. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13328. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13329. camLeft.setTarget(this.getTarget());
  13330. camRight.setTarget(this.getTarget());
  13331. break;
  13332. case BABYLON.Camera.RIG_MODE_VR:
  13333. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13334. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13335. camLeft.position.copyFrom(this.position);
  13336. camRight.position.copyFrom(this.position);
  13337. break;
  13338. }
  13339. _super.prototype._updateRigCameras.call(this);
  13340. };
  13341. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13342. if (!this._rigCamTransformMatrix) {
  13343. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13344. }
  13345. var target = this.getTarget();
  13346. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13347. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13349. };
  13350. TargetCamera.prototype.getTypeName = function () {
  13351. return "TargetCamera";
  13352. };
  13353. __decorate([
  13354. BABYLON.serializeAsVector3()
  13355. ], TargetCamera.prototype, "rotation", void 0);
  13356. __decorate([
  13357. BABYLON.serialize()
  13358. ], TargetCamera.prototype, "speed", void 0);
  13359. __decorate([
  13360. BABYLON.serializeAsMeshReference("lockedTargetId")
  13361. ], TargetCamera.prototype, "lockedTarget", void 0);
  13362. return TargetCamera;
  13363. })(BABYLON.Camera);
  13364. BABYLON.TargetCamera = TargetCamera;
  13365. })(BABYLON || (BABYLON = {}));
  13366. var BABYLON;
  13367. (function (BABYLON) {
  13368. var FreeCamera = (function (_super) {
  13369. __extends(FreeCamera, _super);
  13370. function FreeCamera(name, position, scene) {
  13371. var _this = this;
  13372. _super.call(this, name, position, scene);
  13373. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13374. this.checkCollisions = false;
  13375. this.applyGravity = false;
  13376. this._collider = new BABYLON.Collider();
  13377. this._needMoveForGravity = false;
  13378. this._oldPosition = BABYLON.Vector3.Zero();
  13379. this._diffPosition = BABYLON.Vector3.Zero();
  13380. this._newPosition = BABYLON.Vector3.Zero();
  13381. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13382. if (collidedMesh === void 0) { collidedMesh = null; }
  13383. //TODO move this to the collision coordinator!
  13384. if (_this.getScene().workerCollisions)
  13385. newPosition.multiplyInPlace(_this._collider.radius);
  13386. var updatePosition = function (newPos) {
  13387. _this._newPosition.copyFrom(newPos);
  13388. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13389. var oldPosition = _this.position.clone();
  13390. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13391. _this.position.addInPlace(_this._diffPosition);
  13392. if (_this.onCollide && collidedMesh) {
  13393. _this.onCollide(collidedMesh);
  13394. }
  13395. }
  13396. };
  13397. updatePosition(newPosition);
  13398. };
  13399. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13400. this.inputs.addKeyboard().addMouse();
  13401. }
  13402. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13403. //-- begin properties for backward compatibility for inputs
  13404. get: function () {
  13405. var mouse = this.inputs.attached["mouse"];
  13406. if (mouse)
  13407. return mouse.angularSensibility;
  13408. },
  13409. set: function (value) {
  13410. var mouse = this.inputs.attached["mouse"];
  13411. if (mouse)
  13412. mouse.angularSensibility = value;
  13413. },
  13414. enumerable: true,
  13415. configurable: true
  13416. });
  13417. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13418. get: function () {
  13419. var keyboard = this.inputs.attached["keyboard"];
  13420. if (keyboard)
  13421. return keyboard.keysUp;
  13422. },
  13423. set: function (value) {
  13424. var keyboard = this.inputs.attached["keyboard"];
  13425. if (keyboard)
  13426. keyboard.keysUp = value;
  13427. },
  13428. enumerable: true,
  13429. configurable: true
  13430. });
  13431. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13432. get: function () {
  13433. var keyboard = this.inputs.attached["keyboard"];
  13434. if (keyboard)
  13435. return keyboard.keysDown;
  13436. },
  13437. set: function (value) {
  13438. var keyboard = this.inputs.attached["keyboard"];
  13439. if (keyboard)
  13440. keyboard.keysDown = value;
  13441. },
  13442. enumerable: true,
  13443. configurable: true
  13444. });
  13445. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13446. get: function () {
  13447. var keyboard = this.inputs.attached["keyboard"];
  13448. if (keyboard)
  13449. return keyboard.keysLeft;
  13450. },
  13451. set: function (value) {
  13452. var keyboard = this.inputs.attached["keyboard"];
  13453. if (keyboard)
  13454. keyboard.keysLeft = value;
  13455. },
  13456. enumerable: true,
  13457. configurable: true
  13458. });
  13459. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13460. get: function () {
  13461. var keyboard = this.inputs.attached["keyboard"];
  13462. if (keyboard)
  13463. return keyboard.keysRight;
  13464. },
  13465. set: function (value) {
  13466. var keyboard = this.inputs.attached["keyboard"];
  13467. if (keyboard)
  13468. keyboard.keysRight = value;
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. // Controls
  13474. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13475. this.inputs.attachElement(element, noPreventDefault);
  13476. };
  13477. FreeCamera.prototype.detachControl = function (element) {
  13478. this.inputs.detachElement(element);
  13479. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13480. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13481. };
  13482. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13483. var globalPosition;
  13484. if (this.parent) {
  13485. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13486. }
  13487. else {
  13488. globalPosition = this.position;
  13489. }
  13490. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13491. this._collider.radius = this.ellipsoid;
  13492. //no need for clone, as long as gravity is not on.
  13493. var actualVelocity = velocity;
  13494. //add gravity to the velocity to prevent the dual-collision checking
  13495. if (this.applyGravity) {
  13496. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13497. actualVelocity = velocity.add(this.getScene().gravity);
  13498. }
  13499. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13500. };
  13501. FreeCamera.prototype._checkInputs = function () {
  13502. if (!this._localDirection) {
  13503. this._localDirection = BABYLON.Vector3.Zero();
  13504. this._transformedDirection = BABYLON.Vector3.Zero();
  13505. }
  13506. this.inputs.checkInputs();
  13507. _super.prototype._checkInputs.call(this);
  13508. };
  13509. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13510. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13511. };
  13512. FreeCamera.prototype._updatePosition = function () {
  13513. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13514. this._collideWithWorld(this.cameraDirection);
  13515. }
  13516. else {
  13517. this.position.addInPlace(this.cameraDirection);
  13518. }
  13519. };
  13520. FreeCamera.prototype.dispose = function () {
  13521. this.inputs.clear();
  13522. _super.prototype.dispose.call(this);
  13523. };
  13524. FreeCamera.prototype.getTypeName = function () {
  13525. return "FreeCamera";
  13526. };
  13527. __decorate([
  13528. BABYLON.serializeAsVector3()
  13529. ], FreeCamera.prototype, "ellipsoid", void 0);
  13530. __decorate([
  13531. BABYLON.serialize()
  13532. ], FreeCamera.prototype, "checkCollisions", void 0);
  13533. __decorate([
  13534. BABYLON.serialize()
  13535. ], FreeCamera.prototype, "applyGravity", void 0);
  13536. return FreeCamera;
  13537. })(BABYLON.TargetCamera);
  13538. BABYLON.FreeCamera = FreeCamera;
  13539. })(BABYLON || (BABYLON = {}));
  13540. var BABYLON;
  13541. (function (BABYLON) {
  13542. var FreeCameraInputsManager = (function (_super) {
  13543. __extends(FreeCameraInputsManager, _super);
  13544. function FreeCameraInputsManager(camera) {
  13545. _super.call(this, camera);
  13546. }
  13547. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13548. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13549. return this;
  13550. };
  13551. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13552. if (touchEnabled === void 0) { touchEnabled = true; }
  13553. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13554. return this;
  13555. };
  13556. FreeCameraInputsManager.prototype.addGamepad = function () {
  13557. this.add(new BABYLON.FreeCameraGamepadInput());
  13558. return this;
  13559. };
  13560. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13561. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13562. return this;
  13563. };
  13564. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13565. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13566. return this;
  13567. };
  13568. FreeCameraInputsManager.prototype.addTouch = function () {
  13569. this.add(new BABYLON.FreeCameraTouchInput());
  13570. return this;
  13571. };
  13572. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13573. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13574. return this;
  13575. };
  13576. return FreeCameraInputsManager;
  13577. })(BABYLON.CameraInputsManager);
  13578. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13579. })(BABYLON || (BABYLON = {}));
  13580. var BABYLON;
  13581. (function (BABYLON) {
  13582. var FollowCamera = (function (_super) {
  13583. __extends(FollowCamera, _super);
  13584. function FollowCamera(name, position, scene, target) {
  13585. _super.call(this, name, position, scene);
  13586. this.radius = 12;
  13587. this.rotationOffset = 0;
  13588. this.heightOffset = 4;
  13589. this.cameraAcceleration = 0.05;
  13590. this.maxCameraSpeed = 20;
  13591. this.target = target;
  13592. }
  13593. FollowCamera.prototype.getRadians = function (degrees) {
  13594. return degrees * Math.PI / 180;
  13595. };
  13596. FollowCamera.prototype.follow = function (cameraTarget) {
  13597. if (!cameraTarget)
  13598. return;
  13599. var yRotation;
  13600. if (cameraTarget.rotationQuaternion) {
  13601. var rotMatrix = new BABYLON.Matrix();
  13602. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13603. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13604. }
  13605. else {
  13606. yRotation = cameraTarget.rotation.y;
  13607. }
  13608. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13609. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13610. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13611. var dx = targetX - this.position.x;
  13612. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13613. var dz = (targetZ) - this.position.z;
  13614. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13615. var vy = dy * this.cameraAcceleration;
  13616. var vz = dz * this.cameraAcceleration * 2;
  13617. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13618. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13619. }
  13620. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13621. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13622. }
  13623. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13624. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13625. }
  13626. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13627. this.setTarget(cameraTarget.position);
  13628. };
  13629. FollowCamera.prototype._checkInputs = function () {
  13630. _super.prototype._checkInputs.call(this);
  13631. this.follow(this.target);
  13632. };
  13633. FollowCamera.prototype.getTypeName = function () {
  13634. return "FollowCamera";
  13635. };
  13636. __decorate([
  13637. BABYLON.serialize()
  13638. ], FollowCamera.prototype, "radius", void 0);
  13639. __decorate([
  13640. BABYLON.serialize()
  13641. ], FollowCamera.prototype, "rotationOffset", void 0);
  13642. __decorate([
  13643. BABYLON.serialize()
  13644. ], FollowCamera.prototype, "heightOffset", void 0);
  13645. __decorate([
  13646. BABYLON.serialize()
  13647. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13648. __decorate([
  13649. BABYLON.serialize()
  13650. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13651. __decorate([
  13652. BABYLON.serializeAsMeshReference("lockedTargetId")
  13653. ], FollowCamera.prototype, "target", void 0);
  13654. return FollowCamera;
  13655. })(BABYLON.TargetCamera);
  13656. BABYLON.FollowCamera = FollowCamera;
  13657. var ArcFollowCamera = (function (_super) {
  13658. __extends(ArcFollowCamera, _super);
  13659. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13660. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13661. this.alpha = alpha;
  13662. this.beta = beta;
  13663. this.radius = radius;
  13664. this.target = target;
  13665. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13666. this.follow();
  13667. }
  13668. ArcFollowCamera.prototype.follow = function () {
  13669. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13670. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13671. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13672. this.position = this.target.position.add(this._cartesianCoordinates);
  13673. this.setTarget(this.target.position);
  13674. };
  13675. ArcFollowCamera.prototype._checkInputs = function () {
  13676. _super.prototype._checkInputs.call(this);
  13677. this.follow();
  13678. };
  13679. ArcFollowCamera.prototype.getTypeName = function () {
  13680. return "ArcFollowCamera";
  13681. };
  13682. return ArcFollowCamera;
  13683. })(BABYLON.TargetCamera);
  13684. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13685. })(BABYLON || (BABYLON = {}));
  13686. var BABYLON;
  13687. (function (BABYLON) {
  13688. // We're mainly based on the logic defined into the FreeCamera code
  13689. var TouchCamera = (function (_super) {
  13690. __extends(TouchCamera, _super);
  13691. //-- end properties for backward compatibility for inputs
  13692. function TouchCamera(name, position, scene) {
  13693. _super.call(this, name, position, scene);
  13694. this.inputs.addTouch();
  13695. this._setupInputs();
  13696. }
  13697. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13698. //-- Begin properties for backward compatibility for inputs
  13699. get: function () {
  13700. var touch = this.inputs.attached["touch"];
  13701. if (touch)
  13702. return touch.touchAngularSensibility;
  13703. },
  13704. set: function (value) {
  13705. var touch = this.inputs.attached["touch"];
  13706. if (touch)
  13707. touch.touchAngularSensibility = value;
  13708. },
  13709. enumerable: true,
  13710. configurable: true
  13711. });
  13712. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13713. get: function () {
  13714. var touch = this.inputs.attached["touch"];
  13715. if (touch)
  13716. return touch.touchMoveSensibility;
  13717. },
  13718. set: function (value) {
  13719. var touch = this.inputs.attached["touch"];
  13720. if (touch)
  13721. touch.touchMoveSensibility = value;
  13722. },
  13723. enumerable: true,
  13724. configurable: true
  13725. });
  13726. TouchCamera.prototype.getTypeName = function () {
  13727. return "TouchCamera";
  13728. };
  13729. TouchCamera.prototype._setupInputs = function () {
  13730. var mouse = this.inputs.attached["mouse"];
  13731. if (mouse) {
  13732. mouse.touchEnabled = false;
  13733. }
  13734. };
  13735. return TouchCamera;
  13736. })(BABYLON.FreeCamera);
  13737. BABYLON.TouchCamera = TouchCamera;
  13738. })(BABYLON || (BABYLON = {}));
  13739. var BABYLON;
  13740. (function (BABYLON) {
  13741. var ArcRotateCamera = (function (_super) {
  13742. __extends(ArcRotateCamera, _super);
  13743. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13744. var _this = this;
  13745. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13746. this.inertialAlphaOffset = 0;
  13747. this.inertialBetaOffset = 0;
  13748. this.inertialRadiusOffset = 0;
  13749. this.lowerAlphaLimit = null;
  13750. this.upperAlphaLimit = null;
  13751. this.lowerBetaLimit = 0.01;
  13752. this.upperBetaLimit = Math.PI;
  13753. this.lowerRadiusLimit = null;
  13754. this.upperRadiusLimit = null;
  13755. this.inertialPanningX = 0;
  13756. this.inertialPanningY = 0;
  13757. //-- end properties for backward compatibility for inputs
  13758. this.zoomOnFactor = 1;
  13759. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13760. this.allowUpsideDown = true;
  13761. this._viewMatrix = new BABYLON.Matrix();
  13762. // Panning
  13763. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13764. this.checkCollisions = false;
  13765. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13766. this._collider = new BABYLON.Collider();
  13767. this._previousPosition = BABYLON.Vector3.Zero();
  13768. this._collisionVelocity = BABYLON.Vector3.Zero();
  13769. this._newPosition = BABYLON.Vector3.Zero();
  13770. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13771. if (collidedMesh === void 0) { collidedMesh = null; }
  13772. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13773. newPosition.multiplyInPlace(_this._collider.radius);
  13774. }
  13775. if (!collidedMesh) {
  13776. _this._previousPosition.copyFrom(_this.position);
  13777. }
  13778. else {
  13779. _this.setPosition(newPosition);
  13780. if (_this.onCollide) {
  13781. _this.onCollide(collidedMesh);
  13782. }
  13783. }
  13784. // Recompute because of constraints
  13785. var cosa = Math.cos(_this.alpha);
  13786. var sina = Math.sin(_this.alpha);
  13787. var cosb = Math.cos(_this.beta);
  13788. var sinb = Math.sin(_this.beta);
  13789. if (sinb === 0) {
  13790. sinb = 0.0001;
  13791. }
  13792. var target = _this._getTargetPosition();
  13793. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13794. _this.position.copyFrom(_this._newPosition);
  13795. var up = _this.upVector;
  13796. if (_this.allowUpsideDown && _this.beta < 0) {
  13797. up = up.clone();
  13798. up = up.negate();
  13799. }
  13800. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13801. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13802. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13803. _this._collisionTriggered = false;
  13804. };
  13805. if (!target) {
  13806. this.target = BABYLON.Vector3.Zero();
  13807. }
  13808. else {
  13809. this.target = target;
  13810. }
  13811. this.alpha = alpha;
  13812. this.beta = beta;
  13813. this.radius = radius;
  13814. this.getViewMatrix();
  13815. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13816. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13817. }
  13818. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13819. //-- begin properties for backward compatibility for inputs
  13820. get: function () {
  13821. var pointers = this.inputs.attached["pointers"];
  13822. if (pointers)
  13823. return pointers.angularSensibilityX;
  13824. },
  13825. set: function (value) {
  13826. var pointers = this.inputs.attached["pointers"];
  13827. if (pointers) {
  13828. pointers.angularSensibilityX = value;
  13829. }
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13835. get: function () {
  13836. var pointers = this.inputs.attached["pointers"];
  13837. if (pointers)
  13838. return pointers.angularSensibilityY;
  13839. },
  13840. set: function (value) {
  13841. var pointers = this.inputs.attached["pointers"];
  13842. if (pointers) {
  13843. pointers.angularSensibilityY = value;
  13844. }
  13845. },
  13846. enumerable: true,
  13847. configurable: true
  13848. });
  13849. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13850. get: function () {
  13851. var pointers = this.inputs.attached["pointers"];
  13852. if (pointers)
  13853. return pointers.pinchPrecision;
  13854. },
  13855. set: function (value) {
  13856. var pointers = this.inputs.attached["pointers"];
  13857. if (pointers) {
  13858. pointers.pinchPrecision = value;
  13859. }
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13865. get: function () {
  13866. var pointers = this.inputs.attached["pointers"];
  13867. if (pointers)
  13868. return pointers.panningSensibility;
  13869. },
  13870. set: function (value) {
  13871. var pointers = this.inputs.attached["pointers"];
  13872. if (pointers) {
  13873. pointers.panningSensibility = value;
  13874. }
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13880. get: function () {
  13881. var keyboard = this.inputs.attached["keyboard"];
  13882. if (keyboard)
  13883. return keyboard.keysUp;
  13884. },
  13885. set: function (value) {
  13886. var keyboard = this.inputs.attached["keyboard"];
  13887. if (keyboard)
  13888. keyboard.keysUp = value;
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13894. get: function () {
  13895. var keyboard = this.inputs.attached["keyboard"];
  13896. if (keyboard)
  13897. return keyboard.keysDown;
  13898. },
  13899. set: function (value) {
  13900. var keyboard = this.inputs.attached["keyboard"];
  13901. if (keyboard)
  13902. keyboard.keysDown = value;
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13908. get: function () {
  13909. var keyboard = this.inputs.attached["keyboard"];
  13910. if (keyboard)
  13911. return keyboard.keysLeft;
  13912. },
  13913. set: function (value) {
  13914. var keyboard = this.inputs.attached["keyboard"];
  13915. if (keyboard)
  13916. keyboard.keysLeft = value;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13922. get: function () {
  13923. var keyboard = this.inputs.attached["keyboard"];
  13924. if (keyboard)
  13925. return keyboard.keysRight;
  13926. },
  13927. set: function (value) {
  13928. var keyboard = this.inputs.attached["keyboard"];
  13929. if (keyboard)
  13930. keyboard.keysRight = value;
  13931. },
  13932. enumerable: true,
  13933. configurable: true
  13934. });
  13935. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13936. get: function () {
  13937. var mousewheel = this.inputs.attached["mousewheel"];
  13938. if (mousewheel)
  13939. return mousewheel.wheelPrecision;
  13940. },
  13941. set: function (value) {
  13942. var mousewheel = this.inputs.attached["mousewheel"];
  13943. if (mousewheel)
  13944. mousewheel.wheelPrecision = value;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. // Cache
  13950. ArcRotateCamera.prototype._initCache = function () {
  13951. _super.prototype._initCache.call(this);
  13952. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13953. this._cache.alpha = undefined;
  13954. this._cache.beta = undefined;
  13955. this._cache.radius = undefined;
  13956. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13957. };
  13958. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13959. if (!ignoreParentClass) {
  13960. _super.prototype._updateCache.call(this);
  13961. }
  13962. this._cache.target.copyFrom(this._getTargetPosition());
  13963. this._cache.alpha = this.alpha;
  13964. this._cache.beta = this.beta;
  13965. this._cache.radius = this.radius;
  13966. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13967. };
  13968. ArcRotateCamera.prototype._getTargetPosition = function () {
  13969. if (this.target.getAbsolutePosition) {
  13970. return this.target.getAbsolutePosition();
  13971. }
  13972. return this.target;
  13973. };
  13974. // Synchronized
  13975. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13976. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13977. return false;
  13978. return this._cache.target.equals(this.target)
  13979. && this._cache.alpha === this.alpha
  13980. && this._cache.beta === this.beta
  13981. && this._cache.radius === this.radius
  13982. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13983. };
  13984. // Methods
  13985. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13986. var _this = this;
  13987. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13988. this._useCtrlForPanning = useCtrlForPanning;
  13989. this.inputs.attachElement(element, noPreventDefault);
  13990. this._reset = function () {
  13991. _this.inertialAlphaOffset = 0;
  13992. _this.inertialBetaOffset = 0;
  13993. _this.inertialRadiusOffset = 0;
  13994. };
  13995. };
  13996. ArcRotateCamera.prototype.detachControl = function (element) {
  13997. this.inputs.detachElement(element);
  13998. if (this._reset) {
  13999. this._reset();
  14000. }
  14001. };
  14002. ArcRotateCamera.prototype._checkInputs = function () {
  14003. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14004. if (this._collisionTriggered) {
  14005. return;
  14006. }
  14007. this.inputs.checkInputs();
  14008. // Inertia
  14009. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14010. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14011. this.beta += this.inertialBetaOffset;
  14012. this.radius -= this.inertialRadiusOffset;
  14013. this.inertialAlphaOffset *= this.inertia;
  14014. this.inertialBetaOffset *= this.inertia;
  14015. this.inertialRadiusOffset *= this.inertia;
  14016. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14017. this.inertialAlphaOffset = 0;
  14018. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14019. this.inertialBetaOffset = 0;
  14020. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14021. this.inertialRadiusOffset = 0;
  14022. }
  14023. // Panning inertia
  14024. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14025. if (!this._localDirection) {
  14026. this._localDirection = BABYLON.Vector3.Zero();
  14027. this._transformedDirection = BABYLON.Vector3.Zero();
  14028. }
  14029. this.inertialPanningX *= this.inertia;
  14030. this.inertialPanningY *= this.inertia;
  14031. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14032. this.inertialPanningX = 0;
  14033. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14034. this.inertialPanningY = 0;
  14035. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14036. this._localDirection.multiplyInPlace(this.panningAxis);
  14037. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14038. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14039. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14040. if (!this.panningAxis.y) {
  14041. this._transformedDirection.y = 0;
  14042. }
  14043. if (!this.target.getAbsolutePosition) {
  14044. this.target.addInPlace(this._transformedDirection);
  14045. }
  14046. }
  14047. // Limits
  14048. this._checkLimits();
  14049. _super.prototype._checkInputs.call(this);
  14050. };
  14051. ArcRotateCamera.prototype._checkLimits = function () {
  14052. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14053. if (this.allowUpsideDown && this.beta > Math.PI) {
  14054. this.beta = this.beta - (2 * Math.PI);
  14055. }
  14056. }
  14057. else {
  14058. if (this.beta < this.lowerBetaLimit) {
  14059. this.beta = this.lowerBetaLimit;
  14060. }
  14061. }
  14062. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14063. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14064. this.beta = this.beta + (2 * Math.PI);
  14065. }
  14066. }
  14067. else {
  14068. if (this.beta > this.upperBetaLimit) {
  14069. this.beta = this.upperBetaLimit;
  14070. }
  14071. }
  14072. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14073. this.alpha = this.lowerAlphaLimit;
  14074. }
  14075. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14076. this.alpha = this.upperAlphaLimit;
  14077. }
  14078. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14079. this.radius = this.lowerRadiusLimit;
  14080. }
  14081. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14082. this.radius = this.upperRadiusLimit;
  14083. }
  14084. };
  14085. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14086. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14087. this.radius = radiusv3.length();
  14088. // Alpha
  14089. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14090. if (radiusv3.z < 0) {
  14091. this.alpha = 2 * Math.PI - this.alpha;
  14092. }
  14093. // Beta
  14094. this.beta = Math.acos(radiusv3.y / this.radius);
  14095. this._checkLimits();
  14096. };
  14097. ArcRotateCamera.prototype.setPosition = function (position) {
  14098. if (this.position.equals(position)) {
  14099. return;
  14100. }
  14101. this.position = position;
  14102. this.rebuildAnglesAndRadius();
  14103. };
  14104. ArcRotateCamera.prototype.setTarget = function (target) {
  14105. if (this._getTargetPosition().equals(target)) {
  14106. return;
  14107. }
  14108. this.target = target;
  14109. this.rebuildAnglesAndRadius();
  14110. };
  14111. ArcRotateCamera.prototype._getViewMatrix = function () {
  14112. // Compute
  14113. var cosa = Math.cos(this.alpha);
  14114. var sina = Math.sin(this.alpha);
  14115. var cosb = Math.cos(this.beta);
  14116. var sinb = Math.sin(this.beta);
  14117. if (sinb === 0) {
  14118. sinb = 0.0001;
  14119. }
  14120. var target = this._getTargetPosition();
  14121. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14122. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14123. this._collider.radius = this.collisionRadius;
  14124. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14125. this._collisionTriggered = true;
  14126. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14127. }
  14128. else {
  14129. this.position.copyFrom(this._newPosition);
  14130. var up = this.upVector;
  14131. if (this.allowUpsideDown && this.beta < 0) {
  14132. up = up.clone();
  14133. up = up.negate();
  14134. }
  14135. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14136. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14137. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14138. }
  14139. return this._viewMatrix;
  14140. };
  14141. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14142. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14143. meshes = meshes || this.getScene().meshes;
  14144. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14145. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14146. this.radius = distance * this.zoomOnFactor;
  14147. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14148. };
  14149. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14150. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14151. var meshesOrMinMaxVector;
  14152. var distance;
  14153. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14154. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14155. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14156. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14157. }
  14158. else {
  14159. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14160. distance = meshesOrMinMaxVectorAndDistance.distance;
  14161. }
  14162. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14163. if (!doNotUpdateMaxZ) {
  14164. this.maxZ = distance * 2;
  14165. }
  14166. };
  14167. /**
  14168. * @override
  14169. * Override Camera.createRigCamera
  14170. */
  14171. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14172. var alphaShift;
  14173. switch (this.cameraRigMode) {
  14174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14175. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14176. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14177. case BABYLON.Camera.RIG_MODE_VR:
  14178. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14179. break;
  14180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14181. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14182. break;
  14183. }
  14184. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14185. rigCam._cameraRigParams = {};
  14186. return rigCam;
  14187. };
  14188. /**
  14189. * @override
  14190. * Override Camera._updateRigCameras
  14191. */
  14192. ArcRotateCamera.prototype._updateRigCameras = function () {
  14193. var camLeft = this._rigCameras[0];
  14194. var camRight = this._rigCameras[1];
  14195. camLeft.beta = camRight.beta = this.beta;
  14196. camLeft.radius = camRight.radius = this.radius;
  14197. switch (this.cameraRigMode) {
  14198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14199. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14201. case BABYLON.Camera.RIG_MODE_VR:
  14202. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14203. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14204. break;
  14205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14206. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14207. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14208. break;
  14209. }
  14210. _super.prototype._updateRigCameras.call(this);
  14211. };
  14212. ArcRotateCamera.prototype.dispose = function () {
  14213. this.inputs.clear();
  14214. _super.prototype.dispose.call(this);
  14215. };
  14216. ArcRotateCamera.prototype.getTypeName = function () {
  14217. return "ArcRotateCamera";
  14218. };
  14219. __decorate([
  14220. BABYLON.serialize()
  14221. ], ArcRotateCamera.prototype, "alpha", void 0);
  14222. __decorate([
  14223. BABYLON.serialize()
  14224. ], ArcRotateCamera.prototype, "beta", void 0);
  14225. __decorate([
  14226. BABYLON.serialize()
  14227. ], ArcRotateCamera.prototype, "radius", void 0);
  14228. __decorate([
  14229. BABYLON.serializeAsVector3()
  14230. ], ArcRotateCamera.prototype, "target", void 0);
  14231. __decorate([
  14232. BABYLON.serialize()
  14233. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14234. __decorate([
  14235. BABYLON.serialize()
  14236. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14237. __decorate([
  14238. BABYLON.serialize()
  14239. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14240. __decorate([
  14241. BABYLON.serialize()
  14242. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14243. __decorate([
  14244. BABYLON.serialize()
  14245. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14246. __decorate([
  14247. BABYLON.serialize()
  14248. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14249. __decorate([
  14250. BABYLON.serialize()
  14251. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14252. __decorate([
  14253. BABYLON.serialize()
  14254. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14255. __decorate([
  14256. BABYLON.serialize()
  14257. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14261. __decorate([
  14262. BABYLON.serialize()
  14263. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14264. __decorate([
  14265. BABYLON.serialize()
  14266. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14267. __decorate([
  14268. BABYLON.serialize()
  14269. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14270. return ArcRotateCamera;
  14271. })(BABYLON.TargetCamera);
  14272. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14273. })(BABYLON || (BABYLON = {}));
  14274. var BABYLON;
  14275. (function (BABYLON) {
  14276. var ArcRotateCameraInputsManager = (function (_super) {
  14277. __extends(ArcRotateCameraInputsManager, _super);
  14278. function ArcRotateCameraInputsManager(camera) {
  14279. _super.call(this, camera);
  14280. }
  14281. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14282. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14283. return this;
  14284. };
  14285. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14286. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14287. return this;
  14288. };
  14289. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14290. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14291. return this;
  14292. };
  14293. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14294. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14295. return this;
  14296. };
  14297. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14298. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14299. return this;
  14300. };
  14301. return ArcRotateCameraInputsManager;
  14302. })(BABYLON.CameraInputsManager);
  14303. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14304. })(BABYLON || (BABYLON = {}));
  14305. var BABYLON;
  14306. (function (BABYLON) {
  14307. var RenderingManager = (function () {
  14308. function RenderingManager(scene) {
  14309. this._renderingGroups = new Array();
  14310. this._scene = scene;
  14311. }
  14312. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14313. if (this._scene._activeParticleSystems.length === 0) {
  14314. return;
  14315. }
  14316. // Particles
  14317. var activeCamera = this._scene.activeCamera;
  14318. var beforeParticlesDate = BABYLON.Tools.Now;
  14319. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14320. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14321. if (particleSystem.renderingGroupId !== index) {
  14322. continue;
  14323. }
  14324. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14325. continue;
  14326. }
  14327. this._clearDepthBuffer();
  14328. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14329. this._scene._activeParticles += particleSystem.render();
  14330. }
  14331. }
  14332. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14333. };
  14334. RenderingManager.prototype._renderSprites = function (index) {
  14335. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14336. return;
  14337. }
  14338. // Sprites
  14339. var activeCamera = this._scene.activeCamera;
  14340. var beforeSpritessDate = BABYLON.Tools.Now;
  14341. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14342. var spriteManager = this._scene.spriteManagers[id];
  14343. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14344. this._clearDepthBuffer();
  14345. spriteManager.render();
  14346. }
  14347. }
  14348. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  14349. };
  14350. RenderingManager.prototype._clearDepthBuffer = function () {
  14351. if (this._depthBufferAlreadyCleaned) {
  14352. return;
  14353. }
  14354. this._scene.getEngine().clear(0, false, true);
  14355. this._depthBufferAlreadyCleaned = true;
  14356. };
  14357. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14358. if (this._currentRenderSprites) {
  14359. this._renderSprites(this._currentIndex);
  14360. }
  14361. if (this._currentRenderParticles) {
  14362. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14363. }
  14364. };
  14365. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14366. this._currentActiveMeshes = activeMeshes;
  14367. this._currentRenderParticles = renderParticles;
  14368. this._currentRenderSprites = renderSprites;
  14369. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14370. this._depthBufferAlreadyCleaned = index == 0;
  14371. var renderingGroup = this._renderingGroups[index];
  14372. var needToStepBack = false;
  14373. this._currentIndex = index;
  14374. if (renderingGroup) {
  14375. this._clearDepthBuffer();
  14376. if (!renderingGroup.onBeforeTransparentRendering) {
  14377. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14378. }
  14379. if (!renderingGroup.render(customRenderFunction)) {
  14380. this._renderingGroups.splice(index, 1);
  14381. needToStepBack = true;
  14382. this._renderSpritesAndParticles();
  14383. }
  14384. }
  14385. else {
  14386. this._renderSpritesAndParticles();
  14387. }
  14388. if (needToStepBack) {
  14389. index--;
  14390. }
  14391. }
  14392. };
  14393. RenderingManager.prototype.reset = function () {
  14394. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14395. if (renderingGroup) {
  14396. renderingGroup.prepare();
  14397. }
  14398. });
  14399. };
  14400. RenderingManager.prototype.dispatch = function (subMesh) {
  14401. var mesh = subMesh.getMesh();
  14402. var renderingGroupId = mesh.renderingGroupId || 0;
  14403. if (!this._renderingGroups[renderingGroupId]) {
  14404. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14405. }
  14406. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14407. };
  14408. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14409. return RenderingManager;
  14410. })();
  14411. BABYLON.RenderingManager = RenderingManager;
  14412. })(BABYLON || (BABYLON = {}));
  14413. var BABYLON;
  14414. (function (BABYLON) {
  14415. var RenderingGroup = (function () {
  14416. function RenderingGroup(index, scene) {
  14417. this.index = index;
  14418. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14419. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14420. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14421. this._scene = scene;
  14422. }
  14423. RenderingGroup.prototype.render = function (customRenderFunction) {
  14424. if (customRenderFunction) {
  14425. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14426. return true;
  14427. }
  14428. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14429. if (this.onBeforeTransparentRendering) {
  14430. this.onBeforeTransparentRendering();
  14431. }
  14432. return false;
  14433. }
  14434. var engine = this._scene.getEngine();
  14435. // Opaque
  14436. var subIndex;
  14437. var submesh;
  14438. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14439. submesh = this._opaqueSubMeshes.data[subIndex];
  14440. submesh.render(false);
  14441. }
  14442. // Alpha test
  14443. engine.setAlphaTesting(true);
  14444. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14445. submesh = this._alphaTestSubMeshes.data[subIndex];
  14446. submesh.render(false);
  14447. }
  14448. engine.setAlphaTesting(false);
  14449. if (this.onBeforeTransparentRendering) {
  14450. this.onBeforeTransparentRendering();
  14451. }
  14452. // Transparent
  14453. if (this._transparentSubMeshes.length) {
  14454. // Sorting
  14455. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14456. submesh = this._transparentSubMeshes.data[subIndex];
  14457. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14458. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14459. }
  14460. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14461. sortedArray.sort(function (a, b) {
  14462. // Alpha index first
  14463. if (a._alphaIndex > b._alphaIndex) {
  14464. return 1;
  14465. }
  14466. if (a._alphaIndex < b._alphaIndex) {
  14467. return -1;
  14468. }
  14469. // Then distance to camera
  14470. if (a._distanceToCamera < b._distanceToCamera) {
  14471. return 1;
  14472. }
  14473. if (a._distanceToCamera > b._distanceToCamera) {
  14474. return -1;
  14475. }
  14476. return 0;
  14477. });
  14478. // Rendering
  14479. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14480. submesh = sortedArray[subIndex];
  14481. submesh.render(true);
  14482. }
  14483. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14484. }
  14485. return true;
  14486. };
  14487. RenderingGroup.prototype.prepare = function () {
  14488. this._opaqueSubMeshes.reset();
  14489. this._transparentSubMeshes.reset();
  14490. this._alphaTestSubMeshes.reset();
  14491. };
  14492. RenderingGroup.prototype.dispatch = function (subMesh) {
  14493. var material = subMesh.getMaterial();
  14494. var mesh = subMesh.getMesh();
  14495. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14496. this._transparentSubMeshes.push(subMesh);
  14497. }
  14498. else if (material.needAlphaTesting()) {
  14499. this._alphaTestSubMeshes.push(subMesh);
  14500. }
  14501. else {
  14502. this._opaqueSubMeshes.push(subMesh); // Opaque
  14503. }
  14504. };
  14505. return RenderingGroup;
  14506. })();
  14507. BABYLON.RenderingGroup = RenderingGroup;
  14508. })(BABYLON || (BABYLON = {}));
  14509. var BABYLON;
  14510. (function (BABYLON) {
  14511. var PointerEventTypes = (function () {
  14512. function PointerEventTypes() {
  14513. }
  14514. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14515. get: function () {
  14516. return PointerEventTypes._POINTERDOWN;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14522. get: function () {
  14523. return PointerEventTypes._POINTERUP;
  14524. },
  14525. enumerable: true,
  14526. configurable: true
  14527. });
  14528. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14529. get: function () {
  14530. return PointerEventTypes._POINTERMOVE;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14536. get: function () {
  14537. return PointerEventTypes._POINTERWHEEL;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14543. get: function () {
  14544. return PointerEventTypes._POINTERPICK;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. PointerEventTypes._POINTERDOWN = 0x01;
  14550. PointerEventTypes._POINTERUP = 0x02;
  14551. PointerEventTypes._POINTERMOVE = 0x04;
  14552. PointerEventTypes._POINTERWHEEL = 0x08;
  14553. PointerEventTypes._POINTERPICK = 0x10;
  14554. return PointerEventTypes;
  14555. })();
  14556. BABYLON.PointerEventTypes = PointerEventTypes;
  14557. var PointerInfoBase = (function () {
  14558. function PointerInfoBase(type, event) {
  14559. this.type = type;
  14560. this.event = event;
  14561. }
  14562. return PointerInfoBase;
  14563. })();
  14564. BABYLON.PointerInfoBase = PointerInfoBase;
  14565. /**
  14566. * This class is used to store pointer related info for the onPrePointerObservable event.
  14567. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14568. */
  14569. var PointerInfoPre = (function (_super) {
  14570. __extends(PointerInfoPre, _super);
  14571. function PointerInfoPre(type, event, localX, localY) {
  14572. _super.call(this, type, event);
  14573. this.skipOnPointerObservable = false;
  14574. this.localPosition = new BABYLON.Vector2(localX, localY);
  14575. }
  14576. return PointerInfoPre;
  14577. })(PointerInfoBase);
  14578. BABYLON.PointerInfoPre = PointerInfoPre;
  14579. /**
  14580. * This type contains all the data related to a pointer event in Babylon.js.
  14581. * 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.
  14582. */
  14583. var PointerInfo = (function (_super) {
  14584. __extends(PointerInfo, _super);
  14585. function PointerInfo(type, event, pickInfo) {
  14586. _super.call(this, type, event);
  14587. this.pickInfo = pickInfo;
  14588. }
  14589. return PointerInfo;
  14590. })(PointerInfoBase);
  14591. BABYLON.PointerInfo = PointerInfo;
  14592. /**
  14593. * Represents a scene to be rendered by the engine.
  14594. * @see http://doc.babylonjs.com/page.php?p=21911
  14595. */
  14596. var Scene = (function () {
  14597. /**
  14598. * @constructor
  14599. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14600. */
  14601. function Scene(engine) {
  14602. // Members
  14603. this.autoClear = true;
  14604. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14605. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14606. this.forceWireframe = false;
  14607. this.forcePointsCloud = false;
  14608. this.forceShowBoundingBoxes = false;
  14609. this.animationsEnabled = true;
  14610. this.constantlyUpdateMeshUnderPointer = false;
  14611. // Events
  14612. /**
  14613. * An event triggered when the scene is disposed.
  14614. * @type {BABYLON.Observable}
  14615. */
  14616. this.onDisposeObservable = new BABYLON.Observable();
  14617. /**
  14618. * An event triggered before rendering the scene
  14619. * @type {BABYLON.Observable}
  14620. */
  14621. this.onBeforeRenderObservable = new BABYLON.Observable();
  14622. /**
  14623. * An event triggered after rendering the scene
  14624. * @type {BABYLON.Observable}
  14625. */
  14626. this.onAfterRenderObservable = new BABYLON.Observable();
  14627. /**
  14628. * An event triggered when the scene is ready
  14629. * @type {BABYLON.Observable}
  14630. */
  14631. this.onReadyObservable = new BABYLON.Observable();
  14632. /**
  14633. * An event triggered before rendering a camera
  14634. * @type {BABYLON.Observable}
  14635. */
  14636. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14637. /**
  14638. * An event triggered after rendering a camera
  14639. * @type {BABYLON.Observable}
  14640. */
  14641. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14642. /**
  14643. * An event triggered when a camera is created
  14644. * @type {BABYLON.Observable}
  14645. */
  14646. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14647. /**
  14648. * An event triggered when a camera is removed
  14649. * @type {BABYLON.Observable}
  14650. */
  14651. this.onCameraRemovedObservable = new BABYLON.Observable();
  14652. /**
  14653. * An event triggered when a light is created
  14654. * @type {BABYLON.Observable}
  14655. */
  14656. this.onNewLightAddedObservable = new BABYLON.Observable();
  14657. /**
  14658. * An event triggered when a light is removed
  14659. * @type {BABYLON.Observable}
  14660. */
  14661. this.onLightRemovedObservable = new BABYLON.Observable();
  14662. /**
  14663. * An event triggered when a geometry is created
  14664. * @type {BABYLON.Observable}
  14665. */
  14666. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14667. /**
  14668. * An event triggered when a geometry is removed
  14669. * @type {BABYLON.Observable}
  14670. */
  14671. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14672. /**
  14673. * An event triggered when a mesh is created
  14674. * @type {BABYLON.Observable}
  14675. */
  14676. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14677. /**
  14678. * An event triggered when a mesh is removed
  14679. * @type {BABYLON.Observable}
  14680. */
  14681. this.onMeshRemovedObservable = new BABYLON.Observable();
  14682. // Animations
  14683. this.animations = [];
  14684. /**
  14685. * 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).
  14686. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14687. */
  14688. this.onPrePointerObservable = new BABYLON.Observable();
  14689. /**
  14690. * Observable event triggered each time an input event is received from the rendering canvas
  14691. */
  14692. this.onPointerObservable = new BABYLON.Observable();
  14693. 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
  14694. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14695. this._startingPointerTime = 0;
  14696. // Fog
  14697. /**
  14698. * is fog enabled on this scene.
  14699. * @type {boolean}
  14700. */
  14701. this.fogEnabled = true;
  14702. this.fogMode = Scene.FOGMODE_NONE;
  14703. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14704. this.fogDensity = 0.1;
  14705. this.fogStart = 0;
  14706. this.fogEnd = 1000.0;
  14707. // Lights
  14708. /**
  14709. * is shadow enabled on this scene.
  14710. * @type {boolean}
  14711. */
  14712. this.shadowsEnabled = true;
  14713. /**
  14714. * is light enabled on this scene.
  14715. * @type {boolean}
  14716. */
  14717. this.lightsEnabled = true;
  14718. /**
  14719. * All of the lights added to this scene.
  14720. * @see BABYLON.Light
  14721. * @type {BABYLON.Light[]}
  14722. */
  14723. this.lights = new Array();
  14724. // Cameras
  14725. /**
  14726. * All of the cameras added to this scene.
  14727. * @see BABYLON.Camera
  14728. * @type {BABYLON.Camera[]}
  14729. */
  14730. this.cameras = new Array();
  14731. this.activeCameras = new Array();
  14732. // Meshes
  14733. /**
  14734. * All of the (abstract) meshes added to this scene.
  14735. * @see BABYLON.AbstractMesh
  14736. * @type {BABYLON.AbstractMesh[]}
  14737. */
  14738. this.meshes = new Array();
  14739. // Geometries
  14740. this._geometries = new Array();
  14741. this.materials = new Array();
  14742. this.multiMaterials = new Array();
  14743. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14744. // Textures
  14745. this.texturesEnabled = true;
  14746. this.textures = new Array();
  14747. // Particles
  14748. this.particlesEnabled = true;
  14749. this.particleSystems = new Array();
  14750. // Sprites
  14751. this.spritesEnabled = true;
  14752. this.spriteManagers = new Array();
  14753. // Layers
  14754. this.layers = new Array();
  14755. // Skeletons
  14756. this.skeletonsEnabled = true;
  14757. this.skeletons = new Array();
  14758. // Lens flares
  14759. this.lensFlaresEnabled = true;
  14760. this.lensFlareSystems = new Array();
  14761. // Collisions
  14762. this.collisionsEnabled = true;
  14763. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14764. // Postprocesses
  14765. this.postProcessesEnabled = true;
  14766. // Customs render targets
  14767. this.renderTargetsEnabled = true;
  14768. this.dumpNextRenderTargets = false;
  14769. this.customRenderTargets = new Array();
  14770. // Imported meshes
  14771. this.importedMeshesFiles = new Array();
  14772. // Probes
  14773. this.probesEnabled = true;
  14774. this.reflectionProbes = new Array();
  14775. this._actionManagers = new Array();
  14776. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14777. // Procedural textures
  14778. this.proceduralTexturesEnabled = true;
  14779. this._proceduralTextures = new Array();
  14780. this.soundTracks = new Array();
  14781. this._audioEnabled = true;
  14782. this._headphone = false;
  14783. this._totalVertices = 0;
  14784. this._activeIndices = 0;
  14785. this._activeParticles = 0;
  14786. this._lastFrameDuration = 0;
  14787. this._evaluateActiveMeshesDuration = 0;
  14788. this._renderTargetsDuration = 0;
  14789. this._particlesDuration = 0;
  14790. this._renderDuration = 0;
  14791. this._spritesDuration = 0;
  14792. this._animationRatio = 0;
  14793. this._renderId = 0;
  14794. this._executeWhenReadyTimeoutId = -1;
  14795. this._intermediateRendering = false;
  14796. this._toBeDisposed = new BABYLON.SmartArray(256);
  14797. this._pendingData = []; //ANY
  14798. this._activeMeshes = new BABYLON.SmartArray(256);
  14799. this._processedMaterials = new BABYLON.SmartArray(256);
  14800. this._renderTargets = new BABYLON.SmartArray(256);
  14801. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14802. this._activeSkeletons = new BABYLON.SmartArray(32);
  14803. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14804. this._activeBones = 0;
  14805. this._activeAnimatables = new Array();
  14806. this._transformMatrix = BABYLON.Matrix.Zero();
  14807. this._edgesRenderers = new BABYLON.SmartArray(16);
  14808. this._uniqueIdCounter = 0;
  14809. this._engine = engine;
  14810. engine.scenes.push(this);
  14811. this._renderingManager = new BABYLON.RenderingManager(this);
  14812. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14813. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14814. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14815. if (BABYLON.OutlineRenderer) {
  14816. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14817. }
  14818. this.attachControl();
  14819. if (BABYLON.SoundTrack) {
  14820. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14821. }
  14822. //simplification queue
  14823. if (BABYLON.SimplificationQueue) {
  14824. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14825. }
  14826. //collision coordinator initialization. For now legacy per default.
  14827. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14828. }
  14829. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14830. get: function () {
  14831. return Scene._FOGMODE_NONE;
  14832. },
  14833. enumerable: true,
  14834. configurable: true
  14835. });
  14836. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14837. get: function () {
  14838. return Scene._FOGMODE_EXP;
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14844. get: function () {
  14845. return Scene._FOGMODE_EXP2;
  14846. },
  14847. enumerable: true,
  14848. configurable: true
  14849. });
  14850. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14851. get: function () {
  14852. return Scene._FOGMODE_LINEAR;
  14853. },
  14854. enumerable: true,
  14855. configurable: true
  14856. });
  14857. Object.defineProperty(Scene.prototype, "onDispose", {
  14858. set: function (callback) {
  14859. if (this._onDisposeObserver) {
  14860. this.onDisposeObservable.remove(this._onDisposeObserver);
  14861. }
  14862. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Object.defineProperty(Scene.prototype, "beforeRender", {
  14868. set: function (callback) {
  14869. if (this._onBeforeRenderObserver) {
  14870. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14871. }
  14872. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14873. },
  14874. enumerable: true,
  14875. configurable: true
  14876. });
  14877. Object.defineProperty(Scene.prototype, "afterRender", {
  14878. set: function (callback) {
  14879. if (this._onAfterRenderObserver) {
  14880. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14881. }
  14882. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14888. set: function (callback) {
  14889. if (this._onBeforeCameraRenderObserver) {
  14890. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14891. }
  14892. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14893. },
  14894. enumerable: true,
  14895. configurable: true
  14896. });
  14897. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14898. set: function (callback) {
  14899. if (this._onAfterCameraRenderObserver) {
  14900. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14901. }
  14902. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14903. },
  14904. enumerable: true,
  14905. configurable: true
  14906. });
  14907. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14908. get: function () {
  14909. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14910. },
  14911. enumerable: true,
  14912. configurable: true
  14913. });
  14914. Object.defineProperty(Scene.prototype, "debugLayer", {
  14915. // Properties
  14916. get: function () {
  14917. if (!this._debugLayer) {
  14918. this._debugLayer = new BABYLON.DebugLayer(this);
  14919. }
  14920. return this._debugLayer;
  14921. },
  14922. enumerable: true,
  14923. configurable: true
  14924. });
  14925. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14926. get: function () {
  14927. return this._workerCollisions;
  14928. },
  14929. set: function (enabled) {
  14930. enabled = (enabled && !!Worker);
  14931. this._workerCollisions = enabled;
  14932. if (this.collisionCoordinator) {
  14933. this.collisionCoordinator.destroy();
  14934. }
  14935. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14936. this.collisionCoordinator.init(this);
  14937. },
  14938. enumerable: true,
  14939. configurable: true
  14940. });
  14941. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14942. get: function () {
  14943. return this._selectionOctree;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14949. /**
  14950. * The mesh that is currently under the pointer.
  14951. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14952. */
  14953. get: function () {
  14954. return this._pointerOverMesh;
  14955. },
  14956. enumerable: true,
  14957. configurable: true
  14958. });
  14959. Object.defineProperty(Scene.prototype, "pointerX", {
  14960. /**
  14961. * Current on-screen X position of the pointer
  14962. * @return {number} X position of the pointer
  14963. */
  14964. get: function () {
  14965. return this._pointerX;
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. Object.defineProperty(Scene.prototype, "pointerY", {
  14971. /**
  14972. * Current on-screen Y position of the pointer
  14973. * @return {number} Y position of the pointer
  14974. */
  14975. get: function () {
  14976. return this._pointerY;
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. Scene.prototype.getCachedMaterial = function () {
  14982. return this._cachedMaterial;
  14983. };
  14984. Scene.prototype.getBoundingBoxRenderer = function () {
  14985. return this._boundingBoxRenderer;
  14986. };
  14987. Scene.prototype.getOutlineRenderer = function () {
  14988. return this._outlineRenderer;
  14989. };
  14990. Scene.prototype.getEngine = function () {
  14991. return this._engine;
  14992. };
  14993. Scene.prototype.getTotalVertices = function () {
  14994. return this._totalVertices;
  14995. };
  14996. Scene.prototype.getActiveIndices = function () {
  14997. return this._activeIndices;
  14998. };
  14999. Scene.prototype.getActiveParticles = function () {
  15000. return this._activeParticles;
  15001. };
  15002. Scene.prototype.getActiveBones = function () {
  15003. return this._activeBones;
  15004. };
  15005. // Stats
  15006. Scene.prototype.getLastFrameDuration = function () {
  15007. return this._lastFrameDuration;
  15008. };
  15009. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15010. return this._evaluateActiveMeshesDuration;
  15011. };
  15012. Scene.prototype.getActiveMeshes = function () {
  15013. return this._activeMeshes;
  15014. };
  15015. Scene.prototype.getRenderTargetsDuration = function () {
  15016. return this._renderTargetsDuration;
  15017. };
  15018. Scene.prototype.getRenderDuration = function () {
  15019. return this._renderDuration;
  15020. };
  15021. Scene.prototype.getParticlesDuration = function () {
  15022. return this._particlesDuration;
  15023. };
  15024. Scene.prototype.getSpritesDuration = function () {
  15025. return this._spritesDuration;
  15026. };
  15027. Scene.prototype.getAnimationRatio = function () {
  15028. return this._animationRatio;
  15029. };
  15030. Scene.prototype.getRenderId = function () {
  15031. return this._renderId;
  15032. };
  15033. Scene.prototype.incrementRenderId = function () {
  15034. this._renderId++;
  15035. };
  15036. Scene.prototype._updatePointerPosition = function (evt) {
  15037. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15038. this._pointerX = evt.clientX - canvasRect.left;
  15039. this._pointerY = evt.clientY - canvasRect.top;
  15040. this._unTranslatedPointerX = this._pointerX;
  15041. this._unTranslatedPointerY = this._pointerY;
  15042. if (this.cameraToUseForPointers) {
  15043. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15044. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15045. }
  15046. };
  15047. // Pointers handling
  15048. /**
  15049. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15050. * @param attachUp defines if you want to attach events to pointerup
  15051. * @param attachDown defines if you want to attach events to pointerdown
  15052. * @param attachMove defines if you want to attach events to pointermove
  15053. */
  15054. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15055. var _this = this;
  15056. if (attachUp === void 0) { attachUp = true; }
  15057. if (attachDown === void 0) { attachDown = true; }
  15058. if (attachMove === void 0) { attachMove = true; }
  15059. var spritePredicate = function (sprite) {
  15060. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15061. };
  15062. this._onPointerMove = function (evt) {
  15063. _this._updatePointerPosition(evt);
  15064. // PreObservable support
  15065. if (_this.onPrePointerObservable.hasObservers()) {
  15066. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15067. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15068. _this.onPrePointerObservable.notifyObservers(pi, type);
  15069. if (pi.skipOnPointerObservable) {
  15070. return;
  15071. }
  15072. }
  15073. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15074. return;
  15075. }
  15076. var canvas = _this._engine.getRenderingCanvas();
  15077. if (!_this.pointerMovePredicate) {
  15078. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15079. }
  15080. // Meshes
  15081. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15082. if (pickResult.hit && pickResult.pickedMesh) {
  15083. _this.setPointerOverSprite(null);
  15084. _this.setPointerOverMesh(pickResult.pickedMesh);
  15085. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15086. canvas.style.cursor = "pointer";
  15087. }
  15088. else {
  15089. canvas.style.cursor = "";
  15090. }
  15091. }
  15092. else {
  15093. _this.setPointerOverMesh(null);
  15094. // Sprites
  15095. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15096. if (pickResult.hit && pickResult.pickedSprite) {
  15097. canvas.style.cursor = "pointer";
  15098. _this.setPointerOverSprite(pickResult.pickedSprite);
  15099. }
  15100. else {
  15101. _this.setPointerOverSprite(null);
  15102. // Restore pointer
  15103. canvas.style.cursor = "";
  15104. }
  15105. }
  15106. if (_this.onPointerMove) {
  15107. _this.onPointerMove(evt, pickResult);
  15108. }
  15109. if (_this.onPointerObservable.hasObservers()) {
  15110. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15111. var pi = new PointerInfo(type, evt, pickResult);
  15112. _this.onPointerObservable.notifyObservers(pi, type);
  15113. }
  15114. };
  15115. this._onPointerDown = function (evt) {
  15116. _this._updatePointerPosition(evt);
  15117. // PreObservable support
  15118. if (_this.onPrePointerObservable.hasObservers()) {
  15119. var type = PointerEventTypes.POINTERDOWN;
  15120. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15121. _this.onPrePointerObservable.notifyObservers(pi, type);
  15122. if (pi.skipOnPointerObservable) {
  15123. return;
  15124. }
  15125. }
  15126. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15127. return;
  15128. }
  15129. _this._startingPointerPosition.x = _this._pointerX;
  15130. _this._startingPointerPosition.y = _this._pointerY;
  15131. _this._startingPointerTime = new Date().getTime();
  15132. if (!_this.pointerDownPredicate) {
  15133. _this.pointerDownPredicate = function (mesh) {
  15134. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15135. };
  15136. }
  15137. // Meshes
  15138. _this._pickedDownMesh = null;
  15139. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15140. if (pickResult.hit && pickResult.pickedMesh) {
  15141. if (pickResult.pickedMesh.actionManager) {
  15142. _this._pickedDownMesh = pickResult.pickedMesh;
  15143. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15144. switch (evt.button) {
  15145. case 0:
  15146. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15147. break;
  15148. case 1:
  15149. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15150. break;
  15151. case 2:
  15152. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15153. break;
  15154. }
  15155. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15156. }
  15157. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15158. var that = _this;
  15159. window.setTimeout(function () {
  15160. 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);
  15161. if (pickResult.hit && pickResult.pickedMesh) {
  15162. if (pickResult.pickedMesh.actionManager) {
  15163. 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)) {
  15164. that._startingPointerTime = 0;
  15165. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15166. }
  15167. }
  15168. }
  15169. }, BABYLON.ActionManager.LongPressDelay);
  15170. }
  15171. }
  15172. }
  15173. if (_this.onPointerDown) {
  15174. _this.onPointerDown(evt, pickResult);
  15175. }
  15176. if (_this.onPointerObservable.hasObservers()) {
  15177. var type = PointerEventTypes.POINTERDOWN;
  15178. var pi = new PointerInfo(type, evt, pickResult);
  15179. _this.onPointerObservable.notifyObservers(pi, type);
  15180. }
  15181. // Sprites
  15182. _this._pickedDownSprite = null;
  15183. if (_this.spriteManagers.length > 0) {
  15184. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15185. if (pickResult.hit && pickResult.pickedSprite) {
  15186. if (pickResult.pickedSprite.actionManager) {
  15187. _this._pickedDownSprite = pickResult.pickedSprite;
  15188. switch (evt.button) {
  15189. case 0:
  15190. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15191. break;
  15192. case 1:
  15193. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15194. break;
  15195. case 2:
  15196. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15197. break;
  15198. }
  15199. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15200. }
  15201. }
  15202. }
  15203. };
  15204. this._onPointerUp = function (evt) {
  15205. _this._updatePointerPosition(evt);
  15206. // PreObservable support
  15207. if (_this.onPrePointerObservable.hasObservers()) {
  15208. var type = PointerEventTypes.POINTERUP;
  15209. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15210. _this.onPrePointerObservable.notifyObservers(pi, type);
  15211. if (pi.skipOnPointerObservable) {
  15212. return;
  15213. }
  15214. }
  15215. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15216. return;
  15217. }
  15218. if (!_this.pointerUpPredicate) {
  15219. _this.pointerUpPredicate = function (mesh) {
  15220. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15221. };
  15222. }
  15223. // Meshes
  15224. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15225. if (pickResult.hit && pickResult.pickedMesh) {
  15226. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15227. if (_this.onPointerPick) {
  15228. _this.onPointerPick(evt, pickResult);
  15229. }
  15230. if (_this.onPointerObservable.hasObservers()) {
  15231. var type = PointerEventTypes.POINTERPICK;
  15232. var pi = new PointerInfo(type, evt, pickResult);
  15233. _this.onPointerObservable.notifyObservers(pi, type);
  15234. }
  15235. }
  15236. if (pickResult.pickedMesh.actionManager) {
  15237. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15238. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15240. }
  15241. }
  15242. }
  15243. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15244. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15245. }
  15246. if (_this.onPointerUp) {
  15247. _this.onPointerUp(evt, pickResult);
  15248. }
  15249. if (_this.onPointerObservable.hasObservers()) {
  15250. var type = PointerEventTypes.POINTERUP;
  15251. var pi = new PointerInfo(type, evt, pickResult);
  15252. _this.onPointerObservable.notifyObservers(pi, type);
  15253. }
  15254. _this._startingPointerTime = 0;
  15255. // Sprites
  15256. if (_this.spriteManagers.length > 0) {
  15257. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15258. if (pickResult.hit && pickResult.pickedSprite) {
  15259. if (pickResult.pickedSprite.actionManager) {
  15260. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15261. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15262. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15263. }
  15264. }
  15265. }
  15266. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15267. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15268. }
  15269. }
  15270. };
  15271. this._onKeyDown = function (evt) {
  15272. if (_this.actionManager) {
  15273. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15274. }
  15275. };
  15276. this._onKeyUp = function (evt) {
  15277. if (_this.actionManager) {
  15278. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15279. }
  15280. };
  15281. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15282. if (attachMove) {
  15283. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15284. // Wheel
  15285. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  15286. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15287. }
  15288. if (attachDown) {
  15289. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15290. }
  15291. if (attachUp) {
  15292. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15293. }
  15294. BABYLON.Tools.RegisterTopRootEvents([
  15295. { name: "keydown", handler: this._onKeyDown },
  15296. { name: "keyup", handler: this._onKeyUp }
  15297. ]);
  15298. };
  15299. Scene.prototype.detachControl = function () {
  15300. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15301. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  15302. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  15303. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  15304. // Wheel
  15305. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  15306. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  15307. BABYLON.Tools.UnregisterTopRootEvents([
  15308. { name: "keydown", handler: this._onKeyDown },
  15309. { name: "keyup", handler: this._onKeyUp }
  15310. ]);
  15311. };
  15312. // Ready
  15313. Scene.prototype.isReady = function () {
  15314. if (this._pendingData.length > 0) {
  15315. return false;
  15316. }
  15317. var index;
  15318. for (index = 0; index < this._geometries.length; index++) {
  15319. var geometry = this._geometries[index];
  15320. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15321. return false;
  15322. }
  15323. }
  15324. for (index = 0; index < this.meshes.length; index++) {
  15325. var mesh = this.meshes[index];
  15326. if (!mesh.isReady()) {
  15327. return false;
  15328. }
  15329. var mat = mesh.material;
  15330. if (mat) {
  15331. if (!mat.isReady(mesh)) {
  15332. return false;
  15333. }
  15334. }
  15335. }
  15336. return true;
  15337. };
  15338. Scene.prototype.resetCachedMaterial = function () {
  15339. this._cachedMaterial = null;
  15340. };
  15341. Scene.prototype.registerBeforeRender = function (func) {
  15342. this.onBeforeRenderObservable.add(func);
  15343. };
  15344. Scene.prototype.unregisterBeforeRender = function (func) {
  15345. this.onBeforeRenderObservable.removeCallback(func);
  15346. };
  15347. Scene.prototype.registerAfterRender = function (func) {
  15348. this.onAfterRenderObservable.add(func);
  15349. };
  15350. Scene.prototype.unregisterAfterRender = function (func) {
  15351. this.onAfterRenderObservable.removeCallback(func);
  15352. };
  15353. Scene.prototype._addPendingData = function (data) {
  15354. this._pendingData.push(data);
  15355. };
  15356. Scene.prototype._removePendingData = function (data) {
  15357. var index = this._pendingData.indexOf(data);
  15358. if (index !== -1) {
  15359. this._pendingData.splice(index, 1);
  15360. }
  15361. };
  15362. Scene.prototype.getWaitingItemsCount = function () {
  15363. return this._pendingData.length;
  15364. };
  15365. /**
  15366. * Registers a function to be executed when the scene is ready.
  15367. * @param {Function} func - the function to be executed.
  15368. */
  15369. Scene.prototype.executeWhenReady = function (func) {
  15370. var _this = this;
  15371. this.onReadyObservable.add(func);
  15372. if (this._executeWhenReadyTimeoutId !== -1) {
  15373. return;
  15374. }
  15375. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15376. _this._checkIsReady();
  15377. }, 150);
  15378. };
  15379. Scene.prototype._checkIsReady = function () {
  15380. var _this = this;
  15381. if (this.isReady()) {
  15382. this.onReadyObservable.notifyObservers(this);
  15383. this.onReadyObservable.clear();
  15384. this._executeWhenReadyTimeoutId = -1;
  15385. return;
  15386. }
  15387. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15388. _this._checkIsReady();
  15389. }, 150);
  15390. };
  15391. // Animations
  15392. /**
  15393. * Will start the animation sequence of a given target
  15394. * @param target - the target
  15395. * @param {number} from - from which frame should animation start
  15396. * @param {number} to - till which frame should animation run.
  15397. * @param {boolean} [loop] - should the animation loop
  15398. * @param {number} [speedRatio] - the speed in which to run the animation
  15399. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15400. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15401. * @return {BABYLON.Animatable} the animatable object created for this animation
  15402. * @see BABYLON.Animatable
  15403. * @see http://doc.babylonjs.com/page.php?p=22081
  15404. */
  15405. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15406. if (speedRatio === void 0) { speedRatio = 1.0; }
  15407. this.stopAnimation(target);
  15408. if (!animatable) {
  15409. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15410. }
  15411. // Local animations
  15412. if (target.animations) {
  15413. animatable.appendAnimations(target, target.animations);
  15414. }
  15415. // Children animations
  15416. if (target.getAnimatables) {
  15417. var animatables = target.getAnimatables();
  15418. for (var index = 0; index < animatables.length; index++) {
  15419. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15420. }
  15421. }
  15422. animatable.reset();
  15423. return animatable;
  15424. };
  15425. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15426. if (speedRatio === undefined) {
  15427. speedRatio = 1.0;
  15428. }
  15429. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15430. return animatable;
  15431. };
  15432. Scene.prototype.getAnimatableByTarget = function (target) {
  15433. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15434. if (this._activeAnimatables[index].target === target) {
  15435. return this._activeAnimatables[index];
  15436. }
  15437. }
  15438. return null;
  15439. };
  15440. Object.defineProperty(Scene.prototype, "Animatables", {
  15441. get: function () {
  15442. return this._activeAnimatables;
  15443. },
  15444. enumerable: true,
  15445. configurable: true
  15446. });
  15447. /**
  15448. * Will stop the animation of the given target
  15449. * @param target - the target
  15450. * @see beginAnimation
  15451. */
  15452. Scene.prototype.stopAnimation = function (target) {
  15453. var animatable = this.getAnimatableByTarget(target);
  15454. if (animatable) {
  15455. animatable.stop();
  15456. }
  15457. };
  15458. Scene.prototype._animate = function () {
  15459. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15460. return;
  15461. }
  15462. if (!this._animationStartDate) {
  15463. if (this._pendingData.length > 0) {
  15464. return;
  15465. }
  15466. this._animationStartDate = BABYLON.Tools.Now;
  15467. }
  15468. // Getting time
  15469. var now = BABYLON.Tools.Now;
  15470. var delay = now - this._animationStartDate;
  15471. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15472. this._activeAnimatables[index]._animate(delay);
  15473. }
  15474. };
  15475. // Matrix
  15476. Scene.prototype.getViewMatrix = function () {
  15477. return this._viewMatrix;
  15478. };
  15479. Scene.prototype.getProjectionMatrix = function () {
  15480. return this._projectionMatrix;
  15481. };
  15482. Scene.prototype.getTransformMatrix = function () {
  15483. return this._transformMatrix;
  15484. };
  15485. Scene.prototype.setTransformMatrix = function (view, projection) {
  15486. this._viewMatrix = view;
  15487. this._projectionMatrix = projection;
  15488. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15489. };
  15490. // Methods
  15491. Scene.prototype.addMesh = function (newMesh) {
  15492. newMesh.uniqueId = this._uniqueIdCounter++;
  15493. var position = this.meshes.push(newMesh);
  15494. //notify the collision coordinator
  15495. this.collisionCoordinator.onMeshAdded(newMesh);
  15496. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15497. };
  15498. Scene.prototype.removeMesh = function (toRemove) {
  15499. var index = this.meshes.indexOf(toRemove);
  15500. if (index !== -1) {
  15501. // Remove from the scene if mesh found
  15502. this.meshes.splice(index, 1);
  15503. }
  15504. //notify the collision coordinator
  15505. this.collisionCoordinator.onMeshRemoved(toRemove);
  15506. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15507. return index;
  15508. };
  15509. Scene.prototype.removeSkeleton = function (toRemove) {
  15510. var index = this.skeletons.indexOf(toRemove);
  15511. if (index !== -1) {
  15512. // Remove from the scene if mesh found
  15513. this.skeletons.splice(index, 1);
  15514. }
  15515. return index;
  15516. };
  15517. Scene.prototype.removeLight = function (toRemove) {
  15518. var index = this.lights.indexOf(toRemove);
  15519. if (index !== -1) {
  15520. // Remove from the scene if mesh found
  15521. this.lights.splice(index, 1);
  15522. }
  15523. this.onLightRemovedObservable.notifyObservers(toRemove);
  15524. return index;
  15525. };
  15526. Scene.prototype.removeCamera = function (toRemove) {
  15527. var index = this.cameras.indexOf(toRemove);
  15528. if (index !== -1) {
  15529. // Remove from the scene if mesh found
  15530. this.cameras.splice(index, 1);
  15531. }
  15532. // Remove from activeCameras
  15533. var index2 = this.activeCameras.indexOf(toRemove);
  15534. if (index2 !== -1) {
  15535. // Remove from the scene if mesh found
  15536. this.activeCameras.splice(index2, 1);
  15537. }
  15538. // Reset the activeCamera
  15539. if (this.activeCamera === toRemove) {
  15540. if (this.cameras.length > 0) {
  15541. this.activeCamera = this.cameras[0];
  15542. }
  15543. else {
  15544. this.activeCamera = null;
  15545. }
  15546. }
  15547. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15548. return index;
  15549. };
  15550. Scene.prototype.addLight = function (newLight) {
  15551. newLight.uniqueId = this._uniqueIdCounter++;
  15552. var position = this.lights.push(newLight);
  15553. this.onNewLightAddedObservable.notifyObservers(newLight);
  15554. };
  15555. Scene.prototype.addCamera = function (newCamera) {
  15556. newCamera.uniqueId = this._uniqueIdCounter++;
  15557. var position = this.cameras.push(newCamera);
  15558. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15559. };
  15560. /**
  15561. * Switch active camera
  15562. * @param {Camera} newCamera - new active camera
  15563. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15564. */
  15565. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15566. if (attachControl === void 0) { attachControl = true; }
  15567. var canvas = this._engine.getRenderingCanvas();
  15568. this.activeCamera.detachControl(canvas);
  15569. this.activeCamera = newCamera;
  15570. if (attachControl) {
  15571. newCamera.attachControl(canvas);
  15572. }
  15573. };
  15574. /**
  15575. * sets the active camera of the scene using its ID
  15576. * @param {string} id - the camera's ID
  15577. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15578. * @see activeCamera
  15579. */
  15580. Scene.prototype.setActiveCameraByID = function (id) {
  15581. var camera = this.getCameraByID(id);
  15582. if (camera) {
  15583. this.activeCamera = camera;
  15584. return camera;
  15585. }
  15586. return null;
  15587. };
  15588. /**
  15589. * sets the active camera of the scene using its name
  15590. * @param {string} name - the camera's name
  15591. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15592. * @see activeCamera
  15593. */
  15594. Scene.prototype.setActiveCameraByName = function (name) {
  15595. var camera = this.getCameraByName(name);
  15596. if (camera) {
  15597. this.activeCamera = camera;
  15598. return camera;
  15599. }
  15600. return null;
  15601. };
  15602. /**
  15603. * get a material using its id
  15604. * @param {string} the material's ID
  15605. * @return {BABYLON.Material|null} the material or null if none found.
  15606. */
  15607. Scene.prototype.getMaterialByID = function (id) {
  15608. for (var index = 0; index < this.materials.length; index++) {
  15609. if (this.materials[index].id === id) {
  15610. return this.materials[index];
  15611. }
  15612. }
  15613. return null;
  15614. };
  15615. /**
  15616. * get a material using its name
  15617. * @param {string} the material's name
  15618. * @return {BABYLON.Material|null} the material or null if none found.
  15619. */
  15620. Scene.prototype.getMaterialByName = function (name) {
  15621. for (var index = 0; index < this.materials.length; index++) {
  15622. if (this.materials[index].name === name) {
  15623. return this.materials[index];
  15624. }
  15625. }
  15626. return null;
  15627. };
  15628. Scene.prototype.getLensFlareSystemByName = function (name) {
  15629. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15630. if (this.lensFlareSystems[index].name === name) {
  15631. return this.lensFlareSystems[index];
  15632. }
  15633. }
  15634. return null;
  15635. };
  15636. Scene.prototype.getLensFlareSystemByID = function (id) {
  15637. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15638. if (this.lensFlareSystems[index].id === id) {
  15639. return this.lensFlareSystems[index];
  15640. }
  15641. }
  15642. return null;
  15643. };
  15644. Scene.prototype.getCameraByID = function (id) {
  15645. for (var index = 0; index < this.cameras.length; index++) {
  15646. if (this.cameras[index].id === id) {
  15647. return this.cameras[index];
  15648. }
  15649. }
  15650. return null;
  15651. };
  15652. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15653. for (var index = 0; index < this.cameras.length; index++) {
  15654. if (this.cameras[index].uniqueId === uniqueId) {
  15655. return this.cameras[index];
  15656. }
  15657. }
  15658. return null;
  15659. };
  15660. /**
  15661. * get a camera using its name
  15662. * @param {string} the camera's name
  15663. * @return {BABYLON.Camera|null} the camera or null if none found.
  15664. */
  15665. Scene.prototype.getCameraByName = function (name) {
  15666. for (var index = 0; index < this.cameras.length; index++) {
  15667. if (this.cameras[index].name === name) {
  15668. return this.cameras[index];
  15669. }
  15670. }
  15671. return null;
  15672. };
  15673. /**
  15674. * get a bone using its id
  15675. * @param {string} the bone's id
  15676. * @return {BABYLON.Bone|null} the bone or null if not found
  15677. */
  15678. Scene.prototype.getBoneByID = function (id) {
  15679. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15680. var skeleton = this.skeletons[skeletonIndex];
  15681. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15682. if (skeleton.bones[boneIndex].id === id) {
  15683. return skeleton.bones[boneIndex];
  15684. }
  15685. }
  15686. }
  15687. return null;
  15688. };
  15689. /**
  15690. * get a bone using its id
  15691. * @param {string} the bone's name
  15692. * @return {BABYLON.Bone|null} the bone or null if not found
  15693. */
  15694. Scene.prototype.getBoneByName = function (name) {
  15695. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15696. var skeleton = this.skeletons[skeletonIndex];
  15697. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15698. if (skeleton.bones[boneIndex].name === name) {
  15699. return skeleton.bones[boneIndex];
  15700. }
  15701. }
  15702. }
  15703. return null;
  15704. };
  15705. /**
  15706. * get a light node using its name
  15707. * @param {string} the light's name
  15708. * @return {BABYLON.Light|null} the light or null if none found.
  15709. */
  15710. Scene.prototype.getLightByName = function (name) {
  15711. for (var index = 0; index < this.lights.length; index++) {
  15712. if (this.lights[index].name === name) {
  15713. return this.lights[index];
  15714. }
  15715. }
  15716. return null;
  15717. };
  15718. /**
  15719. * get a light node using its ID
  15720. * @param {string} the light's id
  15721. * @return {BABYLON.Light|null} the light or null if none found.
  15722. */
  15723. Scene.prototype.getLightByID = function (id) {
  15724. for (var index = 0; index < this.lights.length; index++) {
  15725. if (this.lights[index].id === id) {
  15726. return this.lights[index];
  15727. }
  15728. }
  15729. return null;
  15730. };
  15731. /**
  15732. * get a light node using its scene-generated unique ID
  15733. * @param {number} the light's unique id
  15734. * @return {BABYLON.Light|null} the light or null if none found.
  15735. */
  15736. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15737. for (var index = 0; index < this.lights.length; index++) {
  15738. if (this.lights[index].uniqueId === uniqueId) {
  15739. return this.lights[index];
  15740. }
  15741. }
  15742. return null;
  15743. };
  15744. /**
  15745. * get a particle system by id
  15746. * @param id {number} the particle system id
  15747. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15748. */
  15749. Scene.prototype.getParticleSystemByID = function (id) {
  15750. for (var index = 0; index < this.particleSystems.length; index++) {
  15751. if (this.particleSystems[index].id === id) {
  15752. return this.particleSystems[index];
  15753. }
  15754. }
  15755. return null;
  15756. };
  15757. /**
  15758. * get a geometry using its ID
  15759. * @param {string} the geometry's id
  15760. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15761. */
  15762. Scene.prototype.getGeometryByID = function (id) {
  15763. for (var index = 0; index < this._geometries.length; index++) {
  15764. if (this._geometries[index].id === id) {
  15765. return this._geometries[index];
  15766. }
  15767. }
  15768. return null;
  15769. };
  15770. /**
  15771. * add a new geometry to this scene.
  15772. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15773. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15774. * @return {boolean} was the geometry added or not
  15775. */
  15776. Scene.prototype.pushGeometry = function (geometry, force) {
  15777. if (!force && this.getGeometryByID(geometry.id)) {
  15778. return false;
  15779. }
  15780. this._geometries.push(geometry);
  15781. //notify the collision coordinator
  15782. this.collisionCoordinator.onGeometryAdded(geometry);
  15783. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15784. return true;
  15785. };
  15786. /**
  15787. * Removes an existing geometry
  15788. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15789. * @return {boolean} was the geometry removed or not
  15790. */
  15791. Scene.prototype.removeGeometry = function (geometry) {
  15792. var index = this._geometries.indexOf(geometry);
  15793. if (index > -1) {
  15794. this._geometries.splice(index, 1);
  15795. //notify the collision coordinator
  15796. this.collisionCoordinator.onGeometryDeleted(geometry);
  15797. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15798. return true;
  15799. }
  15800. return false;
  15801. };
  15802. Scene.prototype.getGeometries = function () {
  15803. return this._geometries;
  15804. };
  15805. /**
  15806. * Get the first added mesh found of a given ID
  15807. * @param {string} id - the id to search for
  15808. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15809. */
  15810. Scene.prototype.getMeshByID = function (id) {
  15811. for (var index = 0; index < this.meshes.length; index++) {
  15812. if (this.meshes[index].id === id) {
  15813. return this.meshes[index];
  15814. }
  15815. }
  15816. return null;
  15817. };
  15818. Scene.prototype.getMeshesByID = function (id) {
  15819. return this.meshes.filter(function (m) {
  15820. return m.id === id;
  15821. });
  15822. };
  15823. /**
  15824. * Get a mesh with its auto-generated unique id
  15825. * @param {number} uniqueId - the unique id to search for
  15826. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15827. */
  15828. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15829. for (var index = 0; index < this.meshes.length; index++) {
  15830. if (this.meshes[index].uniqueId === uniqueId) {
  15831. return this.meshes[index];
  15832. }
  15833. }
  15834. return null;
  15835. };
  15836. /**
  15837. * Get a the last added mesh found of a given ID
  15838. * @param {string} id - the id to search for
  15839. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15840. */
  15841. Scene.prototype.getLastMeshByID = function (id) {
  15842. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15843. if (this.meshes[index].id === id) {
  15844. return this.meshes[index];
  15845. }
  15846. }
  15847. return null;
  15848. };
  15849. /**
  15850. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15851. * @param {string} id - the id to search for
  15852. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15853. */
  15854. Scene.prototype.getLastEntryByID = function (id) {
  15855. var index;
  15856. for (index = this.meshes.length - 1; index >= 0; index--) {
  15857. if (this.meshes[index].id === id) {
  15858. return this.meshes[index];
  15859. }
  15860. }
  15861. for (index = this.cameras.length - 1; index >= 0; index--) {
  15862. if (this.cameras[index].id === id) {
  15863. return this.cameras[index];
  15864. }
  15865. }
  15866. for (index = this.lights.length - 1; index >= 0; index--) {
  15867. if (this.lights[index].id === id) {
  15868. return this.lights[index];
  15869. }
  15870. }
  15871. return null;
  15872. };
  15873. Scene.prototype.getNodeByID = function (id) {
  15874. var mesh = this.getMeshByID(id);
  15875. if (mesh) {
  15876. return mesh;
  15877. }
  15878. var light = this.getLightByID(id);
  15879. if (light) {
  15880. return light;
  15881. }
  15882. var camera = this.getCameraByID(id);
  15883. if (camera) {
  15884. return camera;
  15885. }
  15886. var bone = this.getBoneByID(id);
  15887. return bone;
  15888. };
  15889. Scene.prototype.getNodeByName = function (name) {
  15890. var mesh = this.getMeshByName(name);
  15891. if (mesh) {
  15892. return mesh;
  15893. }
  15894. var light = this.getLightByName(name);
  15895. if (light) {
  15896. return light;
  15897. }
  15898. var camera = this.getCameraByName(name);
  15899. if (camera) {
  15900. return camera;
  15901. }
  15902. var bone = this.getBoneByName(name);
  15903. return bone;
  15904. };
  15905. Scene.prototype.getMeshByName = function (name) {
  15906. for (var index = 0; index < this.meshes.length; index++) {
  15907. if (this.meshes[index].name === name) {
  15908. return this.meshes[index];
  15909. }
  15910. }
  15911. return null;
  15912. };
  15913. Scene.prototype.getSoundByName = function (name) {
  15914. var index;
  15915. if (BABYLON.AudioEngine) {
  15916. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15917. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15918. return this.mainSoundTrack.soundCollection[index];
  15919. }
  15920. }
  15921. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15922. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15923. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15924. return this.soundTracks[sdIndex].soundCollection[index];
  15925. }
  15926. }
  15927. }
  15928. }
  15929. return null;
  15930. };
  15931. Scene.prototype.getLastSkeletonByID = function (id) {
  15932. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15933. if (this.skeletons[index].id === id) {
  15934. return this.skeletons[index];
  15935. }
  15936. }
  15937. return null;
  15938. };
  15939. Scene.prototype.getSkeletonById = function (id) {
  15940. for (var index = 0; index < this.skeletons.length; index++) {
  15941. if (this.skeletons[index].id === id) {
  15942. return this.skeletons[index];
  15943. }
  15944. }
  15945. return null;
  15946. };
  15947. Scene.prototype.getSkeletonByName = function (name) {
  15948. for (var index = 0; index < this.skeletons.length; index++) {
  15949. if (this.skeletons[index].name === name) {
  15950. return this.skeletons[index];
  15951. }
  15952. }
  15953. return null;
  15954. };
  15955. Scene.prototype.isActiveMesh = function (mesh) {
  15956. return (this._activeMeshes.indexOf(mesh) !== -1);
  15957. };
  15958. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15959. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15960. var material = subMesh.getMaterial();
  15961. if (mesh.showSubMeshesBoundingBox) {
  15962. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15963. }
  15964. if (material) {
  15965. // Render targets
  15966. if (material.getRenderTargetTextures) {
  15967. if (this._processedMaterials.indexOf(material) === -1) {
  15968. this._processedMaterials.push(material);
  15969. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15970. }
  15971. }
  15972. // Dispatch
  15973. this._activeIndices += subMesh.indexCount;
  15974. this._renderingManager.dispatch(subMesh);
  15975. }
  15976. }
  15977. };
  15978. Scene.prototype._isInIntermediateRendering = function () {
  15979. return this._intermediateRendering;
  15980. };
  15981. Scene.prototype._evaluateActiveMeshes = function () {
  15982. this.activeCamera._activeMeshes.reset();
  15983. this._activeMeshes.reset();
  15984. this._renderingManager.reset();
  15985. this._processedMaterials.reset();
  15986. this._activeParticleSystems.reset();
  15987. this._activeSkeletons.reset();
  15988. this._softwareSkinnedMeshes.reset();
  15989. this._boundingBoxRenderer.reset();
  15990. this._edgesRenderers.reset();
  15991. if (!this._frustumPlanes) {
  15992. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15993. }
  15994. else {
  15995. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15996. }
  15997. // Meshes
  15998. var meshes;
  15999. var len;
  16000. if (this._selectionOctree) {
  16001. var selection = this._selectionOctree.select(this._frustumPlanes);
  16002. meshes = selection.data;
  16003. len = selection.length;
  16004. }
  16005. else {
  16006. len = this.meshes.length;
  16007. meshes = this.meshes;
  16008. }
  16009. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16010. var mesh = meshes[meshIndex];
  16011. if (mesh.isBlocked) {
  16012. continue;
  16013. }
  16014. this._totalVertices += mesh.getTotalVertices();
  16015. if (!mesh.isReady() || !mesh.isEnabled()) {
  16016. continue;
  16017. }
  16018. mesh.computeWorldMatrix();
  16019. // Intersections
  16020. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16021. this._meshesForIntersections.pushNoDuplicate(mesh);
  16022. }
  16023. // Switch to current LOD
  16024. var meshLOD = mesh.getLOD(this.activeCamera);
  16025. if (!meshLOD) {
  16026. continue;
  16027. }
  16028. mesh._preActivate();
  16029. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16030. this._activeMeshes.push(mesh);
  16031. this.activeCamera._activeMeshes.push(mesh);
  16032. mesh._activate(this._renderId);
  16033. this._activeMesh(meshLOD);
  16034. }
  16035. }
  16036. // Particle systems
  16037. var beforeParticlesDate = BABYLON.Tools.Now;
  16038. if (this.particlesEnabled) {
  16039. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16040. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16041. var particleSystem = this.particleSystems[particleIndex];
  16042. if (!particleSystem.isStarted()) {
  16043. continue;
  16044. }
  16045. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16046. this._activeParticleSystems.push(particleSystem);
  16047. particleSystem.animate();
  16048. }
  16049. }
  16050. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16051. }
  16052. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  16053. };
  16054. Scene.prototype._activeMesh = function (mesh) {
  16055. if (mesh.skeleton && this.skeletonsEnabled) {
  16056. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16057. mesh.skeleton.prepare();
  16058. }
  16059. if (!mesh.computeBonesUsingShaders) {
  16060. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16061. }
  16062. }
  16063. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16064. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  16065. }
  16066. if (mesh._edgesRenderer) {
  16067. this._edgesRenderers.push(mesh._edgesRenderer);
  16068. }
  16069. if (mesh && mesh.subMeshes) {
  16070. // Submeshes Octrees
  16071. var len;
  16072. var subMeshes;
  16073. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16074. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16075. len = intersections.length;
  16076. subMeshes = intersections.data;
  16077. }
  16078. else {
  16079. subMeshes = mesh.subMeshes;
  16080. len = subMeshes.length;
  16081. }
  16082. for (var subIndex = 0; subIndex < len; subIndex++) {
  16083. var subMesh = subMeshes[subIndex];
  16084. this._evaluateSubMesh(subMesh, mesh);
  16085. }
  16086. }
  16087. };
  16088. Scene.prototype.updateTransformMatrix = function (force) {
  16089. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16090. };
  16091. Scene.prototype._renderForCamera = function (camera) {
  16092. var engine = this._engine;
  16093. this.activeCamera = camera;
  16094. if (!this.activeCamera)
  16095. throw new Error("Active camera not set");
  16096. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16097. // Viewport
  16098. engine.setViewport(this.activeCamera.viewport);
  16099. // Camera
  16100. this.resetCachedMaterial();
  16101. this._renderId++;
  16102. this.updateTransformMatrix();
  16103. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16104. // Meshes
  16105. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  16106. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16107. this._evaluateActiveMeshes();
  16108. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  16109. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16110. // Software skinning
  16111. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16112. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16113. mesh.applySkeleton(mesh.skeleton);
  16114. }
  16115. // Render targets
  16116. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16117. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16118. this._intermediateRendering = true;
  16119. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16120. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16121. var renderTarget = this._renderTargets.data[renderIndex];
  16122. if (renderTarget._shouldRender()) {
  16123. this._renderId++;
  16124. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16125. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16126. }
  16127. }
  16128. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16129. this._intermediateRendering = false;
  16130. this._renderId++;
  16131. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16132. }
  16133. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16134. // Prepare Frame
  16135. this.postProcessManager._prepareFrame();
  16136. var beforeRenderDate = BABYLON.Tools.Now;
  16137. // Backgrounds
  16138. var layerIndex;
  16139. var layer;
  16140. if (this.layers.length) {
  16141. engine.setDepthBuffer(false);
  16142. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16143. layer = this.layers[layerIndex];
  16144. if (layer.isBackground) {
  16145. layer.render();
  16146. }
  16147. }
  16148. engine.setDepthBuffer(true);
  16149. }
  16150. // Render
  16151. BABYLON.Tools.StartPerformanceCounter("Main render");
  16152. this._renderingManager.render(null, null, true, true);
  16153. BABYLON.Tools.EndPerformanceCounter("Main render");
  16154. // Bounding boxes
  16155. this._boundingBoxRenderer.render();
  16156. // Edges
  16157. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16158. this._edgesRenderers.data[edgesRendererIndex].render();
  16159. }
  16160. // Lens flares
  16161. if (this.lensFlaresEnabled) {
  16162. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16163. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16164. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16165. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16166. lensFlareSystem.render();
  16167. }
  16168. }
  16169. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16170. }
  16171. // Foregrounds
  16172. if (this.layers.length) {
  16173. engine.setDepthBuffer(false);
  16174. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16175. layer = this.layers[layerIndex];
  16176. if (!layer.isBackground) {
  16177. layer.render();
  16178. }
  16179. }
  16180. engine.setDepthBuffer(true);
  16181. }
  16182. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  16183. // Finalize frame
  16184. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16185. // Update camera
  16186. this.activeCamera._updateFromScene();
  16187. // Reset some special arrays
  16188. this._renderTargets.reset();
  16189. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16190. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16191. };
  16192. Scene.prototype._processSubCameras = function (camera) {
  16193. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16194. this._renderForCamera(camera);
  16195. return;
  16196. }
  16197. // rig cameras
  16198. for (var index = 0; index < camera._rigCameras.length; index++) {
  16199. this._renderForCamera(camera._rigCameras[index]);
  16200. }
  16201. this.activeCamera = camera;
  16202. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16203. // Update camera
  16204. this.activeCamera._updateFromScene();
  16205. };
  16206. Scene.prototype._checkIntersections = function () {
  16207. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16208. var sourceMesh = this._meshesForIntersections.data[index];
  16209. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16210. var action = sourceMesh.actionManager.actions[actionIndex];
  16211. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16212. var parameters = action.getTriggerParameter();
  16213. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16214. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16215. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16216. if (areIntersecting && currentIntersectionInProgress === -1) {
  16217. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16218. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16219. sourceMesh._intersectionsInProgress.push(otherMesh);
  16220. }
  16221. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16222. sourceMesh._intersectionsInProgress.push(otherMesh);
  16223. }
  16224. }
  16225. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16226. //They intersected, and now they don't.
  16227. //is this trigger an exit trigger? execute an event.
  16228. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16229. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16230. }
  16231. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16232. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16233. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16234. }
  16235. }
  16236. }
  16237. }
  16238. }
  16239. };
  16240. Scene.prototype.render = function () {
  16241. var startDate = BABYLON.Tools.Now;
  16242. this._particlesDuration = 0;
  16243. this._spritesDuration = 0;
  16244. this._activeParticles = 0;
  16245. this._renderDuration = 0;
  16246. this._renderTargetsDuration = 0;
  16247. this._evaluateActiveMeshesDuration = 0;
  16248. this._totalVertices = 0;
  16249. this._activeIndices = 0;
  16250. this._activeBones = 0;
  16251. this.getEngine().resetDrawCalls();
  16252. this._meshesForIntersections.reset();
  16253. this.resetCachedMaterial();
  16254. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16255. // Actions
  16256. if (this.actionManager) {
  16257. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16258. }
  16259. //Simplification Queue
  16260. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16261. this.simplificationQueue.executeNext();
  16262. }
  16263. // Animations
  16264. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16265. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16266. this._animate();
  16267. // Physics
  16268. if (this._physicsEngine) {
  16269. BABYLON.Tools.StartPerformanceCounter("Physics");
  16270. this._physicsEngine._step(deltaTime / 1000.0);
  16271. BABYLON.Tools.EndPerformanceCounter("Physics");
  16272. }
  16273. // Before render
  16274. this.onBeforeRenderObservable.notifyObservers(this);
  16275. // Customs render targets
  16276. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16277. var engine = this.getEngine();
  16278. var currentActiveCamera = this.activeCamera;
  16279. if (this.renderTargetsEnabled) {
  16280. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16281. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16282. var renderTarget = this.customRenderTargets[customIndex];
  16283. if (renderTarget._shouldRender()) {
  16284. this._renderId++;
  16285. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16286. if (!this.activeCamera)
  16287. throw new Error("Active camera not set");
  16288. // Viewport
  16289. engine.setViewport(this.activeCamera.viewport);
  16290. // Camera
  16291. this.updateTransformMatrix();
  16292. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16293. }
  16294. }
  16295. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16296. this._renderId++;
  16297. }
  16298. if (this.customRenderTargets.length > 0) {
  16299. engine.restoreDefaultFramebuffer();
  16300. }
  16301. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16302. this.activeCamera = currentActiveCamera;
  16303. // Procedural textures
  16304. if (this.proceduralTexturesEnabled) {
  16305. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16306. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16307. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16308. if (proceduralTexture._shouldRender()) {
  16309. proceduralTexture.render();
  16310. }
  16311. }
  16312. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16313. }
  16314. // Clear
  16315. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16316. // Shadows
  16317. if (this.shadowsEnabled) {
  16318. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16319. var light = this.lights[lightIndex];
  16320. var shadowGenerator = light.getShadowGenerator();
  16321. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16322. this._renderTargets.push(shadowGenerator.getShadowMap());
  16323. }
  16324. }
  16325. }
  16326. // Depth renderer
  16327. if (this._depthRenderer) {
  16328. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16329. }
  16330. // RenderPipeline
  16331. this.postProcessRenderPipelineManager.update();
  16332. // Multi-cameras?
  16333. if (this.activeCameras.length > 0) {
  16334. var currentRenderId = this._renderId;
  16335. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16336. this._renderId = currentRenderId;
  16337. if (cameraIndex > 0) {
  16338. this._engine.clear(0, false, true);
  16339. }
  16340. this._processSubCameras(this.activeCameras[cameraIndex]);
  16341. }
  16342. }
  16343. else {
  16344. if (!this.activeCamera) {
  16345. throw new Error("No camera defined");
  16346. }
  16347. this._processSubCameras(this.activeCamera);
  16348. }
  16349. // Intersection checks
  16350. this._checkIntersections();
  16351. // Update the audio listener attached to the camera
  16352. if (BABYLON.AudioEngine) {
  16353. this._updateAudioParameters();
  16354. }
  16355. // After render
  16356. if (this.afterRender) {
  16357. this.afterRender();
  16358. }
  16359. this.onAfterRenderObservable.notifyObservers(this);
  16360. // Cleaning
  16361. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16362. this._toBeDisposed.data[index].dispose();
  16363. this._toBeDisposed[index] = null;
  16364. }
  16365. this._toBeDisposed.reset();
  16366. if (this.dumpNextRenderTargets) {
  16367. this.dumpNextRenderTargets = false;
  16368. }
  16369. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16370. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  16371. };
  16372. Scene.prototype._updateAudioParameters = function () {
  16373. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16374. return;
  16375. }
  16376. var listeningCamera;
  16377. var audioEngine = BABYLON.Engine.audioEngine;
  16378. if (this.activeCameras.length > 0) {
  16379. listeningCamera = this.activeCameras[0];
  16380. }
  16381. else {
  16382. listeningCamera = this.activeCamera;
  16383. }
  16384. if (listeningCamera && audioEngine.canUseWebAudio) {
  16385. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16386. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16387. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16388. cameraDirection.normalize();
  16389. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16390. var i;
  16391. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16392. var sound = this.mainSoundTrack.soundCollection[i];
  16393. if (sound.useCustomAttenuation) {
  16394. sound.updateDistanceFromListener();
  16395. }
  16396. }
  16397. for (i = 0; i < this.soundTracks.length; i++) {
  16398. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16399. sound = this.soundTracks[i].soundCollection[j];
  16400. if (sound.useCustomAttenuation) {
  16401. sound.updateDistanceFromListener();
  16402. }
  16403. }
  16404. }
  16405. }
  16406. };
  16407. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16408. // Audio
  16409. get: function () {
  16410. return this._audioEnabled;
  16411. },
  16412. set: function (value) {
  16413. this._audioEnabled = value;
  16414. if (BABYLON.AudioEngine) {
  16415. if (this._audioEnabled) {
  16416. this._enableAudio();
  16417. }
  16418. else {
  16419. this._disableAudio();
  16420. }
  16421. }
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Scene.prototype._disableAudio = function () {
  16427. var i;
  16428. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16429. this.mainSoundTrack.soundCollection[i].pause();
  16430. }
  16431. for (i = 0; i < this.soundTracks.length; i++) {
  16432. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16433. this.soundTracks[i].soundCollection[j].pause();
  16434. }
  16435. }
  16436. };
  16437. Scene.prototype._enableAudio = function () {
  16438. var i;
  16439. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16440. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16441. this.mainSoundTrack.soundCollection[i].play();
  16442. }
  16443. }
  16444. for (i = 0; i < this.soundTracks.length; i++) {
  16445. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16446. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16447. this.soundTracks[i].soundCollection[j].play();
  16448. }
  16449. }
  16450. }
  16451. };
  16452. Object.defineProperty(Scene.prototype, "headphone", {
  16453. get: function () {
  16454. return this._headphone;
  16455. },
  16456. set: function (value) {
  16457. this._headphone = value;
  16458. if (BABYLON.AudioEngine) {
  16459. if (this._headphone) {
  16460. this._switchAudioModeForHeadphones();
  16461. }
  16462. else {
  16463. this._switchAudioModeForNormalSpeakers();
  16464. }
  16465. }
  16466. },
  16467. enumerable: true,
  16468. configurable: true
  16469. });
  16470. Scene.prototype._switchAudioModeForHeadphones = function () {
  16471. this.mainSoundTrack.switchPanningModelToHRTF();
  16472. for (var i = 0; i < this.soundTracks.length; i++) {
  16473. this.soundTracks[i].switchPanningModelToHRTF();
  16474. }
  16475. };
  16476. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16477. this.mainSoundTrack.switchPanningModelToEqualPower();
  16478. for (var i = 0; i < this.soundTracks.length; i++) {
  16479. this.soundTracks[i].switchPanningModelToEqualPower();
  16480. }
  16481. };
  16482. Scene.prototype.enableDepthRenderer = function () {
  16483. if (this._depthRenderer) {
  16484. return this._depthRenderer;
  16485. }
  16486. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16487. return this._depthRenderer;
  16488. };
  16489. Scene.prototype.disableDepthRenderer = function () {
  16490. if (!this._depthRenderer) {
  16491. return;
  16492. }
  16493. this._depthRenderer.dispose();
  16494. this._depthRenderer = null;
  16495. };
  16496. Scene.prototype.freezeMaterials = function () {
  16497. for (var i = 0; i < this.materials.length; i++) {
  16498. this.materials[i].freeze();
  16499. }
  16500. };
  16501. Scene.prototype.unfreezeMaterials = function () {
  16502. for (var i = 0; i < this.materials.length; i++) {
  16503. this.materials[i].unfreeze();
  16504. }
  16505. };
  16506. Scene.prototype.dispose = function () {
  16507. this.beforeRender = null;
  16508. this.afterRender = null;
  16509. this.skeletons = [];
  16510. this._boundingBoxRenderer.dispose();
  16511. if (this._depthRenderer) {
  16512. this._depthRenderer.dispose();
  16513. }
  16514. // Debug layer
  16515. if (this._debugLayer) {
  16516. this._debugLayer.hide();
  16517. }
  16518. // Events
  16519. this.onDisposeObservable.notifyObservers(this);
  16520. this.onDisposeObservable.clear();
  16521. this.onBeforeRenderObservable.clear();
  16522. this.onAfterRenderObservable.clear();
  16523. this.detachControl();
  16524. // Release sounds & sounds tracks
  16525. if (BABYLON.AudioEngine) {
  16526. this.disposeSounds();
  16527. }
  16528. // Detach cameras
  16529. var canvas = this._engine.getRenderingCanvas();
  16530. var index;
  16531. for (index = 0; index < this.cameras.length; index++) {
  16532. this.cameras[index].detachControl(canvas);
  16533. }
  16534. // Release lights
  16535. while (this.lights.length) {
  16536. this.lights[0].dispose();
  16537. }
  16538. // Release meshes
  16539. while (this.meshes.length) {
  16540. this.meshes[0].dispose(true);
  16541. }
  16542. // Release cameras
  16543. while (this.cameras.length) {
  16544. this.cameras[0].dispose();
  16545. }
  16546. // Release materials
  16547. while (this.materials.length) {
  16548. this.materials[0].dispose();
  16549. }
  16550. // Release particles
  16551. while (this.particleSystems.length) {
  16552. this.particleSystems[0].dispose();
  16553. }
  16554. // Release sprites
  16555. while (this.spriteManagers.length) {
  16556. this.spriteManagers[0].dispose();
  16557. }
  16558. // Release layers
  16559. while (this.layers.length) {
  16560. this.layers[0].dispose();
  16561. }
  16562. // Release textures
  16563. while (this.textures.length) {
  16564. this.textures[0].dispose();
  16565. }
  16566. // Post-processes
  16567. this.postProcessManager.dispose();
  16568. // Physics
  16569. if (this._physicsEngine) {
  16570. this.disablePhysicsEngine();
  16571. }
  16572. // Remove from engine
  16573. index = this._engine.scenes.indexOf(this);
  16574. if (index > -1) {
  16575. this._engine.scenes.splice(index, 1);
  16576. }
  16577. this._engine.wipeCaches();
  16578. };
  16579. // Release sounds & sounds tracks
  16580. Scene.prototype.disposeSounds = function () {
  16581. this.mainSoundTrack.dispose();
  16582. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16583. this.soundTracks[scIndex].dispose();
  16584. }
  16585. };
  16586. // Octrees
  16587. Scene.prototype.getWorldExtends = function () {
  16588. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16589. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16590. for (var index = 0; index < this.meshes.length; index++) {
  16591. var mesh = this.meshes[index];
  16592. mesh.computeWorldMatrix(true);
  16593. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16594. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16595. BABYLON.Tools.CheckExtends(minBox, min, max);
  16596. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16597. }
  16598. return {
  16599. min: min,
  16600. max: max
  16601. };
  16602. };
  16603. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16604. if (maxCapacity === void 0) { maxCapacity = 64; }
  16605. if (maxDepth === void 0) { maxDepth = 2; }
  16606. if (!this._selectionOctree) {
  16607. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16608. }
  16609. var worldExtends = this.getWorldExtends();
  16610. // Update octree
  16611. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16612. return this._selectionOctree;
  16613. };
  16614. // Picking
  16615. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16616. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16617. var engine = this._engine;
  16618. if (!camera) {
  16619. if (!this.activeCamera)
  16620. throw new Error("Active camera not set");
  16621. camera = this.activeCamera;
  16622. }
  16623. var cameraViewport = camera.viewport;
  16624. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16625. // Moving coordinates to local viewport world
  16626. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16627. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16628. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16629. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16630. };
  16631. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16632. var engine = this._engine;
  16633. if (!camera) {
  16634. if (!this.activeCamera)
  16635. throw new Error("Active camera not set");
  16636. camera = this.activeCamera;
  16637. }
  16638. var cameraViewport = camera.viewport;
  16639. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16640. var identity = BABYLON.Matrix.Identity();
  16641. // Moving coordinates to local viewport world
  16642. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16643. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16644. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16645. };
  16646. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16647. var pickingInfo = null;
  16648. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16649. var mesh = this.meshes[meshIndex];
  16650. if (predicate) {
  16651. if (!predicate(mesh)) {
  16652. continue;
  16653. }
  16654. }
  16655. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16656. continue;
  16657. }
  16658. var world = mesh.getWorldMatrix();
  16659. var ray = rayFunction(world);
  16660. var result = mesh.intersects(ray, fastCheck);
  16661. if (!result || !result.hit)
  16662. continue;
  16663. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16664. continue;
  16665. pickingInfo = result;
  16666. if (fastCheck) {
  16667. break;
  16668. }
  16669. }
  16670. return pickingInfo || new BABYLON.PickingInfo();
  16671. };
  16672. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16673. var pickingInfo = null;
  16674. camera = camera || this.activeCamera;
  16675. if (this.spriteManagers.length > 0) {
  16676. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16677. var spriteManager = this.spriteManagers[spriteIndex];
  16678. if (!spriteManager.isPickable) {
  16679. continue;
  16680. }
  16681. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16682. if (!result || !result.hit)
  16683. continue;
  16684. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16685. continue;
  16686. pickingInfo = result;
  16687. if (fastCheck) {
  16688. break;
  16689. }
  16690. }
  16691. }
  16692. return pickingInfo || new BABYLON.PickingInfo();
  16693. };
  16694. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16695. var _this = this;
  16696. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16697. /// <param name="x">X position on screen</param>
  16698. /// <param name="y">Y position on screen</param>
  16699. /// <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>
  16700. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16701. /// <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>
  16702. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16703. };
  16704. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16705. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16706. /// <param name="x">X position on screen</param>
  16707. /// <param name="y">Y position on screen</param>
  16708. /// <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>
  16709. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16710. /// <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>
  16711. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16712. };
  16713. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16714. var _this = this;
  16715. return this._internalPick(function (world) {
  16716. if (!_this._pickWithRayInverseMatrix) {
  16717. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16718. }
  16719. world.invertToRef(_this._pickWithRayInverseMatrix);
  16720. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16721. }, predicate, fastCheck);
  16722. };
  16723. Scene.prototype.setPointerOverMesh = function (mesh) {
  16724. if (this._pointerOverMesh === mesh) {
  16725. return;
  16726. }
  16727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16729. }
  16730. this._pointerOverMesh = mesh;
  16731. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16732. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16733. }
  16734. };
  16735. Scene.prototype.getPointerOverMesh = function () {
  16736. return this._pointerOverMesh;
  16737. };
  16738. Scene.prototype.setPointerOverSprite = function (sprite) {
  16739. if (this._pointerOverSprite === sprite) {
  16740. return;
  16741. }
  16742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16744. }
  16745. this._pointerOverSprite = sprite;
  16746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16748. }
  16749. };
  16750. Scene.prototype.getPointerOverSprite = function () {
  16751. return this._pointerOverSprite;
  16752. };
  16753. // Physics
  16754. Scene.prototype.getPhysicsEngine = function () {
  16755. return this._physicsEngine;
  16756. };
  16757. /**
  16758. * Enables physics to the current scene
  16759. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16760. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16761. * @return {boolean} was the physics engine initialized
  16762. */
  16763. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16764. if (this._physicsEngine) {
  16765. return true;
  16766. }
  16767. try {
  16768. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16769. return true;
  16770. }
  16771. catch (e) {
  16772. BABYLON.Tools.Error(e.message);
  16773. return false;
  16774. }
  16775. };
  16776. Scene.prototype.disablePhysicsEngine = function () {
  16777. if (!this._physicsEngine) {
  16778. return;
  16779. }
  16780. this._physicsEngine.dispose();
  16781. this._physicsEngine = undefined;
  16782. };
  16783. Scene.prototype.isPhysicsEnabled = function () {
  16784. return this._physicsEngine !== undefined;
  16785. };
  16786. /**
  16787. *
  16788. * Sets the gravity of the physics engine (and NOT of the scene)
  16789. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16790. */
  16791. Scene.prototype.setGravity = function (gravity) {
  16792. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16793. if (!this._physicsEngine) {
  16794. return;
  16795. }
  16796. this._physicsEngine.setGravity(gravity);
  16797. };
  16798. /**
  16799. * Legacy support, using the new API
  16800. * @Deprecated
  16801. */
  16802. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16803. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16804. if (parts.parts) {
  16805. options = parts;
  16806. parts = parts.parts;
  16807. }
  16808. var mainMesh = parts[0].mesh;
  16809. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16810. for (var index = 1; index < parts.length; index++) {
  16811. var mesh = parts[index].mesh;
  16812. if (mesh.parent !== mainMesh) {
  16813. mesh.position = mesh.position.subtract(mainMesh.position);
  16814. mesh.parent = mainMesh;
  16815. }
  16816. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16817. }
  16818. mainMesh.physicsImpostor.forceUpdate();
  16819. };
  16820. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16821. var mesh = compound.parts[0].mesh;
  16822. mesh.physicsImpostor.dispose();
  16823. mesh.physicsImpostor = null;
  16824. };
  16825. // Misc.
  16826. Scene.prototype.createDefaultCameraOrLight = function () {
  16827. // Light
  16828. if (this.lights.length === 0) {
  16829. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16830. }
  16831. // Camera
  16832. if (!this.activeCamera) {
  16833. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16834. // Compute position
  16835. var worldExtends = this.getWorldExtends();
  16836. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16837. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16838. camera.setTarget(worldCenter);
  16839. this.activeCamera = camera;
  16840. }
  16841. };
  16842. // Tags
  16843. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16844. if (tagsQuery === undefined) {
  16845. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16846. return list;
  16847. }
  16848. var listByTags = [];
  16849. forEach = forEach || (function (item) { return; });
  16850. for (var i in list) {
  16851. var item = list[i];
  16852. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16853. listByTags.push(item);
  16854. forEach(item);
  16855. }
  16856. }
  16857. return listByTags;
  16858. };
  16859. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16860. return this._getByTags(this.meshes, tagsQuery, forEach);
  16861. };
  16862. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16863. return this._getByTags(this.cameras, tagsQuery, forEach);
  16864. };
  16865. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16866. return this._getByTags(this.lights, tagsQuery, forEach);
  16867. };
  16868. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16869. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16870. };
  16871. // Statics
  16872. Scene._FOGMODE_NONE = 0;
  16873. Scene._FOGMODE_EXP = 1;
  16874. Scene._FOGMODE_EXP2 = 2;
  16875. Scene._FOGMODE_LINEAR = 3;
  16876. Scene.MinDeltaTime = 1.0;
  16877. Scene.MaxDeltaTime = 1000.0;
  16878. return Scene;
  16879. })();
  16880. BABYLON.Scene = Scene;
  16881. })(BABYLON || (BABYLON = {}));
  16882. var BABYLON;
  16883. (function (BABYLON) {
  16884. var Buffer = (function () {
  16885. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  16886. if (engine instanceof BABYLON.Mesh) {
  16887. this._engine = engine.getScene().getEngine();
  16888. }
  16889. else {
  16890. this._engine = engine;
  16891. }
  16892. this._updatable = updatable;
  16893. this._data = data;
  16894. this._strideSize = stride;
  16895. if (!postponeInternalCreation) {
  16896. this.create();
  16897. }
  16898. this._instanced = instanced;
  16899. }
  16900. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  16901. // a lot of these parameters are ignored as they are overriden by the buffer
  16902. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  16903. };
  16904. // Properties
  16905. Buffer.prototype.isUpdatable = function () {
  16906. return this._updatable;
  16907. };
  16908. Buffer.prototype.getData = function () {
  16909. return this._data;
  16910. };
  16911. Buffer.prototype.getBuffer = function () {
  16912. return this._buffer;
  16913. };
  16914. Buffer.prototype.getStrideSize = function () {
  16915. return this._strideSize;
  16916. };
  16917. Buffer.prototype.getIsInstanced = function () {
  16918. return this._instanced;
  16919. };
  16920. // Methods
  16921. Buffer.prototype.create = function (data) {
  16922. if (!data && this._buffer) {
  16923. return; // nothing to do
  16924. }
  16925. data = data || this._data;
  16926. if (!this._buffer) {
  16927. if (this._updatable) {
  16928. this._buffer = this._engine.createDynamicVertexBuffer(data);
  16929. this._data = data;
  16930. }
  16931. else {
  16932. this._buffer = this._engine.createVertexBuffer(data);
  16933. }
  16934. }
  16935. else if (this._updatable) {
  16936. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16937. this._data = data;
  16938. }
  16939. };
  16940. Buffer.prototype.update = function (data) {
  16941. this.create(data);
  16942. };
  16943. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  16944. if (!this._buffer) {
  16945. return;
  16946. }
  16947. if (this._updatable) {
  16948. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  16949. this._data = null;
  16950. }
  16951. };
  16952. Buffer.prototype.dispose = function () {
  16953. if (!this._buffer) {
  16954. return;
  16955. }
  16956. if (this._engine._releaseBuffer(this._buffer)) {
  16957. this._buffer = null;
  16958. }
  16959. };
  16960. return Buffer;
  16961. })();
  16962. BABYLON.Buffer = Buffer;
  16963. })(BABYLON || (BABYLON = {}));
  16964. var BABYLON;
  16965. (function (BABYLON) {
  16966. var VertexBuffer = (function () {
  16967. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  16968. if (!stride) {
  16969. // Deduce stride from kind
  16970. switch (kind) {
  16971. case VertexBuffer.PositionKind:
  16972. stride = 3;
  16973. break;
  16974. case VertexBuffer.NormalKind:
  16975. stride = 3;
  16976. break;
  16977. case VertexBuffer.UVKind:
  16978. case VertexBuffer.UV2Kind:
  16979. case VertexBuffer.UV3Kind:
  16980. case VertexBuffer.UV4Kind:
  16981. case VertexBuffer.UV5Kind:
  16982. case VertexBuffer.UV6Kind:
  16983. stride = 2;
  16984. break;
  16985. case VertexBuffer.ColorKind:
  16986. stride = 4;
  16987. break;
  16988. case VertexBuffer.MatricesIndicesKind:
  16989. case VertexBuffer.MatricesIndicesExtraKind:
  16990. stride = 4;
  16991. break;
  16992. case VertexBuffer.MatricesWeightsKind:
  16993. case VertexBuffer.MatricesWeightsExtraKind:
  16994. stride = 4;
  16995. break;
  16996. }
  16997. }
  16998. if (data instanceof BABYLON.Buffer) {
  16999. if (!stride) {
  17000. stride = data.getStrideSize();
  17001. }
  17002. this._buffer = data;
  17003. this._ownsBuffer = false;
  17004. }
  17005. else {
  17006. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17007. this._ownsBuffer = true;
  17008. }
  17009. this._stride = stride;
  17010. this._offset = offset ? offset : 0;
  17011. this._size = size ? size : stride;
  17012. this._kind = kind;
  17013. }
  17014. VertexBuffer.prototype.getKind = function () {
  17015. return this._kind;
  17016. };
  17017. // Properties
  17018. VertexBuffer.prototype.isUpdatable = function () {
  17019. return this._buffer.isUpdatable();
  17020. };
  17021. VertexBuffer.prototype.getData = function () {
  17022. return this._buffer.getData();
  17023. };
  17024. VertexBuffer.prototype.getBuffer = function () {
  17025. return this._buffer.getBuffer();
  17026. };
  17027. VertexBuffer.prototype.getStrideSize = function () {
  17028. return this._stride;
  17029. };
  17030. VertexBuffer.prototype.getOffset = function () {
  17031. return this._offset;
  17032. };
  17033. VertexBuffer.prototype.getSize = function () {
  17034. return this._size;
  17035. };
  17036. VertexBuffer.prototype.getIsInstanced = function () {
  17037. return this._buffer.getIsInstanced();
  17038. };
  17039. // Methods
  17040. VertexBuffer.prototype.create = function (data) {
  17041. return this._buffer.create(data);
  17042. };
  17043. VertexBuffer.prototype.update = function (data) {
  17044. return this._buffer.update(data);
  17045. };
  17046. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17047. return this._buffer.updateDirectly(data, offset);
  17048. };
  17049. VertexBuffer.prototype.dispose = function () {
  17050. if (this._ownsBuffer) {
  17051. this._buffer.dispose();
  17052. }
  17053. };
  17054. Object.defineProperty(VertexBuffer, "PositionKind", {
  17055. get: function () {
  17056. return VertexBuffer._PositionKind;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(VertexBuffer, "NormalKind", {
  17062. get: function () {
  17063. return VertexBuffer._NormalKind;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(VertexBuffer, "UVKind", {
  17069. get: function () {
  17070. return VertexBuffer._UVKind;
  17071. },
  17072. enumerable: true,
  17073. configurable: true
  17074. });
  17075. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17076. get: function () {
  17077. return VertexBuffer._UV2Kind;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17083. get: function () {
  17084. return VertexBuffer._UV3Kind;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17090. get: function () {
  17091. return VertexBuffer._UV4Kind;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17097. get: function () {
  17098. return VertexBuffer._UV5Kind;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17104. get: function () {
  17105. return VertexBuffer._UV6Kind;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(VertexBuffer, "ColorKind", {
  17111. get: function () {
  17112. return VertexBuffer._ColorKind;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17118. get: function () {
  17119. return VertexBuffer._MatricesIndicesKind;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17125. get: function () {
  17126. return VertexBuffer._MatricesWeightsKind;
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17132. get: function () {
  17133. return VertexBuffer._MatricesIndicesExtraKind;
  17134. },
  17135. enumerable: true,
  17136. configurable: true
  17137. });
  17138. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17139. get: function () {
  17140. return VertexBuffer._MatricesWeightsExtraKind;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. // Enums
  17146. VertexBuffer._PositionKind = "position";
  17147. VertexBuffer._NormalKind = "normal";
  17148. VertexBuffer._UVKind = "uv";
  17149. VertexBuffer._UV2Kind = "uv2";
  17150. VertexBuffer._UV3Kind = "uv3";
  17151. VertexBuffer._UV4Kind = "uv4";
  17152. VertexBuffer._UV5Kind = "uv5";
  17153. VertexBuffer._UV6Kind = "uv6";
  17154. VertexBuffer._ColorKind = "color";
  17155. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17156. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17157. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17158. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17159. return VertexBuffer;
  17160. })();
  17161. BABYLON.VertexBuffer = VertexBuffer;
  17162. })(BABYLON || (BABYLON = {}));
  17163. var BABYLON;
  17164. (function (BABYLON) {
  17165. /**
  17166. * Creates an instance based on a source mesh.
  17167. */
  17168. var InstancedMesh = (function (_super) {
  17169. __extends(InstancedMesh, _super);
  17170. function InstancedMesh(name, source) {
  17171. _super.call(this, name, source.getScene());
  17172. source.instances.push(this);
  17173. this._sourceMesh = source;
  17174. this.position.copyFrom(source.position);
  17175. this.rotation.copyFrom(source.rotation);
  17176. this.scaling.copyFrom(source.scaling);
  17177. if (source.rotationQuaternion) {
  17178. this.rotationQuaternion = source.rotationQuaternion.clone();
  17179. }
  17180. this.infiniteDistance = source.infiniteDistance;
  17181. this.setPivotMatrix(source.getPivotMatrix());
  17182. this.refreshBoundingInfo();
  17183. this._syncSubMeshes();
  17184. }
  17185. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17186. // Methods
  17187. get: function () {
  17188. return this._sourceMesh.receiveShadows;
  17189. },
  17190. enumerable: true,
  17191. configurable: true
  17192. });
  17193. Object.defineProperty(InstancedMesh.prototype, "material", {
  17194. get: function () {
  17195. return this._sourceMesh.material;
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17201. get: function () {
  17202. return this._sourceMesh.visibility;
  17203. },
  17204. enumerable: true,
  17205. configurable: true
  17206. });
  17207. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17208. get: function () {
  17209. return this._sourceMesh.skeleton;
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17215. get: function () {
  17216. return this._sourceMesh.renderingGroupId;
  17217. },
  17218. enumerable: true,
  17219. configurable: true
  17220. });
  17221. InstancedMesh.prototype.getTotalVertices = function () {
  17222. return this._sourceMesh.getTotalVertices();
  17223. };
  17224. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17225. get: function () {
  17226. return this._sourceMesh;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17232. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17233. };
  17234. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17235. return this._sourceMesh.isVerticesDataPresent(kind);
  17236. };
  17237. InstancedMesh.prototype.getIndices = function () {
  17238. return this._sourceMesh.getIndices();
  17239. };
  17240. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17241. get: function () {
  17242. return this._sourceMesh._positions;
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17248. var meshBB = this._sourceMesh.getBoundingInfo();
  17249. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17250. this._updateBoundingInfo();
  17251. };
  17252. InstancedMesh.prototype._preActivate = function () {
  17253. if (this._currentLOD) {
  17254. this._currentLOD._preActivate();
  17255. }
  17256. };
  17257. InstancedMesh.prototype._activate = function (renderId) {
  17258. if (this._currentLOD) {
  17259. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17260. }
  17261. };
  17262. InstancedMesh.prototype.getLOD = function (camera) {
  17263. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17264. if (this._currentLOD === this.sourceMesh) {
  17265. return this;
  17266. }
  17267. return this._currentLOD;
  17268. };
  17269. InstancedMesh.prototype._syncSubMeshes = function () {
  17270. this.releaseSubMeshes();
  17271. if (this._sourceMesh.subMeshes) {
  17272. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17273. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17274. }
  17275. }
  17276. };
  17277. InstancedMesh.prototype._generatePointsArray = function () {
  17278. return this._sourceMesh._generatePointsArray();
  17279. };
  17280. // Clone
  17281. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17282. var result = this._sourceMesh.createInstance(name);
  17283. // Deep copy
  17284. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17285. // Bounding info
  17286. this.refreshBoundingInfo();
  17287. // Parent
  17288. if (newParent) {
  17289. result.parent = newParent;
  17290. }
  17291. if (!doNotCloneChildren) {
  17292. // Children
  17293. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17294. var mesh = this.getScene().meshes[index];
  17295. if (mesh.parent === this) {
  17296. mesh.clone(mesh.name, result);
  17297. }
  17298. }
  17299. }
  17300. result.computeWorldMatrix(true);
  17301. return result;
  17302. };
  17303. // Dispoe
  17304. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17305. // Remove from mesh
  17306. var index = this._sourceMesh.instances.indexOf(this);
  17307. this._sourceMesh.instances.splice(index, 1);
  17308. _super.prototype.dispose.call(this, doNotRecurse);
  17309. };
  17310. return InstancedMesh;
  17311. })(BABYLON.AbstractMesh);
  17312. BABYLON.InstancedMesh = InstancedMesh;
  17313. })(BABYLON || (BABYLON = {}));
  17314. var BABYLON;
  17315. (function (BABYLON) {
  17316. var _InstancesBatch = (function () {
  17317. function _InstancesBatch() {
  17318. this.mustReturn = false;
  17319. this.visibleInstances = new Array();
  17320. this.renderSelf = new Array();
  17321. }
  17322. return _InstancesBatch;
  17323. })();
  17324. BABYLON._InstancesBatch = _InstancesBatch;
  17325. var Mesh = (function (_super) {
  17326. __extends(Mesh, _super);
  17327. /**
  17328. * @constructor
  17329. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17330. * @param {Scene} scene The scene to add this mesh to.
  17331. * @param {Node} parent The parent of this mesh, if it has one
  17332. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17333. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17334. * When false, achieved by calling a clone(), also passing False.
  17335. * This will make creation of children, recursive.
  17336. */
  17337. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17338. if (parent === void 0) { parent = null; }
  17339. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17340. _super.call(this, name, scene);
  17341. // Events
  17342. /**
  17343. * An event triggered before rendering the mesh
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onBeforeRenderObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered after rendering the mesh
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. this.onAfterRenderObservable = new BABYLON.Observable();
  17352. /**
  17353. * An event triggered before drawing the mesh
  17354. * @type {BABYLON.Observable}
  17355. */
  17356. this.onBeforeDrawObservable = new BABYLON.Observable();
  17357. // Members
  17358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17359. this.instances = new Array();
  17360. this._LODLevels = new Array();
  17361. this._visibleInstances = {};
  17362. this._renderIdForInstances = new Array();
  17363. this._batchCache = new _InstancesBatch();
  17364. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17365. this._sideOrientation = Mesh._DEFAULTSIDE;
  17366. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17367. if (source) {
  17368. // Geometry
  17369. if (source._geometry) {
  17370. source._geometry.applyToMesh(this);
  17371. }
  17372. // Deep copy
  17373. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17374. // Pivot
  17375. this.setPivotMatrix(source.getPivotMatrix());
  17376. this.id = name + "." + source.id;
  17377. // Material
  17378. this.material = source.material;
  17379. var index;
  17380. if (!doNotCloneChildren) {
  17381. // Children
  17382. for (index = 0; index < scene.meshes.length; index++) {
  17383. var mesh = scene.meshes[index];
  17384. if (mesh.parent === source) {
  17385. // doNotCloneChildren is always going to be False
  17386. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17387. }
  17388. }
  17389. }
  17390. // Physics clone
  17391. var physicsEngine = this.getScene().getPhysicsEngine();
  17392. if (clonePhysicsImpostor && physicsEngine) {
  17393. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17394. if (impostor) {
  17395. this.physicsImpostor = impostor.clone(this);
  17396. }
  17397. }
  17398. // Particles
  17399. for (index = 0; index < scene.particleSystems.length; index++) {
  17400. var system = scene.particleSystems[index];
  17401. if (system.emitter === source) {
  17402. system.clone(system.name, this);
  17403. }
  17404. }
  17405. this.computeWorldMatrix(true);
  17406. }
  17407. // Parent
  17408. if (parent !== null) {
  17409. this.parent = parent;
  17410. }
  17411. }
  17412. Object.defineProperty(Mesh, "FRONTSIDE", {
  17413. /**
  17414. * Mesh side orientation : usually the external or front surface
  17415. */
  17416. get: function () {
  17417. return Mesh._FRONTSIDE;
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Object.defineProperty(Mesh, "BACKSIDE", {
  17423. /**
  17424. * Mesh side orientation : usually the internal or back surface
  17425. */
  17426. get: function () {
  17427. return Mesh._BACKSIDE;
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17433. /**
  17434. * Mesh side orientation : both internal and external or front and back surfaces
  17435. */
  17436. get: function () {
  17437. return Mesh._DOUBLESIDE;
  17438. },
  17439. enumerable: true,
  17440. configurable: true
  17441. });
  17442. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17443. /**
  17444. * Mesh side orientation : by default, `FRONTSIDE`
  17445. */
  17446. get: function () {
  17447. return Mesh._DEFAULTSIDE;
  17448. },
  17449. enumerable: true,
  17450. configurable: true
  17451. });
  17452. Object.defineProperty(Mesh, "NO_CAP", {
  17453. /**
  17454. * Mesh cap setting : no cap
  17455. */
  17456. get: function () {
  17457. return Mesh._NO_CAP;
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. Object.defineProperty(Mesh, "CAP_START", {
  17463. /**
  17464. * Mesh cap setting : one cap at the beginning of the mesh
  17465. */
  17466. get: function () {
  17467. return Mesh._CAP_START;
  17468. },
  17469. enumerable: true,
  17470. configurable: true
  17471. });
  17472. Object.defineProperty(Mesh, "CAP_END", {
  17473. /**
  17474. * Mesh cap setting : one cap at the end of the mesh
  17475. */
  17476. get: function () {
  17477. return Mesh._CAP_END;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. Object.defineProperty(Mesh, "CAP_ALL", {
  17483. /**
  17484. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17485. */
  17486. get: function () {
  17487. return Mesh._CAP_ALL;
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17493. set: function (callback) {
  17494. if (this._onBeforeDrawObserver) {
  17495. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17496. }
  17497. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. // Methods
  17503. /**
  17504. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17505. */
  17506. Mesh.prototype.toString = function (fullDetails) {
  17507. var ret = _super.prototype.toString.call(this, fullDetails);
  17508. ret += ", n vertices: " + this.getTotalVertices();
  17509. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17510. if (this.animations) {
  17511. for (var i = 0; i < this.animations.length; i++) {
  17512. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17513. }
  17514. }
  17515. if (fullDetails) {
  17516. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17517. }
  17518. return ret;
  17519. };
  17520. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17521. get: function () {
  17522. return this._LODLevels.length > 0;
  17523. },
  17524. enumerable: true,
  17525. configurable: true
  17526. });
  17527. Mesh.prototype._sortLODLevels = function () {
  17528. this._LODLevels.sort(function (a, b) {
  17529. if (a.distance < b.distance) {
  17530. return 1;
  17531. }
  17532. if (a.distance > b.distance) {
  17533. return -1;
  17534. }
  17535. return 0;
  17536. });
  17537. };
  17538. /**
  17539. * Add a mesh as LOD level triggered at the given distance.
  17540. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17541. * @param {number} distance The distance from the center of the object to show this level
  17542. * @param {Mesh} mesh The mesh to be added as LOD level
  17543. * @return {Mesh} This mesh (for chaining)
  17544. */
  17545. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17546. if (mesh && mesh._masterMesh) {
  17547. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17548. return this;
  17549. }
  17550. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17551. this._LODLevels.push(level);
  17552. if (mesh) {
  17553. mesh._masterMesh = this;
  17554. }
  17555. this._sortLODLevels();
  17556. return this;
  17557. };
  17558. /**
  17559. * Returns the LOD level mesh at the passed distance or null if not found.
  17560. * It is related to the method `addLODLevel(distance, mesh)`.
  17561. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17562. */
  17563. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17564. for (var index = 0; index < this._LODLevels.length; index++) {
  17565. var level = this._LODLevels[index];
  17566. if (level.distance === distance) {
  17567. return level.mesh;
  17568. }
  17569. }
  17570. return null;
  17571. };
  17572. /**
  17573. * Remove a mesh from the LOD array
  17574. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17575. * @param {Mesh} mesh The mesh to be removed.
  17576. * @return {Mesh} This mesh (for chaining)
  17577. */
  17578. Mesh.prototype.removeLODLevel = function (mesh) {
  17579. for (var index = 0; index < this._LODLevels.length; index++) {
  17580. if (this._LODLevels[index].mesh === mesh) {
  17581. this._LODLevels.splice(index, 1);
  17582. if (mesh) {
  17583. mesh._masterMesh = null;
  17584. }
  17585. }
  17586. }
  17587. this._sortLODLevels();
  17588. return this;
  17589. };
  17590. /**
  17591. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17592. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17593. */
  17594. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17595. if (!this._LODLevels || this._LODLevels.length === 0) {
  17596. return this;
  17597. }
  17598. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17599. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17600. if (this.onLODLevelSelection) {
  17601. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17602. }
  17603. return this;
  17604. }
  17605. for (var index = 0; index < this._LODLevels.length; index++) {
  17606. var level = this._LODLevels[index];
  17607. if (level.distance < distanceToCamera) {
  17608. if (level.mesh) {
  17609. level.mesh._preActivate();
  17610. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17611. }
  17612. if (this.onLODLevelSelection) {
  17613. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17614. }
  17615. return level.mesh;
  17616. }
  17617. }
  17618. if (this.onLODLevelSelection) {
  17619. this.onLODLevelSelection(distanceToCamera, this, this);
  17620. }
  17621. return this;
  17622. };
  17623. Object.defineProperty(Mesh.prototype, "geometry", {
  17624. /**
  17625. * Returns the mesh internal Geometry object.
  17626. */
  17627. get: function () {
  17628. return this._geometry;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17635. */
  17636. Mesh.prototype.getTotalVertices = function () {
  17637. if (!this._geometry) {
  17638. return 0;
  17639. }
  17640. return this._geometry.getTotalVertices();
  17641. };
  17642. /**
  17643. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17644. * 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.
  17645. * Returns null if the mesh has no geometry or no vertex buffer.
  17646. * Possible `kind` values :
  17647. * - BABYLON.VertexBuffer.PositionKind
  17648. * - BABYLON.VertexBuffer.UVKind
  17649. * - BABYLON.VertexBuffer.UV2Kind
  17650. * - BABYLON.VertexBuffer.UV3Kind
  17651. * - BABYLON.VertexBuffer.UV4Kind
  17652. * - BABYLON.VertexBuffer.UV5Kind
  17653. * - BABYLON.VertexBuffer.UV6Kind
  17654. * - BABYLON.VertexBuffer.ColorKind
  17655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17659. */
  17660. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17661. if (!this._geometry) {
  17662. return null;
  17663. }
  17664. return this._geometry.getVerticesData(kind, copyWhenShared);
  17665. };
  17666. /**
  17667. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  17668. * Returns `undefined` if the mesh has no geometry.
  17669. * Possible `kind` values :
  17670. * - BABYLON.VertexBuffer.PositionKind
  17671. * - BABYLON.VertexBuffer.UVKind
  17672. * - BABYLON.VertexBuffer.UV2Kind
  17673. * - BABYLON.VertexBuffer.UV3Kind
  17674. * - BABYLON.VertexBuffer.UV4Kind
  17675. * - BABYLON.VertexBuffer.UV5Kind
  17676. * - BABYLON.VertexBuffer.UV6Kind
  17677. * - BABYLON.VertexBuffer.ColorKind
  17678. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17679. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17680. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17681. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17682. */
  17683. Mesh.prototype.getVertexBuffer = function (kind) {
  17684. if (!this._geometry) {
  17685. return undefined;
  17686. }
  17687. return this._geometry.getVertexBuffer(kind);
  17688. };
  17689. /**
  17690. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17691. * Possible `kind` values :
  17692. * - BABYLON.VertexBuffer.PositionKind
  17693. * - BABYLON.VertexBuffer.UVKind
  17694. * - BABYLON.VertexBuffer.UV2Kind
  17695. * - BABYLON.VertexBuffer.UV3Kind
  17696. * - BABYLON.VertexBuffer.UV4Kind
  17697. * - BABYLON.VertexBuffer.UV5Kind
  17698. * - BABYLON.VertexBuffer.UV6Kind
  17699. * - BABYLON.VertexBuffer.ColorKind
  17700. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17701. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17702. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17703. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17704. */
  17705. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17706. if (!this._geometry) {
  17707. if (this._delayInfo) {
  17708. return this._delayInfo.indexOf(kind) !== -1;
  17709. }
  17710. return false;
  17711. }
  17712. return this._geometry.isVerticesDataPresent(kind);
  17713. };
  17714. /**
  17715. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17716. * Possible `kind` values :
  17717. * - BABYLON.VertexBuffer.PositionKind
  17718. * - BABYLON.VertexBuffer.UVKind
  17719. * - BABYLON.VertexBuffer.UV2Kind
  17720. * - BABYLON.VertexBuffer.UV3Kind
  17721. * - BABYLON.VertexBuffer.UV4Kind
  17722. * - BABYLON.VertexBuffer.UV5Kind
  17723. * - BABYLON.VertexBuffer.UV6Kind
  17724. * - BABYLON.VertexBuffer.ColorKind
  17725. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17726. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17727. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17728. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17729. */
  17730. Mesh.prototype.getVerticesDataKinds = function () {
  17731. if (!this._geometry) {
  17732. var result = [];
  17733. if (this._delayInfo) {
  17734. for (var kind in this._delayInfo) {
  17735. result.push(kind);
  17736. }
  17737. }
  17738. return result;
  17739. }
  17740. return this._geometry.getVerticesDataKinds();
  17741. };
  17742. /**
  17743. * Returns a positive integer : the total number of indices in this mesh geometry.
  17744. * Returns zero if the mesh has no geometry.
  17745. */
  17746. Mesh.prototype.getTotalIndices = function () {
  17747. if (!this._geometry) {
  17748. return 0;
  17749. }
  17750. return this._geometry.getTotalIndices();
  17751. };
  17752. /**
  17753. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17754. * 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.
  17755. * Returns an empty array if the mesh has no geometry.
  17756. */
  17757. Mesh.prototype.getIndices = function (copyWhenShared) {
  17758. if (!this._geometry) {
  17759. return [];
  17760. }
  17761. return this._geometry.getIndices(copyWhenShared);
  17762. };
  17763. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17764. get: function () {
  17765. return this._masterMesh !== null && this._masterMesh !== undefined;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. /**
  17771. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17772. */
  17773. Mesh.prototype.isReady = function () {
  17774. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17775. return false;
  17776. }
  17777. return _super.prototype.isReady.call(this);
  17778. };
  17779. /**
  17780. * Boolean : true if the mesh has been disposed.
  17781. */
  17782. Mesh.prototype.isDisposed = function () {
  17783. return this._isDisposed;
  17784. };
  17785. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17786. get: function () {
  17787. return this._sideOrientation;
  17788. },
  17789. /**
  17790. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17791. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17792. */
  17793. set: function (sideO) {
  17794. this._sideOrientation = sideO;
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17800. /**
  17801. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17802. * This property is pertinent only for updatable parametric shapes.
  17803. */
  17804. get: function () {
  17805. return this._areNormalsFrozen;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. /**
  17811. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17812. * It has no effect at all on other shapes.
  17813. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17814. */
  17815. Mesh.prototype.freezeNormals = function () {
  17816. this._areNormalsFrozen = true;
  17817. };
  17818. /**
  17819. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17820. * It has no effect at all on other shapes.
  17821. * It reactivates the mesh normals computation if it was previously frozen.
  17822. */
  17823. Mesh.prototype.unfreezeNormals = function () {
  17824. this._areNormalsFrozen = false;
  17825. };
  17826. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  17827. /**
  17828. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  17829. */
  17830. set: function (count) {
  17831. this._overridenInstanceCount = count;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. // Methods
  17837. Mesh.prototype._preActivate = function () {
  17838. var sceneRenderId = this.getScene().getRenderId();
  17839. if (this._preActivateId === sceneRenderId) {
  17840. return;
  17841. }
  17842. this._preActivateId = sceneRenderId;
  17843. this._visibleInstances = null;
  17844. };
  17845. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17846. if (this._visibleInstances) {
  17847. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17848. }
  17849. };
  17850. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17851. if (!this._visibleInstances) {
  17852. this._visibleInstances = {};
  17853. this._visibleInstances.defaultRenderId = renderId;
  17854. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17855. }
  17856. if (!this._visibleInstances[renderId]) {
  17857. this._visibleInstances[renderId] = new Array();
  17858. }
  17859. this._visibleInstances[renderId].push(instance);
  17860. };
  17861. /**
  17862. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  17863. * This means the mesh underlying bounding box and sphere are recomputed.
  17864. */
  17865. Mesh.prototype.refreshBoundingInfo = function () {
  17866. if (this._boundingInfo.isLocked) {
  17867. return;
  17868. }
  17869. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17870. if (data) {
  17871. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17872. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17873. }
  17874. if (this.subMeshes) {
  17875. for (var index = 0; index < this.subMeshes.length; index++) {
  17876. this.subMeshes[index].refreshBoundingInfo();
  17877. }
  17878. }
  17879. this._updateBoundingInfo();
  17880. };
  17881. Mesh.prototype._createGlobalSubMesh = function () {
  17882. var totalVertices = this.getTotalVertices();
  17883. if (!totalVertices || !this.getIndices()) {
  17884. return null;
  17885. }
  17886. this.releaseSubMeshes();
  17887. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17888. };
  17889. Mesh.prototype.subdivide = function (count) {
  17890. if (count < 1) {
  17891. return;
  17892. }
  17893. var totalIndices = this.getTotalIndices();
  17894. var subdivisionSize = (totalIndices / count) | 0;
  17895. var offset = 0;
  17896. // Ensure that subdivisionSize is a multiple of 3
  17897. while (subdivisionSize % 3 !== 0) {
  17898. subdivisionSize++;
  17899. }
  17900. this.releaseSubMeshes();
  17901. for (var index = 0; index < count; index++) {
  17902. if (offset >= totalIndices) {
  17903. break;
  17904. }
  17905. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17906. offset += subdivisionSize;
  17907. }
  17908. this.synchronizeInstances();
  17909. };
  17910. /**
  17911. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17912. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17913. * The `data` are either a numeric array either a Float32Array.
  17914. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17915. * 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).
  17916. * Note that a new underlying VertexBuffer object is created each call.
  17917. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17918. *
  17919. * Possible `kind` values :
  17920. * - BABYLON.VertexBuffer.PositionKind
  17921. * - BABYLON.VertexBuffer.UVKind
  17922. * - BABYLON.VertexBuffer.UV2Kind
  17923. * - BABYLON.VertexBuffer.UV3Kind
  17924. * - BABYLON.VertexBuffer.UV4Kind
  17925. * - BABYLON.VertexBuffer.UV5Kind
  17926. * - BABYLON.VertexBuffer.UV6Kind
  17927. * - BABYLON.VertexBuffer.ColorKind
  17928. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17929. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17930. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17931. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17932. */
  17933. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17934. if (!this._geometry) {
  17935. var vertexData = new BABYLON.VertexData();
  17936. vertexData.set(data, kind);
  17937. var scene = this.getScene();
  17938. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17939. }
  17940. else {
  17941. this._geometry.setVerticesData(kind, data, updatable, stride);
  17942. }
  17943. };
  17944. Mesh.prototype.setVerticesBuffer = function (buffer) {
  17945. if (!this._geometry) {
  17946. var scene = this.getScene();
  17947. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  17948. }
  17949. this._geometry.setVerticesBuffer(buffer);
  17950. };
  17951. /**
  17952. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17953. * If the mesh has no geometry, it is simply returned as it is.
  17954. * The `data` are either a numeric array either a Float32Array.
  17955. * No new underlying VertexBuffer object is created.
  17956. * 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.
  17957. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17958. *
  17959. * Possible `kind` values :
  17960. * - BABYLON.VertexBuffer.PositionKind
  17961. * - BABYLON.VertexBuffer.UVKind
  17962. * - BABYLON.VertexBuffer.UV2Kind
  17963. * - BABYLON.VertexBuffer.UV3Kind
  17964. * - BABYLON.VertexBuffer.UV4Kind
  17965. * - BABYLON.VertexBuffer.UV5Kind
  17966. * - BABYLON.VertexBuffer.UV6Kind
  17967. * - BABYLON.VertexBuffer.ColorKind
  17968. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17969. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17970. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17971. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17972. */
  17973. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17974. if (!this._geometry) {
  17975. return;
  17976. }
  17977. if (!makeItUnique) {
  17978. this._geometry.updateVerticesData(kind, data, updateExtends);
  17979. }
  17980. else {
  17981. this.makeGeometryUnique();
  17982. this.updateVerticesData(kind, data, updateExtends, false);
  17983. }
  17984. };
  17985. /**
  17986. * Deprecated since BabylonJS v2.3
  17987. */
  17988. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17989. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17990. if (!this._geometry) {
  17991. return;
  17992. }
  17993. if (!makeItUnique) {
  17994. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17995. }
  17996. else {
  17997. this.makeGeometryUnique();
  17998. this.updateVerticesDataDirectly(kind, data, offset, false);
  17999. }
  18000. };
  18001. /**
  18002. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18003. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18004. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18005. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18006. */
  18007. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18008. if (computeNormals === void 0) { computeNormals = true; }
  18009. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18010. positionFunction(positions);
  18011. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18012. if (computeNormals) {
  18013. var indices = this.getIndices();
  18014. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18015. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18016. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18017. }
  18018. };
  18019. Mesh.prototype.makeGeometryUnique = function () {
  18020. if (!this._geometry) {
  18021. return;
  18022. }
  18023. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18024. geometry.applyToMesh(this);
  18025. };
  18026. /**
  18027. * Sets the mesh indices.
  18028. * Expects an array populated with integers or a Int32Array.
  18029. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  18030. * This method creates a new index buffer each call.
  18031. */
  18032. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18033. if (!this._geometry) {
  18034. var vertexData = new BABYLON.VertexData();
  18035. vertexData.indices = indices;
  18036. var scene = this.getScene();
  18037. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18038. }
  18039. else {
  18040. this._geometry.setIndices(indices, totalVertices);
  18041. }
  18042. };
  18043. /**
  18044. * Invert the geometry to move from a right handed system to a left handed one.
  18045. */
  18046. Mesh.prototype.toLeftHanded = function () {
  18047. if (!this._geometry) {
  18048. return;
  18049. }
  18050. this._geometry.toLeftHanded();
  18051. };
  18052. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18053. var engine = this.getScene().getEngine();
  18054. // Wireframe
  18055. var indexToBind;
  18056. if (this._unIndexed) {
  18057. indexToBind = null;
  18058. }
  18059. else {
  18060. switch (fillMode) {
  18061. case BABYLON.Material.PointFillMode:
  18062. indexToBind = null;
  18063. break;
  18064. case BABYLON.Material.WireFrameFillMode:
  18065. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18066. break;
  18067. default:
  18068. case BABYLON.Material.TriangleFillMode:
  18069. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18070. break;
  18071. }
  18072. }
  18073. // VBOs
  18074. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18075. };
  18076. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18077. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18078. return;
  18079. }
  18080. this.onBeforeDrawObservable.notifyObservers(this);
  18081. var engine = this.getScene().getEngine();
  18082. // Draw order
  18083. switch (fillMode) {
  18084. case BABYLON.Material.PointFillMode:
  18085. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18086. break;
  18087. case BABYLON.Material.WireFrameFillMode:
  18088. if (this._unIndexed) {
  18089. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18090. }
  18091. else {
  18092. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  18093. }
  18094. break;
  18095. default:
  18096. if (this._unIndexed) {
  18097. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18098. }
  18099. else {
  18100. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18101. }
  18102. }
  18103. };
  18104. /**
  18105. * Registers for this mesh a javascript function called just before the rendering process.
  18106. * This function is passed the current mesh and doesn't return anything.
  18107. */
  18108. Mesh.prototype.registerBeforeRender = function (func) {
  18109. this.onBeforeRenderObservable.add(func);
  18110. };
  18111. /**
  18112. * Disposes a previously registered javascript function called before the rendering.
  18113. * This function is passed the current mesh and doesn't return anything.
  18114. */
  18115. Mesh.prototype.unregisterBeforeRender = function (func) {
  18116. this.onBeforeRenderObservable.removeCallback(func);
  18117. };
  18118. /**
  18119. * Registers for this mesh a javascript function called just after the rendering is complete.
  18120. * This function is passed the current mesh and doesn't return anything.
  18121. */
  18122. Mesh.prototype.registerAfterRender = function (func) {
  18123. this.onAfterRenderObservable.add(func);
  18124. };
  18125. /**
  18126. * Disposes a previously registered javascript function called after the rendering.
  18127. * This function is passed the current mesh and doesn't return anything.
  18128. */
  18129. Mesh.prototype.unregisterAfterRender = function (func) {
  18130. this.onAfterRenderObservable.removeCallback(func);
  18131. };
  18132. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18133. var scene = this.getScene();
  18134. this._batchCache.mustReturn = false;
  18135. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18136. this._batchCache.visibleInstances[subMeshId] = null;
  18137. if (this._visibleInstances) {
  18138. var currentRenderId = scene.getRenderId();
  18139. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18140. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18141. var selfRenderId = this._renderId;
  18142. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18143. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18144. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18145. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18146. }
  18147. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18148. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18149. this._batchCache.mustReturn = true;
  18150. return this._batchCache;
  18151. }
  18152. if (currentRenderId !== selfRenderId) {
  18153. this._batchCache.renderSelf[subMeshId] = false;
  18154. }
  18155. }
  18156. this._renderIdForInstances[subMeshId] = currentRenderId;
  18157. }
  18158. return this._batchCache;
  18159. };
  18160. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18161. var visibleInstances = batch.visibleInstances[subMesh._id];
  18162. var matricesCount = visibleInstances.length + 1;
  18163. var bufferSize = matricesCount * 16 * 4;
  18164. var currentInstancesBufferSize = this._instancesBufferSize;
  18165. var instancesBuffer = this._instancesBuffer;
  18166. while (this._instancesBufferSize < bufferSize) {
  18167. this._instancesBufferSize *= 2;
  18168. }
  18169. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18170. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18171. }
  18172. var offset = 0;
  18173. var instancesCount = 0;
  18174. var world = this.getWorldMatrix();
  18175. if (batch.renderSelf[subMesh._id]) {
  18176. world.copyToArray(this._instancesData, offset);
  18177. offset += 16;
  18178. instancesCount++;
  18179. }
  18180. if (visibleInstances) {
  18181. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18182. var instance = visibleInstances[instanceIndex];
  18183. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18184. offset += 16;
  18185. instancesCount++;
  18186. }
  18187. }
  18188. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18189. if (instancesBuffer) {
  18190. instancesBuffer.dispose();
  18191. }
  18192. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18193. this._instancesBuffer = instancesBuffer;
  18194. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18195. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18196. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18197. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18198. }
  18199. else {
  18200. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18201. }
  18202. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18203. this._draw(subMesh, fillMode, instancesCount);
  18204. engine.unbindInstanceAttributes();
  18205. };
  18206. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  18207. var scene = this.getScene();
  18208. var engine = scene.getEngine();
  18209. if (hardwareInstancedRendering) {
  18210. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18211. }
  18212. else {
  18213. if (batch.renderSelf[subMesh._id]) {
  18214. // Draw
  18215. if (onBeforeDraw) {
  18216. onBeforeDraw(false, this.getWorldMatrix());
  18217. }
  18218. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18219. }
  18220. if (batch.visibleInstances[subMesh._id]) {
  18221. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18222. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18223. // World
  18224. var world = instance.getWorldMatrix();
  18225. if (onBeforeDraw) {
  18226. onBeforeDraw(true, world);
  18227. }
  18228. // Draw
  18229. this._draw(subMesh, fillMode);
  18230. }
  18231. }
  18232. }
  18233. };
  18234. /**
  18235. * Triggers the draw call for the mesh.
  18236. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18237. */
  18238. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18239. var scene = this.getScene();
  18240. // Managing instances
  18241. var batch = this._getInstancesRenderList(subMesh._id);
  18242. if (batch.mustReturn) {
  18243. return;
  18244. }
  18245. // Checking geometry state
  18246. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18247. return;
  18248. }
  18249. var callbackIndex;
  18250. this.onBeforeRenderObservable.notifyObservers(this);
  18251. var engine = scene.getEngine();
  18252. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18253. // Material
  18254. var effectiveMaterial = subMesh.getMaterial();
  18255. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18256. return;
  18257. }
  18258. // Outline - step 1
  18259. var savedDepthWrite = engine.getDepthWrite();
  18260. if (this.renderOutline) {
  18261. engine.setDepthWrite(false);
  18262. scene.getOutlineRenderer().render(subMesh, batch);
  18263. engine.setDepthWrite(savedDepthWrite);
  18264. }
  18265. effectiveMaterial._preBind();
  18266. var effect = effectiveMaterial.getEffect();
  18267. // Bind
  18268. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18269. this._bind(subMesh, effect, fillMode);
  18270. var world = this.getWorldMatrix();
  18271. effectiveMaterial.bind(world, this);
  18272. // Alpha mode
  18273. if (enableAlphaMode) {
  18274. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18275. }
  18276. // Draw
  18277. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  18278. if (isInstance) {
  18279. effectiveMaterial.bindOnlyWorldMatrix(world);
  18280. }
  18281. });
  18282. // Unbind
  18283. effectiveMaterial.unbind();
  18284. // Outline - step 2
  18285. if (this.renderOutline && savedDepthWrite) {
  18286. engine.setDepthWrite(true);
  18287. engine.setColorWrite(false);
  18288. scene.getOutlineRenderer().render(subMesh, batch);
  18289. engine.setColorWrite(true);
  18290. }
  18291. // Overlay
  18292. if (this.renderOverlay) {
  18293. var currentMode = engine.getAlphaMode();
  18294. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18295. scene.getOutlineRenderer().render(subMesh, batch, true);
  18296. engine.setAlphaMode(currentMode);
  18297. }
  18298. this.onAfterRenderObservable.notifyObservers(this);
  18299. };
  18300. /**
  18301. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18302. */
  18303. Mesh.prototype.getEmittedParticleSystems = function () {
  18304. var results = new Array();
  18305. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18306. var particleSystem = this.getScene().particleSystems[index];
  18307. if (particleSystem.emitter === this) {
  18308. results.push(particleSystem);
  18309. }
  18310. }
  18311. return results;
  18312. };
  18313. /**
  18314. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18315. */
  18316. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18317. var results = new Array();
  18318. var descendants = this.getDescendants();
  18319. descendants.push(this);
  18320. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18321. var particleSystem = this.getScene().particleSystems[index];
  18322. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18323. results.push(particleSystem);
  18324. }
  18325. }
  18326. return results;
  18327. };
  18328. Mesh.prototype._checkDelayState = function () {
  18329. var _this = this;
  18330. var that = this;
  18331. var scene = this.getScene();
  18332. if (this._geometry) {
  18333. this._geometry.load(scene);
  18334. }
  18335. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18336. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18337. scene._addPendingData(that);
  18338. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18339. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18340. if (data instanceof ArrayBuffer) {
  18341. _this._delayLoadingFunction(data, _this);
  18342. }
  18343. else {
  18344. _this._delayLoadingFunction(JSON.parse(data), _this);
  18345. }
  18346. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18347. scene._removePendingData(_this);
  18348. }, function () { }, scene.database, getBinaryData);
  18349. }
  18350. };
  18351. /**
  18352. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18353. */
  18354. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18355. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18356. return false;
  18357. }
  18358. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18359. return false;
  18360. }
  18361. this._checkDelayState();
  18362. return true;
  18363. };
  18364. /**
  18365. * Sets the mesh material by the material or multiMaterial `id` property.
  18366. * The material `id` is a string identifying the material or the multiMaterial.
  18367. * This method returns nothing.
  18368. */
  18369. Mesh.prototype.setMaterialByID = function (id) {
  18370. var materials = this.getScene().materials;
  18371. var index;
  18372. for (index = 0; index < materials.length; index++) {
  18373. if (materials[index].id === id) {
  18374. this.material = materials[index];
  18375. return;
  18376. }
  18377. }
  18378. // Multi
  18379. var multiMaterials = this.getScene().multiMaterials;
  18380. for (index = 0; index < multiMaterials.length; index++) {
  18381. if (multiMaterials[index].id === id) {
  18382. this.material = multiMaterials[index];
  18383. return;
  18384. }
  18385. }
  18386. };
  18387. /**
  18388. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18389. */
  18390. Mesh.prototype.getAnimatables = function () {
  18391. var results = [];
  18392. if (this.material) {
  18393. results.push(this.material);
  18394. }
  18395. if (this.skeleton) {
  18396. results.push(this.skeleton);
  18397. }
  18398. return results;
  18399. };
  18400. /**
  18401. * Modifies the mesh geometry according to the passed transformation matrix.
  18402. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18403. * The mesh normals are modified accordingly the same transformation.
  18404. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18405. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18406. */
  18407. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18408. // Position
  18409. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18410. return;
  18411. }
  18412. var submeshes = this.subMeshes.splice(0);
  18413. this._resetPointsArrayCache();
  18414. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18415. var temp = [];
  18416. var index;
  18417. for (index = 0; index < data.length; index += 3) {
  18418. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18419. }
  18420. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18421. // Normals
  18422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18423. return;
  18424. }
  18425. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18426. temp = [];
  18427. for (index = 0; index < data.length; index += 3) {
  18428. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18429. }
  18430. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18431. // flip faces?
  18432. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18433. this.flipFaces();
  18434. }
  18435. // Restore submeshes
  18436. this.releaseSubMeshes();
  18437. this.subMeshes = submeshes;
  18438. };
  18439. /**
  18440. * Modifies the mesh geometry according to its own current World Matrix.
  18441. * The mesh World Matrix is then reset.
  18442. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18443. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18444. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18445. */
  18446. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18447. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18448. this.scaling.copyFromFloats(1, 1, 1);
  18449. this.position.copyFromFloats(0, 0, 0);
  18450. this.rotation.copyFromFloats(0, 0, 0);
  18451. //only if quaternion is already set
  18452. if (this.rotationQuaternion) {
  18453. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18454. }
  18455. this._worldMatrix = BABYLON.Matrix.Identity();
  18456. };
  18457. // Cache
  18458. Mesh.prototype._resetPointsArrayCache = function () {
  18459. this._positions = null;
  18460. };
  18461. Mesh.prototype._generatePointsArray = function () {
  18462. if (this._positions)
  18463. return true;
  18464. this._positions = [];
  18465. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18466. if (!data) {
  18467. return false;
  18468. }
  18469. for (var index = 0; index < data.length; index += 3) {
  18470. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18471. }
  18472. return true;
  18473. };
  18474. /**
  18475. * Returns a new Mesh object generated from the current mesh properties.
  18476. * This method must not get confused with createInstance().
  18477. * The parameter `name` is a string, the name given to the new mesh.
  18478. * The optional parameter `newParent` can be any `Node` object (default `null`).
  18479. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18480. * 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.
  18481. */
  18482. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18483. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18484. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18485. };
  18486. /**
  18487. * Disposes the mesh.
  18488. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18489. */
  18490. Mesh.prototype.dispose = function (doNotRecurse) {
  18491. if (this._geometry) {
  18492. this._geometry.releaseForMesh(this, true);
  18493. }
  18494. // Instances
  18495. if (this._instancesBuffer) {
  18496. this._instancesBuffer.dispose();
  18497. this._instancesBuffer = null;
  18498. }
  18499. while (this.instances.length) {
  18500. this.instances[0].dispose();
  18501. }
  18502. _super.prototype.dispose.call(this, doNotRecurse);
  18503. };
  18504. /**
  18505. * Modifies the mesh geometry according to a displacement map.
  18506. * 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.
  18507. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18508. * This method returns nothing.
  18509. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18510. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18511. * 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.
  18512. */
  18513. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18514. var _this = this;
  18515. var scene = this.getScene();
  18516. var onload = function (img) {
  18517. // Getting height map data
  18518. var canvas = document.createElement("canvas");
  18519. var context = canvas.getContext("2d");
  18520. var heightMapWidth = img.width;
  18521. var heightMapHeight = img.height;
  18522. canvas.width = heightMapWidth;
  18523. canvas.height = heightMapHeight;
  18524. context.drawImage(img, 0, 0);
  18525. // Create VertexData from map data
  18526. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18527. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18528. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18529. //execute success callback, if set
  18530. if (onSuccess) {
  18531. onSuccess(_this);
  18532. }
  18533. };
  18534. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18535. };
  18536. /**
  18537. * Modifies the mesh geometry according to a displacementMap buffer.
  18538. * 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.
  18539. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18540. * This method returns nothing.
  18541. * 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.
  18542. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18543. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18544. */
  18545. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18547. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18548. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18549. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18550. return;
  18551. }
  18552. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18553. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18554. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18555. var position = BABYLON.Vector3.Zero();
  18556. var normal = BABYLON.Vector3.Zero();
  18557. var uv = BABYLON.Vector2.Zero();
  18558. for (var index = 0; index < positions.length; index += 3) {
  18559. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18560. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18561. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18562. // Compute height
  18563. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18564. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18565. var pos = (u + v * heightMapWidth) * 4;
  18566. var r = buffer[pos] / 255.0;
  18567. var g = buffer[pos + 1] / 255.0;
  18568. var b = buffer[pos + 2] / 255.0;
  18569. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18570. normal.normalize();
  18571. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18572. position = position.add(normal);
  18573. position.toArray(positions, index);
  18574. }
  18575. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18576. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18577. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18578. };
  18579. /**
  18580. * Modify the mesh to get a flat shading rendering.
  18581. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18582. * This method returns nothing.
  18583. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18584. */
  18585. Mesh.prototype.convertToFlatShadedMesh = function () {
  18586. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18587. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18588. var kinds = this.getVerticesDataKinds();
  18589. var vbs = [];
  18590. var data = [];
  18591. var newdata = [];
  18592. var updatableNormals = false;
  18593. var kindIndex;
  18594. var kind;
  18595. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18596. kind = kinds[kindIndex];
  18597. var vertexBuffer = this.getVertexBuffer(kind);
  18598. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18599. updatableNormals = vertexBuffer.isUpdatable();
  18600. kinds.splice(kindIndex, 1);
  18601. kindIndex--;
  18602. continue;
  18603. }
  18604. vbs[kind] = vertexBuffer;
  18605. data[kind] = vbs[kind].getData();
  18606. newdata[kind] = [];
  18607. }
  18608. // Save previous submeshes
  18609. var previousSubmeshes = this.subMeshes.slice(0);
  18610. var indices = this.getIndices();
  18611. var totalIndices = this.getTotalIndices();
  18612. // Generating unique vertices per face
  18613. var index;
  18614. for (index = 0; index < totalIndices; index++) {
  18615. var vertexIndex = indices[index];
  18616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18617. kind = kinds[kindIndex];
  18618. var stride = vbs[kind].getStrideSize();
  18619. for (var offset = 0; offset < stride; offset++) {
  18620. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18621. }
  18622. }
  18623. }
  18624. // Updating faces & normal
  18625. var normals = [];
  18626. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18627. for (index = 0; index < totalIndices; index += 3) {
  18628. indices[index] = index;
  18629. indices[index + 1] = index + 1;
  18630. indices[index + 2] = index + 2;
  18631. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18632. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18633. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18634. var p1p2 = p1.subtract(p2);
  18635. var p3p2 = p3.subtract(p2);
  18636. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18637. // Store same normals for every vertex
  18638. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18639. normals.push(normal.x);
  18640. normals.push(normal.y);
  18641. normals.push(normal.z);
  18642. }
  18643. }
  18644. this.setIndices(indices);
  18645. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18646. // Updating vertex buffers
  18647. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18648. kind = kinds[kindIndex];
  18649. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18650. }
  18651. // Updating submeshes
  18652. this.releaseSubMeshes();
  18653. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18654. var previousOne = previousSubmeshes[submeshIndex];
  18655. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18656. }
  18657. this.synchronizeInstances();
  18658. };
  18659. /**
  18660. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18661. * In other words, more vertices, no more indices and a single bigger VBO.
  18662. * This method returns nothing.
  18663. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18664. *
  18665. */
  18666. Mesh.prototype.convertToUnIndexedMesh = function () {
  18667. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18668. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18669. var kinds = this.getVerticesDataKinds();
  18670. var vbs = [];
  18671. var data = [];
  18672. var newdata = [];
  18673. var updatableNormals = false;
  18674. var kindIndex;
  18675. var kind;
  18676. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18677. kind = kinds[kindIndex];
  18678. var vertexBuffer = this.getVertexBuffer(kind);
  18679. vbs[kind] = vertexBuffer;
  18680. data[kind] = vbs[kind].getData();
  18681. newdata[kind] = [];
  18682. }
  18683. // Save previous submeshes
  18684. var previousSubmeshes = this.subMeshes.slice(0);
  18685. var indices = this.getIndices();
  18686. var totalIndices = this.getTotalIndices();
  18687. // Generating unique vertices per face
  18688. var index;
  18689. for (index = 0; index < totalIndices; index++) {
  18690. var vertexIndex = indices[index];
  18691. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18692. kind = kinds[kindIndex];
  18693. var stride = vbs[kind].getStrideSize();
  18694. for (var offset = 0; offset < stride; offset++) {
  18695. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18696. }
  18697. }
  18698. }
  18699. // Updating indices
  18700. for (index = 0; index < totalIndices; index += 3) {
  18701. indices[index] = index;
  18702. indices[index + 1] = index + 1;
  18703. indices[index + 2] = index + 2;
  18704. }
  18705. this.setIndices(indices);
  18706. // Updating vertex buffers
  18707. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18708. kind = kinds[kindIndex];
  18709. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18710. }
  18711. // Updating submeshes
  18712. this.releaseSubMeshes();
  18713. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18714. var previousOne = previousSubmeshes[submeshIndex];
  18715. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18716. }
  18717. this._unIndexed = true;
  18718. this.synchronizeInstances();
  18719. };
  18720. /**
  18721. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18722. * This method returns nothing.
  18723. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18724. */
  18725. Mesh.prototype.flipFaces = function (flipNormals) {
  18726. if (flipNormals === void 0) { flipNormals = false; }
  18727. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18728. var i;
  18729. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18730. for (i = 0; i < vertex_data.normals.length; i++) {
  18731. vertex_data.normals[i] *= -1;
  18732. }
  18733. }
  18734. var temp;
  18735. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18736. // reassign indices
  18737. temp = vertex_data.indices[i + 1];
  18738. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18739. vertex_data.indices[i + 2] = temp;
  18740. }
  18741. vertex_data.applyToMesh(this);
  18742. };
  18743. // Instances
  18744. /**
  18745. * Creates a new InstancedMesh object from the mesh model.
  18746. * An instance shares the same properties and the same material than its model.
  18747. * Only these properties of each instance can then be set individually :
  18748. * - position
  18749. * - rotation
  18750. * - rotationQuaternion
  18751. * - setPivotMatrix
  18752. * - scaling
  18753. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18754. * Warning : this method is not supported for Line mesh and LineSystem
  18755. */
  18756. Mesh.prototype.createInstance = function (name) {
  18757. return new BABYLON.InstancedMesh(name, this);
  18758. };
  18759. /**
  18760. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18761. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18762. * This method returns nothing.
  18763. */
  18764. Mesh.prototype.synchronizeInstances = function () {
  18765. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18766. var instance = this.instances[instanceIndex];
  18767. instance._syncSubMeshes();
  18768. }
  18769. };
  18770. /**
  18771. * Simplify the mesh according to the given array of settings.
  18772. * Function will return immediately and will simplify async. It returns nothing.
  18773. * @param settings a collection of simplification settings.
  18774. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18775. * @param type the type of simplification to run.
  18776. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18777. */
  18778. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18779. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18780. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18781. this.getScene().simplificationQueue.addTask({
  18782. settings: settings,
  18783. parallelProcessing: parallelProcessing,
  18784. mesh: this,
  18785. simplificationType: simplificationType,
  18786. successCallback: successCallback
  18787. });
  18788. };
  18789. /**
  18790. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18791. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18792. * This should be used together with the simplification to avoid disappearing triangles.
  18793. * @param successCallback an optional success callback to be called after the optimization finished.
  18794. */
  18795. Mesh.prototype.optimizeIndices = function (successCallback) {
  18796. var _this = this;
  18797. var indices = this.getIndices();
  18798. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18799. var vectorPositions = [];
  18800. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18801. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18802. }
  18803. var dupes = [];
  18804. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18805. var realPos = vectorPositions.length - 1 - iteration;
  18806. var testedPosition = vectorPositions[realPos];
  18807. for (var j = 0; j < realPos; ++j) {
  18808. var againstPosition = vectorPositions[j];
  18809. if (testedPosition.equals(againstPosition)) {
  18810. dupes[realPos] = j;
  18811. break;
  18812. }
  18813. }
  18814. }, function () {
  18815. for (var i = 0; i < indices.length; ++i) {
  18816. indices[i] = dupes[indices[i]] || indices[i];
  18817. }
  18818. //indices are now reordered
  18819. var originalSubMeshes = _this.subMeshes.slice(0);
  18820. _this.setIndices(indices);
  18821. _this.subMeshes = originalSubMeshes;
  18822. if (successCallback) {
  18823. successCallback(_this);
  18824. }
  18825. });
  18826. };
  18827. // Statics
  18828. /**
  18829. * Returns a new Mesh object what is a deep copy of the passed mesh.
  18830. * The parameter `parsedMesh` is the mesh to be copied.
  18831. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18832. */
  18833. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18834. var mesh = new Mesh(parsedMesh.name, scene);
  18835. mesh.id = parsedMesh.id;
  18836. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18837. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18838. if (parsedMesh.rotationQuaternion) {
  18839. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18840. }
  18841. else if (parsedMesh.rotation) {
  18842. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18843. }
  18844. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18845. if (parsedMesh.localMatrix) {
  18846. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18847. }
  18848. else if (parsedMesh.pivotMatrix) {
  18849. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18850. }
  18851. mesh.setEnabled(parsedMesh.isEnabled);
  18852. mesh.isVisible = parsedMesh.isVisible;
  18853. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18854. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18855. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18856. if (parsedMesh.applyFog !== undefined) {
  18857. mesh.applyFog = parsedMesh.applyFog;
  18858. }
  18859. if (parsedMesh.pickable !== undefined) {
  18860. mesh.isPickable = parsedMesh.pickable;
  18861. }
  18862. if (parsedMesh.alphaIndex !== undefined) {
  18863. mesh.alphaIndex = parsedMesh.alphaIndex;
  18864. }
  18865. mesh.receiveShadows = parsedMesh.receiveShadows;
  18866. mesh.billboardMode = parsedMesh.billboardMode;
  18867. if (parsedMesh.visibility !== undefined) {
  18868. mesh.visibility = parsedMesh.visibility;
  18869. }
  18870. mesh.checkCollisions = parsedMesh.checkCollisions;
  18871. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18872. // freezeWorldMatrix
  18873. if (parsedMesh.freezeWorldMatrix) {
  18874. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18875. }
  18876. // Parent
  18877. if (parsedMesh.parentId) {
  18878. mesh._waitingParentId = parsedMesh.parentId;
  18879. }
  18880. // Actions
  18881. if (parsedMesh.actions !== undefined) {
  18882. mesh._waitingActions = parsedMesh.actions;
  18883. }
  18884. // Geometry
  18885. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18886. if (parsedMesh.delayLoadingFile) {
  18887. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18888. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18889. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18890. if (parsedMesh._binaryInfo) {
  18891. mesh._binaryInfo = parsedMesh._binaryInfo;
  18892. }
  18893. mesh._delayInfo = [];
  18894. if (parsedMesh.hasUVs) {
  18895. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18896. }
  18897. if (parsedMesh.hasUVs2) {
  18898. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18899. }
  18900. if (parsedMesh.hasUVs3) {
  18901. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18902. }
  18903. if (parsedMesh.hasUVs4) {
  18904. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18905. }
  18906. if (parsedMesh.hasUVs5) {
  18907. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18908. }
  18909. if (parsedMesh.hasUVs6) {
  18910. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18911. }
  18912. if (parsedMesh.hasColors) {
  18913. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18914. }
  18915. if (parsedMesh.hasMatricesIndices) {
  18916. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18917. }
  18918. if (parsedMesh.hasMatricesWeights) {
  18919. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18920. }
  18921. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18922. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18923. mesh._checkDelayState();
  18924. }
  18925. }
  18926. else {
  18927. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18928. }
  18929. // Material
  18930. if (parsedMesh.materialId) {
  18931. mesh.setMaterialByID(parsedMesh.materialId);
  18932. }
  18933. else {
  18934. mesh.material = null;
  18935. }
  18936. // Skeleton
  18937. if (parsedMesh.skeletonId > -1) {
  18938. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18939. if (parsedMesh.numBoneInfluencers) {
  18940. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18941. }
  18942. }
  18943. // Animations
  18944. if (parsedMesh.animations) {
  18945. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18946. var parsedAnimation = parsedMesh.animations[animationIndex];
  18947. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18948. }
  18949. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18950. }
  18951. if (parsedMesh.autoAnimate) {
  18952. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18953. }
  18954. // Layer Mask
  18955. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18956. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18957. }
  18958. else {
  18959. mesh.layerMask = 0x0FFFFFFF;
  18960. }
  18961. //(Deprecated) physics
  18962. if (parsedMesh.physicsImpostor) {
  18963. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18964. mass: parsedMesh.physicsMass,
  18965. friction: parsedMesh.physicsFriction,
  18966. restitution: parsedMesh.physicsRestitution
  18967. }, scene);
  18968. }
  18969. // Instances
  18970. if (parsedMesh.instances) {
  18971. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18972. var parsedInstance = parsedMesh.instances[index];
  18973. var instance = mesh.createInstance(parsedInstance.name);
  18974. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18975. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18976. if (parsedInstance.rotationQuaternion) {
  18977. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18978. }
  18979. else if (parsedInstance.rotation) {
  18980. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18981. }
  18982. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18983. instance.checkCollisions = mesh.checkCollisions;
  18984. if (parsedMesh.animations) {
  18985. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18986. parsedAnimation = parsedMesh.animations[animationIndex];
  18987. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18988. }
  18989. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18990. }
  18991. }
  18992. }
  18993. return mesh;
  18994. };
  18995. /**
  18996. * Creates a ribbon mesh.
  18997. * Please consider using the same method from the MeshBuilder class instead.
  18998. * 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.
  18999. *
  19000. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19001. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19002. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19003. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19004. * 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.
  19005. * 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.
  19006. * 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
  19007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19010. */
  19011. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19012. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19013. pathArray: pathArray,
  19014. closeArray: closeArray,
  19015. closePath: closePath,
  19016. offset: offset,
  19017. updatable: updatable,
  19018. sideOrientation: sideOrientation,
  19019. instance: instance
  19020. }, scene);
  19021. };
  19022. /**
  19023. * Creates a plane polygonal mesh. By default, this is a disc.
  19024. * Please consider using the same method from the MeshBuilder class instead.
  19025. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19026. * 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.
  19027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19030. */
  19031. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19032. var options = {
  19033. radius: radius,
  19034. tessellation: tessellation,
  19035. sideOrientation: sideOrientation,
  19036. updatable: updatable
  19037. };
  19038. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19039. };
  19040. /**
  19041. * Creates a box mesh.
  19042. * Please consider using the same method from the MeshBuilder class instead.
  19043. * The parameter `size` sets the size (float) of each box side (default 1).
  19044. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19045. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19047. */
  19048. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19049. var options = {
  19050. size: size,
  19051. sideOrientation: sideOrientation,
  19052. updatable: updatable
  19053. };
  19054. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19055. };
  19056. /**
  19057. * Creates a sphere mesh.
  19058. * Please consider using the same method from the MeshBuilder class instead.
  19059. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19060. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19064. */
  19065. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19066. var options = {
  19067. segments: segments,
  19068. diameterX: diameter,
  19069. diameterY: diameter,
  19070. diameterZ: diameter,
  19071. sideOrientation: sideOrientation,
  19072. updatable: updatable
  19073. };
  19074. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19075. };
  19076. /**
  19077. * Creates a cylinder or a cone mesh.
  19078. * Please consider using the same method from the MeshBuilder class instead.
  19079. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19080. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19081. * 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.
  19082. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19083. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19085. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19087. */
  19088. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19089. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19090. if (scene !== undefined) {
  19091. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19092. updatable = scene;
  19093. }
  19094. scene = subdivisions;
  19095. subdivisions = 1;
  19096. }
  19097. var options = {
  19098. height: height,
  19099. diameterTop: diameterTop,
  19100. diameterBottom: diameterBottom,
  19101. tessellation: tessellation,
  19102. subdivisions: subdivisions,
  19103. sideOrientation: sideOrientation,
  19104. updatable: updatable
  19105. };
  19106. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19107. };
  19108. // Torus (Code from SharpDX.org)
  19109. /**
  19110. * Creates a torus mesh.
  19111. * Please consider using the same method from the MeshBuilder class instead.
  19112. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19113. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19114. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19118. */
  19119. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19120. var options = {
  19121. diameter: diameter,
  19122. thickness: thickness,
  19123. tessellation: tessellation,
  19124. sideOrientation: sideOrientation,
  19125. updatable: updatable
  19126. };
  19127. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19128. };
  19129. /**
  19130. * Creates a torus knot mesh.
  19131. * Please consider using the same method from the MeshBuilder class instead.
  19132. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19133. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19134. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19135. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19136. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19137. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19139. */
  19140. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19141. var options = {
  19142. radius: radius,
  19143. tube: tube,
  19144. radialSegments: radialSegments,
  19145. tubularSegments: tubularSegments,
  19146. p: p,
  19147. q: q,
  19148. sideOrientation: sideOrientation,
  19149. updatable: updatable
  19150. };
  19151. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19152. };
  19153. /**
  19154. * Creates a line mesh.
  19155. * Please consider using the same method from the MeshBuilder class instead.
  19156. * 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.
  19157. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19158. * The parameter `points` is an array successive Vector3.
  19159. * 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
  19160. * When updating an instance, remember that only point positions can change, not the number of points.
  19161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19162. */
  19163. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19164. var options = {
  19165. points: points,
  19166. updatable: updatable,
  19167. instance: instance
  19168. };
  19169. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19170. };
  19171. /**
  19172. * Creates a dashed line mesh.
  19173. * Please consider using the same method from the MeshBuilder class instead.
  19174. * 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.
  19175. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19176. * The parameter `points` is an array successive Vector3.
  19177. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19178. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19179. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19180. * 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
  19181. * When updating an instance, remember that only point positions can change, not the number of points.
  19182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19183. */
  19184. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19185. var options = {
  19186. points: points,
  19187. dashSize: dashSize,
  19188. gapSize: gapSize,
  19189. dashNb: dashNb,
  19190. updatable: updatable
  19191. };
  19192. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19193. };
  19194. /**
  19195. * Creates an extruded shape mesh.
  19196. * 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.
  19197. * Please consider using the same method from the MeshBuilder class instead.
  19198. *
  19199. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19200. * 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
  19201. * extruded along the Z axis.
  19202. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19203. * 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.
  19204. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19205. * 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
  19206. * 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
  19207. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19209. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19211. */
  19212. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19213. var options = {
  19214. shape: shape,
  19215. path: path,
  19216. scale: scale,
  19217. rotation: rotation,
  19218. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19219. sideOrientation: sideOrientation,
  19220. instance: instance,
  19221. updatable: updatable
  19222. };
  19223. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19224. };
  19225. /**
  19226. * Creates an custom extruded shape mesh.
  19227. * 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.
  19228. * Please consider using the same method from the MeshBuilder class instead.
  19229. *
  19230. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19231. * 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
  19232. * extruded along the Z axis.
  19233. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19234. * 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
  19235. * and the distance of this point from the begining of the path :
  19236. * ```javascript
  19237. * var rotationFunction = function(i, distance) {
  19238. * // do things
  19239. * return rotationValue; }
  19240. * ```
  19241. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19242. * 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
  19243. * and the distance of this point from the begining of the path :
  19244. * ```javascript
  19245. * var scaleFunction = function(i, distance) {
  19246. * // do things
  19247. * return scaleValue;}
  19248. * ```
  19249. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19250. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19251. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19252. * 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
  19253. * 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
  19254. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19258. */
  19259. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19260. var options = {
  19261. shape: shape,
  19262. path: path,
  19263. scaleFunction: scaleFunction,
  19264. rotationFunction: rotationFunction,
  19265. ribbonCloseArray: ribbonCloseArray,
  19266. ribbonClosePath: ribbonClosePath,
  19267. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19268. sideOrientation: sideOrientation,
  19269. instance: instance,
  19270. updatable: updatable
  19271. };
  19272. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19273. };
  19274. /**
  19275. * Creates lathe mesh.
  19276. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19277. * Please consider using the same method from the MeshBuilder class instead.
  19278. *
  19279. * 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
  19280. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19281. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19282. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19286. */
  19287. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19288. var options = {
  19289. shape: shape,
  19290. radius: radius,
  19291. tessellation: tessellation,
  19292. sideOrientation: sideOrientation,
  19293. updatable: updatable
  19294. };
  19295. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19296. };
  19297. /**
  19298. * Creates a plane mesh.
  19299. * Please consider using the same method from the MeshBuilder class instead.
  19300. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19304. */
  19305. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19306. var options = {
  19307. size: size,
  19308. width: size,
  19309. height: size,
  19310. sideOrientation: sideOrientation,
  19311. updatable: updatable
  19312. };
  19313. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19314. };
  19315. /**
  19316. * Creates a ground mesh.
  19317. * Please consider using the same method from the MeshBuilder class instead.
  19318. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19319. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19321. */
  19322. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19323. var options = {
  19324. width: width,
  19325. height: height,
  19326. subdivisions: subdivisions,
  19327. updatable: updatable
  19328. };
  19329. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19330. };
  19331. /**
  19332. * Creates a tiled ground mesh.
  19333. * Please consider using the same method from the MeshBuilder class instead.
  19334. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19335. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19336. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19337. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19338. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19339. * numbers of subdivisions on the ground width and height of each tile.
  19340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19341. */
  19342. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19343. var options = {
  19344. xmin: xmin,
  19345. zmin: zmin,
  19346. xmax: xmax,
  19347. zmax: zmax,
  19348. subdivisions: subdivisions,
  19349. precision: precision,
  19350. updatable: updatable
  19351. };
  19352. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19353. };
  19354. /**
  19355. * Creates a ground mesh from a height map.
  19356. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19357. * Please consider using the same method from the MeshBuilder class instead.
  19358. * The parameter `url` sets the URL of the height map image resource.
  19359. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19360. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19361. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19362. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19363. * 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).
  19364. * This function is passed the newly built mesh :
  19365. * ```javascript
  19366. * function(mesh) { // do things
  19367. * return; }
  19368. * ```
  19369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19370. */
  19371. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19372. var options = {
  19373. width: width,
  19374. height: height,
  19375. subdivisions: subdivisions,
  19376. minHeight: minHeight,
  19377. maxHeight: maxHeight,
  19378. updatable: updatable,
  19379. onReady: onReady
  19380. };
  19381. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19382. };
  19383. /**
  19384. * Creates a tube mesh.
  19385. * 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.
  19386. *
  19387. * Please consider using the same method from the MeshBuilder class instead.
  19388. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19389. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19390. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19391. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19392. * 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.
  19393. * It must return a radius value (positive float) :
  19394. * ```javascript
  19395. * var radiusFunction = function(i, distance) {
  19396. * // do things
  19397. * return radius; }
  19398. * ```
  19399. * 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
  19400. * 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
  19401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19404. */
  19405. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19406. var options = {
  19407. path: path,
  19408. radius: radius,
  19409. tessellation: tessellation,
  19410. radiusFunction: radiusFunction,
  19411. arc: 1,
  19412. cap: cap,
  19413. updatable: updatable,
  19414. sideOrientation: sideOrientation,
  19415. instance: instance
  19416. };
  19417. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19418. };
  19419. /**
  19420. * Creates a polyhedron mesh.
  19421. *
  19422. * Please consider using the same method from the MeshBuilder class instead.
  19423. * 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
  19424. * to choose the wanted type.
  19425. * The parameter `size` (positive float, default 1) sets the polygon size.
  19426. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19427. * 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`.
  19428. * 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
  19429. * 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)`).
  19430. * 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
  19431. * 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.
  19432. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19435. */
  19436. Mesh.CreatePolyhedron = function (name, options, scene) {
  19437. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19438. };
  19439. /**
  19440. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19441. * Please consider using the same method from the MeshBuilder class instead.
  19442. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19443. * 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`).
  19444. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19445. * 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.
  19446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19449. */
  19450. Mesh.CreateIcoSphere = function (name, options, scene) {
  19451. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19452. };
  19453. /**
  19454. * Creates a decal mesh.
  19455. * Please consider using the same method from the MeshBuilder class instead.
  19456. * 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.
  19457. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19458. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19459. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19460. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19461. */
  19462. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19463. var options = {
  19464. position: position,
  19465. normal: normal,
  19466. size: size,
  19467. angle: angle
  19468. };
  19469. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19470. };
  19471. // Skeletons
  19472. /**
  19473. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19474. */
  19475. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19476. var source;
  19477. if (!this._sourcePositions) {
  19478. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19479. this._sourcePositions = new Float32Array(source);
  19480. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19481. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19482. }
  19483. }
  19484. return this._sourcePositions;
  19485. };
  19486. /**
  19487. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19488. */
  19489. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19490. var source;
  19491. if (!this._sourceNormals) {
  19492. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19493. this._sourceNormals = new Float32Array(source);
  19494. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19495. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19496. }
  19497. }
  19498. return this._sourceNormals;
  19499. };
  19500. /**
  19501. * Update the vertex buffers by applying transformation from the bones
  19502. * @param {skeleton} skeleton to apply
  19503. */
  19504. Mesh.prototype.applySkeleton = function (skeleton) {
  19505. if (!this.geometry) {
  19506. return;
  19507. }
  19508. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19509. return;
  19510. }
  19511. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19513. return this;
  19514. }
  19515. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19516. return this;
  19517. }
  19518. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19519. return this;
  19520. }
  19521. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19522. return this;
  19523. }
  19524. if (!this._sourcePositions) {
  19525. this.setPositionsForCPUSkinning();
  19526. }
  19527. if (!this._sourceNormals) {
  19528. this.setNormalsForCPUSkinning();
  19529. }
  19530. // positionsData checks for not being Float32Array will only pass at most once
  19531. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19532. if (!(positionsData instanceof Float32Array)) {
  19533. positionsData = new Float32Array(positionsData);
  19534. }
  19535. // normalsData checks for not being Float32Array will only pass at most once
  19536. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19537. if (!(normalsData instanceof Float32Array)) {
  19538. normalsData = new Float32Array(normalsData);
  19539. }
  19540. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19541. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19542. var needExtras = this.numBoneInfluencers > 4;
  19543. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19544. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19545. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19546. var tempVector3 = BABYLON.Vector3.Zero();
  19547. var finalMatrix = new BABYLON.Matrix();
  19548. var tempMatrix = new BABYLON.Matrix();
  19549. var matWeightIdx = 0;
  19550. var inf;
  19551. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19552. var weight;
  19553. for (inf = 0; inf < 4; inf++) {
  19554. weight = matricesWeightsData[matWeightIdx + inf];
  19555. if (weight > 0) {
  19556. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19557. finalMatrix.addToSelf(tempMatrix);
  19558. }
  19559. else
  19560. break;
  19561. }
  19562. if (needExtras) {
  19563. for (inf = 0; inf < 4; inf++) {
  19564. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19565. if (weight > 0) {
  19566. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19567. finalMatrix.addToSelf(tempMatrix);
  19568. }
  19569. else
  19570. break;
  19571. }
  19572. }
  19573. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19574. tempVector3.toArray(positionsData, index);
  19575. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19576. tempVector3.toArray(normalsData, index);
  19577. finalMatrix.reset();
  19578. }
  19579. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19580. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19581. return this;
  19582. };
  19583. // Tools
  19584. /**
  19585. * Returns an object `{min: Vector3, max: Vector3}`
  19586. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19587. */
  19588. Mesh.MinMax = function (meshes) {
  19589. var minVector = null;
  19590. var maxVector = null;
  19591. for (var i in meshes) {
  19592. var mesh = meshes[i];
  19593. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19594. if (!minVector) {
  19595. minVector = boundingBox.minimumWorld;
  19596. maxVector = boundingBox.maximumWorld;
  19597. continue;
  19598. }
  19599. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19600. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19601. }
  19602. return {
  19603. min: minVector,
  19604. max: maxVector
  19605. };
  19606. };
  19607. /**
  19608. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19609. */
  19610. Mesh.Center = function (meshesOrMinMaxVector) {
  19611. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19612. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19613. };
  19614. /**
  19615. * Merge the array of meshes into a single mesh for performance reasons.
  19616. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19617. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19618. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19619. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19620. */
  19621. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19622. if (disposeSource === void 0) { disposeSource = true; }
  19623. var index;
  19624. if (!allow32BitsIndices) {
  19625. var totalVertices = 0;
  19626. // Counting vertices
  19627. for (index = 0; index < meshes.length; index++) {
  19628. if (meshes[index]) {
  19629. totalVertices += meshes[index].getTotalVertices();
  19630. if (totalVertices > 65536) {
  19631. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19632. return null;
  19633. }
  19634. }
  19635. }
  19636. }
  19637. // Merge
  19638. var vertexData;
  19639. var otherVertexData;
  19640. var source;
  19641. for (index = 0; index < meshes.length; index++) {
  19642. if (meshes[index]) {
  19643. meshes[index].computeWorldMatrix(true);
  19644. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19645. otherVertexData.transform(meshes[index].getWorldMatrix());
  19646. if (vertexData) {
  19647. vertexData.merge(otherVertexData);
  19648. }
  19649. else {
  19650. vertexData = otherVertexData;
  19651. source = meshes[index];
  19652. }
  19653. }
  19654. }
  19655. if (!meshSubclass) {
  19656. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19657. }
  19658. vertexData.applyToMesh(meshSubclass);
  19659. // Setting properties
  19660. meshSubclass.material = source.material;
  19661. meshSubclass.checkCollisions = source.checkCollisions;
  19662. // Cleaning
  19663. if (disposeSource) {
  19664. for (index = 0; index < meshes.length; index++) {
  19665. if (meshes[index]) {
  19666. meshes[index].dispose();
  19667. }
  19668. }
  19669. }
  19670. return meshSubclass;
  19671. };
  19672. // Consts
  19673. Mesh._FRONTSIDE = 0;
  19674. Mesh._BACKSIDE = 1;
  19675. Mesh._DOUBLESIDE = 2;
  19676. Mesh._DEFAULTSIDE = 0;
  19677. Mesh._NO_CAP = 0;
  19678. Mesh._CAP_START = 1;
  19679. Mesh._CAP_END = 2;
  19680. Mesh._CAP_ALL = 3;
  19681. return Mesh;
  19682. })(BABYLON.AbstractMesh);
  19683. BABYLON.Mesh = Mesh;
  19684. })(BABYLON || (BABYLON = {}));
  19685. var BABYLON;
  19686. (function (BABYLON) {
  19687. var SubMesh = (function () {
  19688. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19689. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19690. this.materialIndex = materialIndex;
  19691. this.verticesStart = verticesStart;
  19692. this.verticesCount = verticesCount;
  19693. this.indexStart = indexStart;
  19694. this.indexCount = indexCount;
  19695. this._renderId = 0;
  19696. this._mesh = mesh;
  19697. this._renderingMesh = renderingMesh || mesh;
  19698. mesh.subMeshes.push(this);
  19699. this._trianglePlanes = [];
  19700. this._id = mesh.subMeshes.length - 1;
  19701. if (createBoundingBox) {
  19702. this.refreshBoundingInfo();
  19703. mesh.computeWorldMatrix(true);
  19704. }
  19705. }
  19706. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19707. get: function () {
  19708. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. SubMesh.prototype.getBoundingInfo = function () {
  19714. if (this.IsGlobal) {
  19715. return this._mesh.getBoundingInfo();
  19716. }
  19717. return this._boundingInfo;
  19718. };
  19719. SubMesh.prototype.getMesh = function () {
  19720. return this._mesh;
  19721. };
  19722. SubMesh.prototype.getRenderingMesh = function () {
  19723. return this._renderingMesh;
  19724. };
  19725. SubMesh.prototype.getMaterial = function () {
  19726. var rootMaterial = this._renderingMesh.material;
  19727. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19728. var multiMaterial = rootMaterial;
  19729. return multiMaterial.getSubMaterial(this.materialIndex);
  19730. }
  19731. if (!rootMaterial) {
  19732. return this._mesh.getScene().defaultMaterial;
  19733. }
  19734. return rootMaterial;
  19735. };
  19736. // Methods
  19737. SubMesh.prototype.refreshBoundingInfo = function () {
  19738. this._lastColliderWorldVertices = null;
  19739. if (this.IsGlobal) {
  19740. return;
  19741. }
  19742. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19743. if (!data) {
  19744. this._boundingInfo = this._mesh._boundingInfo;
  19745. return;
  19746. }
  19747. var indices = this._renderingMesh.getIndices();
  19748. var extend;
  19749. //is this the only submesh?
  19750. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19751. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19752. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19753. }
  19754. else {
  19755. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19756. }
  19757. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19758. };
  19759. SubMesh.prototype._checkCollision = function (collider) {
  19760. return this.getBoundingInfo()._checkCollision(collider);
  19761. };
  19762. SubMesh.prototype.updateBoundingInfo = function (world) {
  19763. if (!this.getBoundingInfo()) {
  19764. this.refreshBoundingInfo();
  19765. }
  19766. this.getBoundingInfo().update(world);
  19767. };
  19768. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19769. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19770. };
  19771. SubMesh.prototype.render = function (enableAlphaMode) {
  19772. this._renderingMesh.render(this, enableAlphaMode);
  19773. };
  19774. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19775. if (!this._linesIndexBuffer) {
  19776. var linesIndices = [];
  19777. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19778. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19779. }
  19780. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19781. this.linesIndexCount = linesIndices.length;
  19782. }
  19783. return this._linesIndexBuffer;
  19784. };
  19785. SubMesh.prototype.canIntersects = function (ray) {
  19786. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19787. };
  19788. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19789. var intersectInfo = null;
  19790. // LineMesh first as it's also a Mesh...
  19791. if (this._mesh instanceof BABYLON.LinesMesh) {
  19792. var lineMesh = this._mesh;
  19793. // Line test
  19794. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19795. var p0 = positions[indices[index]];
  19796. var p1 = positions[indices[index + 1]];
  19797. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19798. if (length < 0) {
  19799. continue;
  19800. }
  19801. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19802. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19803. if (fastCheck) {
  19804. break;
  19805. }
  19806. }
  19807. }
  19808. }
  19809. else {
  19810. // Triangles test
  19811. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19812. var p0 = positions[indices[index]];
  19813. var p1 = positions[indices[index + 1]];
  19814. var p2 = positions[indices[index + 2]];
  19815. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19816. if (currentIntersectInfo) {
  19817. if (currentIntersectInfo.distance < 0) {
  19818. continue;
  19819. }
  19820. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19821. intersectInfo = currentIntersectInfo;
  19822. intersectInfo.faceId = index / 3;
  19823. if (fastCheck) {
  19824. break;
  19825. }
  19826. }
  19827. }
  19828. }
  19829. }
  19830. return intersectInfo;
  19831. };
  19832. // Clone
  19833. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19834. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19835. if (!this.IsGlobal) {
  19836. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19837. }
  19838. return result;
  19839. };
  19840. // Dispose
  19841. SubMesh.prototype.dispose = function () {
  19842. if (this._linesIndexBuffer) {
  19843. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19844. this._linesIndexBuffer = null;
  19845. }
  19846. // Remove from mesh
  19847. var index = this._mesh.subMeshes.indexOf(this);
  19848. this._mesh.subMeshes.splice(index, 1);
  19849. };
  19850. // Statics
  19851. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19852. var minVertexIndex = Number.MAX_VALUE;
  19853. var maxVertexIndex = -Number.MAX_VALUE;
  19854. renderingMesh = renderingMesh || mesh;
  19855. var indices = renderingMesh.getIndices();
  19856. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19857. var vertexIndex = indices[index];
  19858. if (vertexIndex < minVertexIndex)
  19859. minVertexIndex = vertexIndex;
  19860. if (vertexIndex > maxVertexIndex)
  19861. maxVertexIndex = vertexIndex;
  19862. }
  19863. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19864. };
  19865. return SubMesh;
  19866. })();
  19867. BABYLON.SubMesh = SubMesh;
  19868. })(BABYLON || (BABYLON = {}));
  19869. var BABYLON;
  19870. (function (BABYLON) {
  19871. var MeshBuilder = (function () {
  19872. function MeshBuilder() {
  19873. }
  19874. /**
  19875. * Creates a box mesh.
  19876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19877. * The parameter `size` sets the size (float) of each box side (default 1).
  19878. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19879. * 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).
  19880. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19884. */
  19885. MeshBuilder.CreateBox = function (name, options, scene) {
  19886. var box = new BABYLON.Mesh(name, scene);
  19887. var vertexData = BABYLON.VertexData.CreateBox(options);
  19888. vertexData.applyToMesh(box, options.updatable);
  19889. return box;
  19890. };
  19891. /**
  19892. * Creates a sphere mesh.
  19893. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19894. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19895. * 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`).
  19896. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19897. * 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
  19898. * 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).
  19899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19902. */
  19903. MeshBuilder.CreateSphere = function (name, options, scene) {
  19904. var sphere = new BABYLON.Mesh(name, scene);
  19905. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19906. vertexData.applyToMesh(sphere, options.updatable);
  19907. return sphere;
  19908. };
  19909. /**
  19910. * Creates a plane polygonal mesh. By default, this is a disc.
  19911. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19912. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19913. * 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.
  19914. * 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
  19915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19918. */
  19919. MeshBuilder.CreateDisc = function (name, options, scene) {
  19920. var disc = new BABYLON.Mesh(name, scene);
  19921. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19922. vertexData.applyToMesh(disc, options.updatable);
  19923. return disc;
  19924. };
  19925. /**
  19926. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19928. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19929. * 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`).
  19930. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19931. * 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.
  19932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19935. */
  19936. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19937. var sphere = new BABYLON.Mesh(name, scene);
  19938. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19939. vertexData.applyToMesh(sphere, options.updatable);
  19940. return sphere;
  19941. };
  19942. ;
  19943. /**
  19944. * Creates a ribbon mesh.
  19945. * 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.
  19946. *
  19947. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19948. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19949. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19950. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19951. * 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.
  19952. * 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.
  19953. * 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
  19954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19955. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19957. */
  19958. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19959. var pathArray = options.pathArray;
  19960. var closeArray = options.closeArray;
  19961. var closePath = options.closePath;
  19962. var offset = options.offset;
  19963. var sideOrientation = options.sideOrientation;
  19964. var instance = options.instance;
  19965. var updatable = options.updatable;
  19966. if (instance) {
  19967. // positionFunction : ribbon case
  19968. // only pathArray and sideOrientation parameters are taken into account for positions update
  19969. var positionFunction = function (positions) {
  19970. var minlg = pathArray[0].length;
  19971. var i = 0;
  19972. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19973. for (var si = 1; si <= ns; si++) {
  19974. for (var p = 0; p < pathArray.length; p++) {
  19975. var path = pathArray[p];
  19976. var l = path.length;
  19977. minlg = (minlg < l) ? minlg : l;
  19978. var j = 0;
  19979. while (j < minlg) {
  19980. positions[i] = path[j].x;
  19981. positions[i + 1] = path[j].y;
  19982. positions[i + 2] = path[j].z;
  19983. j++;
  19984. i += 3;
  19985. }
  19986. if (instance._closePath) {
  19987. positions[i] = path[0].x;
  19988. positions[i + 1] = path[0].y;
  19989. positions[i + 2] = path[0].z;
  19990. i += 3;
  19991. }
  19992. }
  19993. }
  19994. };
  19995. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19996. positionFunction(positions);
  19997. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19998. if (!(instance.areNormalsFrozen)) {
  19999. var indices = instance.getIndices();
  20000. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20001. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20002. if (instance._closePath) {
  20003. var indexFirst = 0;
  20004. var indexLast = 0;
  20005. for (var p = 0; p < pathArray.length; p++) {
  20006. indexFirst = instance._idx[p] * 3;
  20007. if (p + 1 < pathArray.length) {
  20008. indexLast = (instance._idx[p + 1] - 1) * 3;
  20009. }
  20010. else {
  20011. indexLast = normals.length - 3;
  20012. }
  20013. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20014. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20015. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20016. normals[indexLast] = normals[indexFirst];
  20017. normals[indexLast + 1] = normals[indexFirst + 1];
  20018. normals[indexLast + 2] = normals[indexFirst + 2];
  20019. }
  20020. }
  20021. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20022. }
  20023. return instance;
  20024. }
  20025. else {
  20026. var ribbon = new BABYLON.Mesh(name, scene);
  20027. ribbon.sideOrientation = sideOrientation;
  20028. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20029. if (closePath) {
  20030. ribbon._idx = vertexData._idx;
  20031. }
  20032. ribbon._closePath = closePath;
  20033. ribbon._closeArray = closeArray;
  20034. vertexData.applyToMesh(ribbon, updatable);
  20035. return ribbon;
  20036. }
  20037. };
  20038. /**
  20039. * Creates a cylinder or a cone mesh.
  20040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20041. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20042. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20043. * 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.
  20044. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20045. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20046. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20047. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20048. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20049. * 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).
  20050. * 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
  20051. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20052. * 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
  20053. * 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.
  20054. * If `enclose` is false, a ring surface is one element.
  20055. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20056. * 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
  20057. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20058. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20060. */
  20061. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20062. var cylinder = new BABYLON.Mesh(name, scene);
  20063. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20064. vertexData.applyToMesh(cylinder, options.updatable);
  20065. return cylinder;
  20066. };
  20067. /**
  20068. * Creates a torus mesh.
  20069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20070. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20071. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20072. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20076. */
  20077. MeshBuilder.CreateTorus = function (name, options, scene) {
  20078. var torus = new BABYLON.Mesh(name, scene);
  20079. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20080. vertexData.applyToMesh(torus, options.updatable);
  20081. return torus;
  20082. };
  20083. /**
  20084. * Creates a torus knot mesh.
  20085. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20086. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20087. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20088. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20089. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20090. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20091. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20093. */
  20094. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20095. var torusKnot = new BABYLON.Mesh(name, scene);
  20096. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20097. vertexData.applyToMesh(torusKnot, options.updatable);
  20098. return torusKnot;
  20099. };
  20100. /**
  20101. * Creates a line system mesh.
  20102. * A line system is a pool of many lines gathered in a single mesh.
  20103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20104. * 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.
  20105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20106. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20107. * 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
  20108. * 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
  20109. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20111. */
  20112. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20113. var instance = options.instance;
  20114. var lines = options.lines;
  20115. if (instance) {
  20116. var positionFunction = function (positions) {
  20117. var i = 0;
  20118. for (var l = 0; l < lines.length; l++) {
  20119. var points = lines[l];
  20120. for (var p = 0; p < points.length; p++) {
  20121. positions[i] = points[p].x;
  20122. positions[i + 1] = points[p].y;
  20123. positions[i + 2] = points[p].z;
  20124. i += 3;
  20125. }
  20126. }
  20127. };
  20128. instance.updateMeshPositions(positionFunction, false);
  20129. return instance;
  20130. }
  20131. // line system creation
  20132. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20133. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20134. vertexData.applyToMesh(lineSystem, options.updatable);
  20135. return lineSystem;
  20136. };
  20137. /**
  20138. * Creates a line mesh.
  20139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20140. * 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.
  20141. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20142. * The parameter `points` is an array successive Vector3.
  20143. * 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
  20144. * When updating an instance, remember that only point positions can change, not the number of points.
  20145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20146. */
  20147. MeshBuilder.CreateLines = function (name, options, scene) {
  20148. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20149. return lines;
  20150. };
  20151. /**
  20152. * Creates a dashed line mesh.
  20153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20154. * 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.
  20155. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20156. * The parameter `points` is an array successive Vector3.
  20157. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20158. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20159. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20160. * 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
  20161. * When updating an instance, remember that only point positions can change, not the number of points.
  20162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20163. */
  20164. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20165. var points = options.points;
  20166. var instance = options.instance;
  20167. var gapSize = options.gapSize;
  20168. var dashNb = options.dashNb;
  20169. var dashSize = options.dashSize;
  20170. if (instance) {
  20171. var positionFunction = function (positions) {
  20172. var curvect = BABYLON.Vector3.Zero();
  20173. var nbSeg = positions.length / 6;
  20174. var lg = 0;
  20175. var nb = 0;
  20176. var shft = 0;
  20177. var dashshft = 0;
  20178. var curshft = 0;
  20179. var p = 0;
  20180. var i = 0;
  20181. var j = 0;
  20182. for (i = 0; i < points.length - 1; i++) {
  20183. points[i + 1].subtractToRef(points[i], curvect);
  20184. lg += curvect.length();
  20185. }
  20186. shft = lg / nbSeg;
  20187. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20188. for (i = 0; i < points.length - 1; i++) {
  20189. points[i + 1].subtractToRef(points[i], curvect);
  20190. nb = Math.floor(curvect.length() / shft);
  20191. curvect.normalize();
  20192. j = 0;
  20193. while (j < nb && p < positions.length) {
  20194. curshft = shft * j;
  20195. positions[p] = points[i].x + curshft * curvect.x;
  20196. positions[p + 1] = points[i].y + curshft * curvect.y;
  20197. positions[p + 2] = points[i].z + curshft * curvect.z;
  20198. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20199. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20200. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20201. p += 6;
  20202. j++;
  20203. }
  20204. }
  20205. while (p < positions.length) {
  20206. positions[p] = points[i].x;
  20207. positions[p + 1] = points[i].y;
  20208. positions[p + 2] = points[i].z;
  20209. p += 3;
  20210. }
  20211. };
  20212. instance.updateMeshPositions(positionFunction, false);
  20213. return instance;
  20214. }
  20215. // dashed lines creation
  20216. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20217. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20218. vertexData.applyToMesh(dashedLines, options.updatable);
  20219. dashedLines.dashSize = dashSize;
  20220. dashedLines.gapSize = gapSize;
  20221. return dashedLines;
  20222. };
  20223. /**
  20224. * Creates an extruded shape mesh.
  20225. * 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.
  20226. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20227. *
  20228. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20229. * 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
  20230. * extruded along the Z axis.
  20231. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20232. * 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.
  20233. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20234. * 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
  20235. * 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
  20236. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20240. */
  20241. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20242. var path = options.path;
  20243. var shape = options.shape;
  20244. var scale = options.scale || 1;
  20245. var rotation = options.rotation || 0;
  20246. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20247. var updatable = options.updatable;
  20248. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20249. var instance = options.instance;
  20250. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  20251. };
  20252. /**
  20253. * Creates an custom extruded shape mesh.
  20254. * 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.
  20255. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20256. *
  20257. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20258. * 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
  20259. * extruded along the Z axis.
  20260. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20261. * 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
  20262. * and the distance of this point from the begining of the path :
  20263. * ```javascript
  20264. * var rotationFunction = function(i, distance) {
  20265. * // do things
  20266. * return rotationValue; }
  20267. * ```
  20268. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20269. * 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
  20270. * and the distance of this point from the begining of the path :
  20271. * ```javascript
  20272. * var scaleFunction = function(i, distance) {
  20273. * // do things
  20274. * return scaleValue;}
  20275. * ```
  20276. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20277. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20278. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20279. * 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
  20280. * 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
  20281. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.ExtrudeShapeCustom = function (name, options, scene) {
  20287. var path = options.path;
  20288. var shape = options.shape;
  20289. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20290. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20291. var ribbonCloseArray = options.ribbonCloseArray || false;
  20292. var ribbonClosePath = options.ribbonClosePath || false;
  20293. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20294. var updatable = options.updatable;
  20295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20296. var instance = options.instance;
  20297. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  20298. };
  20299. /**
  20300. * Creates lathe mesh.
  20301. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20303. *
  20304. * 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
  20305. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20306. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20307. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20308. * 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.
  20309. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20310. * 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
  20311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20314. */
  20315. MeshBuilder.CreateLathe = function (name, options, scene) {
  20316. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20317. var closed = (options.closed === undefined) ? true : options.closed;
  20318. var shape = options.shape;
  20319. var radius = options.radius || 1;
  20320. var tessellation = options.tessellation || 64;
  20321. var updatable = options.updatable;
  20322. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20323. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20324. var pi2 = Math.PI * 2;
  20325. var paths = new Array();
  20326. var i = 0;
  20327. var p = 0;
  20328. var step = pi2 / tessellation * arc;
  20329. var rotated;
  20330. var path = new Array();
  20331. ;
  20332. for (i = 0; i <= tessellation; i++) {
  20333. var path = [];
  20334. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20335. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20336. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20337. }
  20338. for (p = 0; p < shape.length; p++) {
  20339. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20340. path.push(rotated);
  20341. }
  20342. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20343. 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));
  20344. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20345. }
  20346. paths.push(path);
  20347. }
  20348. // lathe ribbon
  20349. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  20350. return lathe;
  20351. };
  20352. /**
  20353. * Creates a plane mesh.
  20354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20355. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20356. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20357. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20361. */
  20362. MeshBuilder.CreatePlane = function (name, options, scene) {
  20363. var plane = new BABYLON.Mesh(name, scene);
  20364. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20365. vertexData.applyToMesh(plane, options.updatable);
  20366. if (options.sourcePlane) {
  20367. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20368. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20369. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20370. plane.rotate(vectorProduct, product);
  20371. }
  20372. return plane;
  20373. };
  20374. /**
  20375. * Creates a ground mesh.
  20376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20377. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20378. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20380. */
  20381. MeshBuilder.CreateGround = function (name, options, scene) {
  20382. var ground = new BABYLON.GroundMesh(name, scene);
  20383. ground._setReady(false);
  20384. ground._subdivisions = options.subdivisions || 1;
  20385. ground._width = options.width || 1;
  20386. ground._height = options.height || 1;
  20387. ground._maxX = ground._width / 2;
  20388. ground._maxZ = ground._height / 2;
  20389. ground._minX = -ground._maxX;
  20390. ground._minZ = -ground._maxZ;
  20391. var vertexData = BABYLON.VertexData.CreateGround(options);
  20392. vertexData.applyToMesh(ground, options.updatable);
  20393. ground._setReady(true);
  20394. return ground;
  20395. };
  20396. /**
  20397. * Creates a tiled ground mesh.
  20398. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20399. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20400. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20401. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20402. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20403. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20404. * numbers of subdivisions on the ground width and height of each tile.
  20405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20406. */
  20407. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20408. var tiledGround = new BABYLON.Mesh(name, scene);
  20409. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20410. vertexData.applyToMesh(tiledGround, options.updatable);
  20411. return tiledGround;
  20412. };
  20413. /**
  20414. * Creates a ground mesh from a height map.
  20415. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20416. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20417. * The parameter `url` sets the URL of the height map image resource.
  20418. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20419. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20420. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20421. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20422. * 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).
  20423. * This function is passed the newly built mesh :
  20424. * ```javascript
  20425. * function(mesh) { // do things
  20426. * return; }
  20427. * ```
  20428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20429. */
  20430. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20431. var width = options.width || 10;
  20432. var height = options.height || 10;
  20433. var subdivisions = options.subdivisions || 1;
  20434. var minHeight = options.minHeight;
  20435. var maxHeight = options.maxHeight || 10;
  20436. var updatable = options.updatable;
  20437. var onReady = options.onReady;
  20438. var ground = new BABYLON.GroundMesh(name, scene);
  20439. ground._subdivisions = subdivisions;
  20440. ground._width = width;
  20441. ground._height = height;
  20442. ground._maxX = ground._width / 2;
  20443. ground._maxZ = ground._height / 2;
  20444. ground._minX = -ground._maxX;
  20445. ground._minZ = -ground._maxZ;
  20446. ground._setReady(false);
  20447. var onload = function (img) {
  20448. // Getting height map data
  20449. var canvas = document.createElement("canvas");
  20450. var context = canvas.getContext("2d");
  20451. var bufferWidth = img.width;
  20452. var bufferHeight = img.height;
  20453. canvas.width = bufferWidth;
  20454. canvas.height = bufferHeight;
  20455. context.drawImage(img, 0, 0);
  20456. // Create VertexData from map data
  20457. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20458. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20459. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20460. width: width, height: height,
  20461. subdivisions: subdivisions,
  20462. minHeight: minHeight, maxHeight: maxHeight,
  20463. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20464. });
  20465. vertexData.applyToMesh(ground, updatable);
  20466. ground._setReady(true);
  20467. //execute ready callback, if set
  20468. if (onReady) {
  20469. onReady(ground);
  20470. }
  20471. };
  20472. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20473. return ground;
  20474. };
  20475. /**
  20476. * Creates a tube mesh.
  20477. * 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.
  20478. *
  20479. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20480. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20481. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20482. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20483. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20484. * 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.
  20485. * It must return a radius value (positive float) :
  20486. * ```javascript
  20487. * var radiusFunction = function(i, distance) {
  20488. * // do things
  20489. * return radius; }
  20490. * ```
  20491. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20492. * 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
  20493. * 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
  20494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20497. */
  20498. MeshBuilder.CreateTube = function (name, options, scene) {
  20499. var path = options.path;
  20500. var radius = options.radius || 1;
  20501. var tessellation = options.tessellation || 64;
  20502. var radiusFunction = options.radiusFunction;
  20503. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20504. var updatable = options.updatable;
  20505. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20506. var instance = options.instance;
  20507. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  20508. // tube geometry
  20509. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20510. var tangents = path3D.getTangents();
  20511. var normals = path3D.getNormals();
  20512. var distances = path3D.getDistances();
  20513. var pi2 = Math.PI * 2;
  20514. var step = pi2 / tessellation * arc;
  20515. var returnRadius = function () { return radius; };
  20516. var radiusFunctionFinal = radiusFunction || returnRadius;
  20517. var circlePath;
  20518. var rad;
  20519. var normal;
  20520. var rotated;
  20521. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20522. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20523. for (var i = 0; i < path.length; i++) {
  20524. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20525. circlePath = Array(); // current circle array
  20526. normal = normals[i]; // current normal
  20527. for (var t = 0; t < tessellation; t++) {
  20528. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20529. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20530. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20531. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20532. circlePath[t] = rotated;
  20533. }
  20534. circlePaths[index] = circlePath;
  20535. index++;
  20536. }
  20537. // cap
  20538. var capPath = function (nbPoints, pathIndex) {
  20539. var pointCap = Array();
  20540. for (var i = 0; i < nbPoints; i++) {
  20541. pointCap.push(path[pathIndex]);
  20542. }
  20543. return pointCap;
  20544. };
  20545. switch (cap) {
  20546. case BABYLON.Mesh.NO_CAP:
  20547. break;
  20548. case BABYLON.Mesh.CAP_START:
  20549. circlePaths[0] = capPath(tessellation, 0);
  20550. circlePaths[1] = circlePaths[2].slice(0);
  20551. break;
  20552. case BABYLON.Mesh.CAP_END:
  20553. circlePaths[index] = circlePaths[index - 1].slice(0);
  20554. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20555. break;
  20556. case BABYLON.Mesh.CAP_ALL:
  20557. circlePaths[0] = capPath(tessellation, 0);
  20558. circlePaths[1] = circlePaths[2].slice(0);
  20559. circlePaths[index] = circlePaths[index - 1].slice(0);
  20560. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20561. break;
  20562. default:
  20563. break;
  20564. }
  20565. return circlePaths;
  20566. };
  20567. var path3D;
  20568. var pathArray;
  20569. if (instance) {
  20570. var arc = options.arc || instance.arc;
  20571. path3D = (instance.path3D).update(path);
  20572. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20573. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20574. instance.path3D = path3D;
  20575. instance.pathArray = pathArray;
  20576. instance.arc = arc;
  20577. return instance;
  20578. }
  20579. // tube creation
  20580. path3D = new BABYLON.Path3D(path);
  20581. var newPathArray = new Array();
  20582. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20583. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20584. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20585. tube.pathArray = pathArray;
  20586. tube.path3D = path3D;
  20587. tube.tessellation = tessellation;
  20588. tube.cap = cap;
  20589. tube.arc = options.arc;
  20590. return tube;
  20591. };
  20592. /**
  20593. * Creates a polyhedron mesh.
  20594. *
  20595. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20596. * 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
  20597. * to choose the wanted type.
  20598. * The parameter `size` (positive float, default 1) sets the polygon size.
  20599. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20600. * 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`.
  20601. * 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
  20602. * 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)`).
  20603. * 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
  20604. * 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.
  20605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20608. */
  20609. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20610. var polyhedron = new BABYLON.Mesh(name, scene);
  20611. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20612. vertexData.applyToMesh(polyhedron, options.updatable);
  20613. return polyhedron;
  20614. };
  20615. /**
  20616. * Creates a decal mesh.
  20617. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20618. * 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.
  20619. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20620. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20621. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20622. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20623. */
  20624. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20625. var indices = sourceMesh.getIndices();
  20626. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20627. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20628. var position = options.position || BABYLON.Vector3.Zero();
  20629. var normal = options.normal || BABYLON.Vector3.Up();
  20630. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20631. var angle = options.angle || 0;
  20632. // Getting correct rotation
  20633. if (!normal) {
  20634. var target = new BABYLON.Vector3(0, 0, 1);
  20635. var camera = sourceMesh.getScene().activeCamera;
  20636. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20637. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20638. }
  20639. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20640. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20641. var pitch = Math.atan2(normal.y, len);
  20642. // Matrix
  20643. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20644. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20645. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20646. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20647. var vertexData = new BABYLON.VertexData();
  20648. vertexData.indices = [];
  20649. vertexData.positions = [];
  20650. vertexData.normals = [];
  20651. vertexData.uvs = [];
  20652. var currentVertexDataIndex = 0;
  20653. var extractDecalVector3 = function (indexId) {
  20654. var vertexId = indices[indexId];
  20655. var result = new BABYLON.PositionNormalVertex();
  20656. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20657. // Send vector to decal local world
  20658. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20659. // Get normal
  20660. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20661. return result;
  20662. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20663. var clip = function (vertices, axis) {
  20664. if (vertices.length === 0) {
  20665. return vertices;
  20666. }
  20667. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20668. var clipVertices = function (v0, v1) {
  20669. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20670. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20671. };
  20672. var result = new Array();
  20673. for (var index = 0; index < vertices.length; index += 3) {
  20674. var v1Out;
  20675. var v2Out;
  20676. var v3Out;
  20677. var total = 0;
  20678. var nV1, nV2, nV3, nV4;
  20679. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20680. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20681. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20682. v1Out = d1 > 0;
  20683. v2Out = d2 > 0;
  20684. v3Out = d3 > 0;
  20685. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20686. switch (total) {
  20687. case 0:
  20688. result.push(vertices[index]);
  20689. result.push(vertices[index + 1]);
  20690. result.push(vertices[index + 2]);
  20691. break;
  20692. case 1:
  20693. if (v1Out) {
  20694. nV1 = vertices[index + 1];
  20695. nV2 = vertices[index + 2];
  20696. nV3 = clipVertices(vertices[index], nV1);
  20697. nV4 = clipVertices(vertices[index], nV2);
  20698. }
  20699. if (v2Out) {
  20700. nV1 = vertices[index];
  20701. nV2 = vertices[index + 2];
  20702. nV3 = clipVertices(vertices[index + 1], nV1);
  20703. nV4 = clipVertices(vertices[index + 1], nV2);
  20704. result.push(nV3);
  20705. result.push(nV2.clone());
  20706. result.push(nV1.clone());
  20707. result.push(nV2.clone());
  20708. result.push(nV3.clone());
  20709. result.push(nV4);
  20710. break;
  20711. }
  20712. if (v3Out) {
  20713. nV1 = vertices[index];
  20714. nV2 = vertices[index + 1];
  20715. nV3 = clipVertices(vertices[index + 2], nV1);
  20716. nV4 = clipVertices(vertices[index + 2], nV2);
  20717. }
  20718. result.push(nV1.clone());
  20719. result.push(nV2.clone());
  20720. result.push(nV3);
  20721. result.push(nV4);
  20722. result.push(nV3.clone());
  20723. result.push(nV2.clone());
  20724. break;
  20725. case 2:
  20726. if (!v1Out) {
  20727. nV1 = vertices[index].clone();
  20728. nV2 = clipVertices(nV1, vertices[index + 1]);
  20729. nV3 = clipVertices(nV1, vertices[index + 2]);
  20730. result.push(nV1);
  20731. result.push(nV2);
  20732. result.push(nV3);
  20733. }
  20734. if (!v2Out) {
  20735. nV1 = vertices[index + 1].clone();
  20736. nV2 = clipVertices(nV1, vertices[index + 2]);
  20737. nV3 = clipVertices(nV1, vertices[index]);
  20738. result.push(nV1);
  20739. result.push(nV2);
  20740. result.push(nV3);
  20741. }
  20742. if (!v3Out) {
  20743. nV1 = vertices[index + 2].clone();
  20744. nV2 = clipVertices(nV1, vertices[index]);
  20745. nV3 = clipVertices(nV1, vertices[index + 1]);
  20746. result.push(nV1);
  20747. result.push(nV2);
  20748. result.push(nV3);
  20749. }
  20750. break;
  20751. case 3:
  20752. break;
  20753. }
  20754. }
  20755. return result;
  20756. };
  20757. for (var index = 0; index < indices.length; index += 3) {
  20758. var faceVertices = new Array();
  20759. faceVertices.push(extractDecalVector3(index));
  20760. faceVertices.push(extractDecalVector3(index + 1));
  20761. faceVertices.push(extractDecalVector3(index + 2));
  20762. // Clip
  20763. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20764. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20765. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20766. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20767. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20768. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20769. if (faceVertices.length === 0) {
  20770. continue;
  20771. }
  20772. // Add UVs and get back to world
  20773. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20774. var vertex = faceVertices[vIndex];
  20775. //TODO check for Int32Array
  20776. vertexData.indices.push(currentVertexDataIndex);
  20777. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20778. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20779. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20780. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20781. currentVertexDataIndex++;
  20782. }
  20783. }
  20784. // Return mesh
  20785. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20786. vertexData.applyToMesh(decal);
  20787. decal.position = position.clone();
  20788. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20789. return decal;
  20790. };
  20791. // Privates
  20792. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20793. // extrusion geometry
  20794. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20795. var tangents = path3D.getTangents();
  20796. var normals = path3D.getNormals();
  20797. var binormals = path3D.getBinormals();
  20798. var distances = path3D.getDistances();
  20799. var angle = 0;
  20800. var returnScale = function () { return scale; };
  20801. var returnRotation = function () { return rotation; };
  20802. var rotate = custom ? rotateFunction : returnRotation;
  20803. var scl = custom ? scaleFunction : returnScale;
  20804. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20805. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20806. for (var i = 0; i < curve.length; i++) {
  20807. var shapePath = new Array();
  20808. var angleStep = rotate(i, distances[i]);
  20809. var scaleRatio = scl(i, distances[i]);
  20810. for (var p = 0; p < shape.length; p++) {
  20811. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20812. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20813. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20814. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20815. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20816. shapePath[p] = rotated;
  20817. }
  20818. shapePaths[index] = shapePath;
  20819. angle += angleStep;
  20820. index++;
  20821. }
  20822. // cap
  20823. var capPath = function (shapePath) {
  20824. var pointCap = Array();
  20825. var barycenter = BABYLON.Vector3.Zero();
  20826. var i;
  20827. for (i = 0; i < shapePath.length; i++) {
  20828. barycenter.addInPlace(shapePath[i]);
  20829. }
  20830. barycenter.scaleInPlace(1 / shapePath.length);
  20831. for (i = 0; i < shapePath.length; i++) {
  20832. pointCap.push(barycenter);
  20833. }
  20834. return pointCap;
  20835. };
  20836. switch (cap) {
  20837. case BABYLON.Mesh.NO_CAP:
  20838. break;
  20839. case BABYLON.Mesh.CAP_START:
  20840. shapePaths[0] = capPath(shapePaths[2]);
  20841. shapePaths[1] = shapePaths[2].slice(0);
  20842. break;
  20843. case BABYLON.Mesh.CAP_END:
  20844. shapePaths[index] = shapePaths[index - 1];
  20845. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20846. break;
  20847. case BABYLON.Mesh.CAP_ALL:
  20848. shapePaths[0] = capPath(shapePaths[2]);
  20849. shapePaths[1] = shapePaths[2].slice(0);
  20850. shapePaths[index] = shapePaths[index - 1];
  20851. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20852. break;
  20853. default:
  20854. break;
  20855. }
  20856. return shapePaths;
  20857. };
  20858. var path3D;
  20859. var pathArray;
  20860. if (instance) {
  20861. path3D = (instance.path3D).update(curve);
  20862. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20863. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20864. return instance;
  20865. }
  20866. // extruded shape creation
  20867. path3D = new BABYLON.Path3D(curve);
  20868. var newShapePaths = new Array();
  20869. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20870. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20871. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20872. extrudedGeneric.pathArray = pathArray;
  20873. extrudedGeneric.path3D = path3D;
  20874. extrudedGeneric.cap = cap;
  20875. return extrudedGeneric;
  20876. };
  20877. return MeshBuilder;
  20878. })();
  20879. BABYLON.MeshBuilder = MeshBuilder;
  20880. })(BABYLON || (BABYLON = {}));
  20881. var BABYLON;
  20882. (function (BABYLON) {
  20883. var BaseTexture = (function () {
  20884. function BaseTexture(scene) {
  20885. this.hasAlpha = false;
  20886. this.getAlphaFromRGB = false;
  20887. this.level = 1;
  20888. this.coordinatesIndex = 0;
  20889. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20890. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20891. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20892. this.anisotropicFilteringLevel = 4;
  20893. this.isCube = false;
  20894. this.isRenderTarget = false;
  20895. this.animations = new Array();
  20896. /**
  20897. * An event triggered when the texture is disposed.
  20898. * @type {BABYLON.Observable}
  20899. */
  20900. this.onDisposeObservable = new BABYLON.Observable();
  20901. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20902. this._scene = scene;
  20903. this._scene.textures.push(this);
  20904. }
  20905. BaseTexture.prototype.toString = function () {
  20906. return this.name;
  20907. };
  20908. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20909. set: function (callback) {
  20910. if (this._onDisposeObserver) {
  20911. this.onDisposeObservable.remove(this._onDisposeObserver);
  20912. }
  20913. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20914. },
  20915. enumerable: true,
  20916. configurable: true
  20917. });
  20918. BaseTexture.prototype.getScene = function () {
  20919. return this._scene;
  20920. };
  20921. BaseTexture.prototype.getTextureMatrix = function () {
  20922. return null;
  20923. };
  20924. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20925. return null;
  20926. };
  20927. BaseTexture.prototype.getInternalTexture = function () {
  20928. return this._texture;
  20929. };
  20930. BaseTexture.prototype.isReady = function () {
  20931. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20932. return true;
  20933. }
  20934. if (this._texture) {
  20935. return this._texture.isReady;
  20936. }
  20937. return false;
  20938. };
  20939. BaseTexture.prototype.getSize = function () {
  20940. if (this._texture._width) {
  20941. return { width: this._texture._width, height: this._texture._height };
  20942. }
  20943. if (this._texture._size) {
  20944. return { width: this._texture._size, height: this._texture._size };
  20945. }
  20946. return { width: 0, height: 0 };
  20947. };
  20948. BaseTexture.prototype.getBaseSize = function () {
  20949. if (!this.isReady() || !this._texture)
  20950. return { width: 0, height: 0 };
  20951. if (this._texture._size) {
  20952. return { width: this._texture._size, height: this._texture._size };
  20953. }
  20954. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20955. };
  20956. BaseTexture.prototype.scale = function (ratio) {
  20957. };
  20958. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20959. get: function () {
  20960. return false;
  20961. },
  20962. enumerable: true,
  20963. configurable: true
  20964. });
  20965. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20966. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20967. for (var index = 0; index < texturesCache.length; index++) {
  20968. var texturesCacheEntry = texturesCache[index];
  20969. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20970. texturesCache.splice(index, 1);
  20971. return;
  20972. }
  20973. }
  20974. };
  20975. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20976. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20977. for (var index = 0; index < texturesCache.length; index++) {
  20978. var texturesCacheEntry = texturesCache[index];
  20979. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20980. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20981. texturesCacheEntry.references++;
  20982. return texturesCacheEntry;
  20983. }
  20984. }
  20985. }
  20986. return null;
  20987. };
  20988. BaseTexture.prototype.delayLoad = function () {
  20989. };
  20990. BaseTexture.prototype.clone = function () {
  20991. return null;
  20992. };
  20993. BaseTexture.prototype.releaseInternalTexture = function () {
  20994. if (this._texture) {
  20995. this._scene.getEngine().releaseInternalTexture(this._texture);
  20996. delete this._texture;
  20997. }
  20998. };
  20999. BaseTexture.prototype.dispose = function () {
  21000. // Animations
  21001. this.getScene().stopAnimation(this);
  21002. // Remove from scene
  21003. var index = this._scene.textures.indexOf(this);
  21004. if (index >= 0) {
  21005. this._scene.textures.splice(index, 1);
  21006. }
  21007. if (this._texture === undefined) {
  21008. return;
  21009. }
  21010. // Release
  21011. this.releaseInternalTexture();
  21012. // Callback
  21013. this.onDisposeObservable.notifyObservers(this);
  21014. this.onDisposeObservable.clear();
  21015. };
  21016. BaseTexture.prototype.serialize = function () {
  21017. if (!this.name) {
  21018. return null;
  21019. }
  21020. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21021. // Animations
  21022. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21023. return serializationObject;
  21024. };
  21025. __decorate([
  21026. BABYLON.serialize()
  21027. ], BaseTexture.prototype, "name", void 0);
  21028. __decorate([
  21029. BABYLON.serialize()
  21030. ], BaseTexture.prototype, "hasAlpha", void 0);
  21031. __decorate([
  21032. BABYLON.serialize()
  21033. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21034. __decorate([
  21035. BABYLON.serialize()
  21036. ], BaseTexture.prototype, "level", void 0);
  21037. __decorate([
  21038. BABYLON.serialize()
  21039. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21040. __decorate([
  21041. BABYLON.serialize()
  21042. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21043. __decorate([
  21044. BABYLON.serialize()
  21045. ], BaseTexture.prototype, "wrapU", void 0);
  21046. __decorate([
  21047. BABYLON.serialize()
  21048. ], BaseTexture.prototype, "wrapV", void 0);
  21049. __decorate([
  21050. BABYLON.serialize()
  21051. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21052. __decorate([
  21053. BABYLON.serialize()
  21054. ], BaseTexture.prototype, "isCube", void 0);
  21055. __decorate([
  21056. BABYLON.serialize()
  21057. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21058. return BaseTexture;
  21059. })();
  21060. BABYLON.BaseTexture = BaseTexture;
  21061. })(BABYLON || (BABYLON = {}));
  21062. var BABYLON;
  21063. (function (BABYLON) {
  21064. var Texture = (function (_super) {
  21065. __extends(Texture, _super);
  21066. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21067. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21068. if (onLoad === void 0) { onLoad = null; }
  21069. if (onError === void 0) { onError = null; }
  21070. if (buffer === void 0) { buffer = null; }
  21071. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21072. _super.call(this, scene);
  21073. this.uOffset = 0;
  21074. this.vOffset = 0;
  21075. this.uScale = 1.0;
  21076. this.vScale = 1.0;
  21077. this.uAng = 0;
  21078. this.vAng = 0;
  21079. this.wAng = 0;
  21080. this.name = url;
  21081. this.url = url;
  21082. this._noMipmap = noMipmap;
  21083. this._invertY = invertY;
  21084. this._samplingMode = samplingMode;
  21085. this._buffer = buffer;
  21086. this._deleteBuffer = deleteBuffer;
  21087. if (!url) {
  21088. return;
  21089. }
  21090. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21091. if (!this._texture) {
  21092. if (!scene.useDelayedTextureLoading) {
  21093. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  21094. if (deleteBuffer) {
  21095. delete this._buffer;
  21096. }
  21097. }
  21098. else {
  21099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21100. this._delayedOnLoad = onLoad;
  21101. this._delayedOnError = onError;
  21102. }
  21103. }
  21104. else {
  21105. BABYLON.Tools.SetImmediate(function () {
  21106. if (onLoad) {
  21107. onLoad();
  21108. }
  21109. });
  21110. }
  21111. }
  21112. Object.defineProperty(Texture.prototype, "noMipmap", {
  21113. get: function () {
  21114. return this._noMipmap;
  21115. },
  21116. enumerable: true,
  21117. configurable: true
  21118. });
  21119. Texture.prototype.delayLoad = function () {
  21120. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21121. return;
  21122. }
  21123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21124. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21125. if (!this._texture) {
  21126. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21127. if (this._deleteBuffer) {
  21128. delete this._buffer;
  21129. }
  21130. }
  21131. };
  21132. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21133. if (!this._texture) {
  21134. return;
  21135. }
  21136. this._samplingMode = samplingMode;
  21137. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21138. };
  21139. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21140. x *= this.uScale;
  21141. y *= this.vScale;
  21142. x -= 0.5 * this.uScale;
  21143. y -= 0.5 * this.vScale;
  21144. z -= 0.5;
  21145. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21146. t.x += 0.5 * this.uScale + this.uOffset;
  21147. t.y += 0.5 * this.vScale + this.vOffset;
  21148. t.z += 0.5;
  21149. };
  21150. Texture.prototype.getTextureMatrix = function () {
  21151. if (this.uOffset === this._cachedUOffset &&
  21152. this.vOffset === this._cachedVOffset &&
  21153. this.uScale === this._cachedUScale &&
  21154. this.vScale === this._cachedVScale &&
  21155. this.uAng === this._cachedUAng &&
  21156. this.vAng === this._cachedVAng &&
  21157. this.wAng === this._cachedWAng) {
  21158. return this._cachedTextureMatrix;
  21159. }
  21160. this._cachedUOffset = this.uOffset;
  21161. this._cachedVOffset = this.vOffset;
  21162. this._cachedUScale = this.uScale;
  21163. this._cachedVScale = this.vScale;
  21164. this._cachedUAng = this.uAng;
  21165. this._cachedVAng = this.vAng;
  21166. this._cachedWAng = this.wAng;
  21167. if (!this._cachedTextureMatrix) {
  21168. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21169. this._rowGenerationMatrix = new BABYLON.Matrix();
  21170. this._t0 = BABYLON.Vector3.Zero();
  21171. this._t1 = BABYLON.Vector3.Zero();
  21172. this._t2 = BABYLON.Vector3.Zero();
  21173. }
  21174. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21175. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21176. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21177. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21178. this._t1.subtractInPlace(this._t0);
  21179. this._t2.subtractInPlace(this._t0);
  21180. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21181. this._cachedTextureMatrix.m[0] = this._t1.x;
  21182. this._cachedTextureMatrix.m[1] = this._t1.y;
  21183. this._cachedTextureMatrix.m[2] = this._t1.z;
  21184. this._cachedTextureMatrix.m[4] = this._t2.x;
  21185. this._cachedTextureMatrix.m[5] = this._t2.y;
  21186. this._cachedTextureMatrix.m[6] = this._t2.z;
  21187. this._cachedTextureMatrix.m[8] = this._t0.x;
  21188. this._cachedTextureMatrix.m[9] = this._t0.y;
  21189. this._cachedTextureMatrix.m[10] = this._t0.z;
  21190. return this._cachedTextureMatrix;
  21191. };
  21192. Texture.prototype.getReflectionTextureMatrix = function () {
  21193. if (this.uOffset === this._cachedUOffset &&
  21194. this.vOffset === this._cachedVOffset &&
  21195. this.uScale === this._cachedUScale &&
  21196. this.vScale === this._cachedVScale &&
  21197. this.coordinatesMode === this._cachedCoordinatesMode) {
  21198. return this._cachedTextureMatrix;
  21199. }
  21200. if (!this._cachedTextureMatrix) {
  21201. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21202. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21203. }
  21204. this._cachedCoordinatesMode = this.coordinatesMode;
  21205. switch (this.coordinatesMode) {
  21206. case Texture.PLANAR_MODE:
  21207. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21208. this._cachedTextureMatrix[0] = this.uScale;
  21209. this._cachedTextureMatrix[5] = this.vScale;
  21210. this._cachedTextureMatrix[12] = this.uOffset;
  21211. this._cachedTextureMatrix[13] = this.vOffset;
  21212. break;
  21213. case Texture.PROJECTION_MODE:
  21214. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21215. this._projectionModeMatrix.m[0] = 0.5;
  21216. this._projectionModeMatrix.m[5] = -0.5;
  21217. this._projectionModeMatrix.m[10] = 0.0;
  21218. this._projectionModeMatrix.m[12] = 0.5;
  21219. this._projectionModeMatrix.m[13] = 0.5;
  21220. this._projectionModeMatrix.m[14] = 1.0;
  21221. this._projectionModeMatrix.m[15] = 1.0;
  21222. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21223. break;
  21224. default:
  21225. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21226. break;
  21227. }
  21228. return this._cachedTextureMatrix;
  21229. };
  21230. Texture.prototype.clone = function () {
  21231. var _this = this;
  21232. return BABYLON.SerializationHelper.Clone(function () {
  21233. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21234. }, this);
  21235. };
  21236. // Statics
  21237. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21238. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21239. if (onLoad === void 0) { onLoad = null; }
  21240. if (onError === void 0) { onError = null; }
  21241. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21242. };
  21243. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21244. if (parsedTexture.isCube) {
  21245. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21246. }
  21247. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21248. return null;
  21249. }
  21250. var texture = BABYLON.SerializationHelper.Parse(function () {
  21251. if (parsedTexture.mirrorPlane) {
  21252. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21253. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21254. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21255. return mirrorTexture;
  21256. }
  21257. else if (parsedTexture.isRenderTarget) {
  21258. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21259. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21260. return renderTargetTexture;
  21261. }
  21262. else {
  21263. var texture;
  21264. if (parsedTexture.base64String) {
  21265. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21266. }
  21267. else {
  21268. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21269. }
  21270. return texture;
  21271. }
  21272. }, parsedTexture, scene);
  21273. // Animations
  21274. if (parsedTexture.animations) {
  21275. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21276. var parsedAnimation = parsedTexture.animations[animationIndex];
  21277. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21278. }
  21279. }
  21280. return texture;
  21281. };
  21282. // Constants
  21283. Texture.NEAREST_SAMPLINGMODE = 1;
  21284. Texture.BILINEAR_SAMPLINGMODE = 2;
  21285. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21286. Texture.EXPLICIT_MODE = 0;
  21287. Texture.SPHERICAL_MODE = 1;
  21288. Texture.PLANAR_MODE = 2;
  21289. Texture.CUBIC_MODE = 3;
  21290. Texture.PROJECTION_MODE = 4;
  21291. Texture.SKYBOX_MODE = 5;
  21292. Texture.INVCUBIC_MODE = 6;
  21293. Texture.EQUIRECTANGULAR_MODE = 7;
  21294. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21295. Texture.CLAMP_ADDRESSMODE = 0;
  21296. Texture.WRAP_ADDRESSMODE = 1;
  21297. Texture.MIRROR_ADDRESSMODE = 2;
  21298. __decorate([
  21299. BABYLON.serialize()
  21300. ], Texture.prototype, "url", void 0);
  21301. __decorate([
  21302. BABYLON.serialize()
  21303. ], Texture.prototype, "uOffset", void 0);
  21304. __decorate([
  21305. BABYLON.serialize()
  21306. ], Texture.prototype, "vOffset", void 0);
  21307. __decorate([
  21308. BABYLON.serialize()
  21309. ], Texture.prototype, "uScale", void 0);
  21310. __decorate([
  21311. BABYLON.serialize()
  21312. ], Texture.prototype, "vScale", void 0);
  21313. __decorate([
  21314. BABYLON.serialize()
  21315. ], Texture.prototype, "uAng", void 0);
  21316. __decorate([
  21317. BABYLON.serialize()
  21318. ], Texture.prototype, "vAng", void 0);
  21319. __decorate([
  21320. BABYLON.serialize()
  21321. ], Texture.prototype, "wAng", void 0);
  21322. return Texture;
  21323. })(BABYLON.BaseTexture);
  21324. BABYLON.Texture = Texture;
  21325. })(BABYLON || (BABYLON = {}));
  21326. var BABYLON;
  21327. (function (BABYLON) {
  21328. var CubeTexture = (function (_super) {
  21329. __extends(CubeTexture, _super);
  21330. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21331. _super.call(this, scene);
  21332. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21333. this.name = rootUrl;
  21334. this.url = rootUrl;
  21335. this._noMipmap = noMipmap;
  21336. this.hasAlpha = false;
  21337. if (!rootUrl && !files) {
  21338. return;
  21339. }
  21340. this._texture = this._getFromCache(rootUrl, noMipmap);
  21341. if (!files) {
  21342. if (!extensions) {
  21343. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21344. }
  21345. files = [];
  21346. for (var index = 0; index < extensions.length; index++) {
  21347. files.push(rootUrl + extensions[index]);
  21348. }
  21349. this._extensions = extensions;
  21350. }
  21351. this._files = files;
  21352. if (!this._texture) {
  21353. if (!scene.useDelayedTextureLoading) {
  21354. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21355. }
  21356. else {
  21357. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21358. }
  21359. }
  21360. this.isCube = true;
  21361. this._textureMatrix = BABYLON.Matrix.Identity();
  21362. }
  21363. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21364. return new CubeTexture("", scene, null, noMipmap, files);
  21365. };
  21366. // Methods
  21367. CubeTexture.prototype.delayLoad = function () {
  21368. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21369. return;
  21370. }
  21371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21372. this._texture = this._getFromCache(this.url, this._noMipmap);
  21373. if (!this._texture) {
  21374. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  21375. }
  21376. };
  21377. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21378. return this._textureMatrix;
  21379. };
  21380. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21381. var texture = BABYLON.SerializationHelper.Parse(function () {
  21382. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21383. }, parsedTexture, scene);
  21384. // Animations
  21385. if (parsedTexture.animations) {
  21386. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21387. var parsedAnimation = parsedTexture.animations[animationIndex];
  21388. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21389. }
  21390. }
  21391. return texture;
  21392. };
  21393. CubeTexture.prototype.clone = function () {
  21394. var _this = this;
  21395. return BABYLON.SerializationHelper.Clone(function () {
  21396. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21397. }, this);
  21398. };
  21399. return CubeTexture;
  21400. })(BABYLON.BaseTexture);
  21401. BABYLON.CubeTexture = CubeTexture;
  21402. })(BABYLON || (BABYLON = {}));
  21403. var BABYLON;
  21404. (function (BABYLON) {
  21405. var RenderTargetTexture = (function (_super) {
  21406. __extends(RenderTargetTexture, _super);
  21407. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21408. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21409. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21410. if (isCube === void 0) { isCube = false; }
  21411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21412. _super.call(this, null, scene, !generateMipMaps);
  21413. this.isCube = isCube;
  21414. /**
  21415. * Use this list to define the list of mesh you want to render.
  21416. */
  21417. this.renderList = new Array();
  21418. this.renderParticles = true;
  21419. this.renderSprites = false;
  21420. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21421. // Events
  21422. /**
  21423. * An event triggered when the texture is unbind.
  21424. * @type {BABYLON.Observable}
  21425. */
  21426. this.onAfterUnbindObservable = new BABYLON.Observable();
  21427. /**
  21428. * An event triggered before rendering the texture
  21429. * @type {BABYLON.Observable}
  21430. */
  21431. this.onBeforeRenderObservable = new BABYLON.Observable();
  21432. /**
  21433. * An event triggered after rendering the texture
  21434. * @type {BABYLON.Observable}
  21435. */
  21436. this.onAfterRenderObservable = new BABYLON.Observable();
  21437. /**
  21438. * An event triggered after the texture clear
  21439. * @type {BABYLON.Observable}
  21440. */
  21441. this.onClearObservable = new BABYLON.Observable();
  21442. this._currentRefreshId = -1;
  21443. this._refreshRate = 1;
  21444. this.name = name;
  21445. this.isRenderTarget = true;
  21446. this._size = size;
  21447. this._generateMipMaps = generateMipMaps;
  21448. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21449. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  21450. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21451. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21452. }
  21453. if (isCube) {
  21454. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  21455. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21456. this._textureMatrix = BABYLON.Matrix.Identity();
  21457. }
  21458. else {
  21459. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  21460. }
  21461. // Rendering groups
  21462. this._renderingManager = new BABYLON.RenderingManager(scene);
  21463. }
  21464. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21465. get: function () {
  21466. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21472. get: function () {
  21473. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21479. get: function () {
  21480. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21486. set: function (callback) {
  21487. if (this._onAfterUnbindObserver) {
  21488. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21489. }
  21490. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21496. set: function (callback) {
  21497. if (this._onBeforeRenderObserver) {
  21498. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21499. }
  21500. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21501. },
  21502. enumerable: true,
  21503. configurable: true
  21504. });
  21505. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21506. set: function (callback) {
  21507. if (this._onAfterRenderObserver) {
  21508. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21509. }
  21510. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21516. set: function (callback) {
  21517. if (this._onClearObserver) {
  21518. this.onClearObservable.remove(this._onClearObserver);
  21519. }
  21520. this._onClearObserver = this.onClearObservable.add(callback);
  21521. },
  21522. enumerable: true,
  21523. configurable: true
  21524. });
  21525. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21526. this._currentRefreshId = -1;
  21527. };
  21528. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21529. get: function () {
  21530. return this._refreshRate;
  21531. },
  21532. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21533. set: function (value) {
  21534. this._refreshRate = value;
  21535. this.resetRefreshCounter();
  21536. },
  21537. enumerable: true,
  21538. configurable: true
  21539. });
  21540. RenderTargetTexture.prototype._shouldRender = function () {
  21541. if (this._currentRefreshId === -1) {
  21542. this._currentRefreshId = 1;
  21543. return true;
  21544. }
  21545. if (this.refreshRate === this._currentRefreshId) {
  21546. this._currentRefreshId = 1;
  21547. return true;
  21548. }
  21549. this._currentRefreshId++;
  21550. return false;
  21551. };
  21552. RenderTargetTexture.prototype.isReady = function () {
  21553. if (!this.getScene().renderTargetsEnabled) {
  21554. return false;
  21555. }
  21556. return _super.prototype.isReady.call(this);
  21557. };
  21558. RenderTargetTexture.prototype.getRenderSize = function () {
  21559. return this._size;
  21560. };
  21561. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21562. get: function () {
  21563. return true;
  21564. },
  21565. enumerable: true,
  21566. configurable: true
  21567. });
  21568. RenderTargetTexture.prototype.scale = function (ratio) {
  21569. var newSize = this._size * ratio;
  21570. this.resize(newSize, this._generateMipMaps);
  21571. };
  21572. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21573. if (this.isCube) {
  21574. return this._textureMatrix;
  21575. }
  21576. return _super.prototype.getReflectionTextureMatrix.call(this);
  21577. };
  21578. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21579. this.releaseInternalTexture();
  21580. if (this.isCube) {
  21581. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21582. }
  21583. else {
  21584. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21585. }
  21586. };
  21587. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21588. var scene = this.getScene();
  21589. if (this.useCameraPostProcesses !== undefined) {
  21590. useCameraPostProcess = this.useCameraPostProcesses;
  21591. }
  21592. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21593. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21594. }
  21595. if (this._waitingRenderList) {
  21596. this.renderList = [];
  21597. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21598. var id = this._waitingRenderList[index];
  21599. this.renderList.push(scene.getMeshByID(id));
  21600. }
  21601. delete this._waitingRenderList;
  21602. }
  21603. // Is predicate defined?
  21604. if (this.renderListPredicate) {
  21605. this.renderList.splice(0); // Clear previous renderList
  21606. var sceneMeshes = this.getScene().meshes;
  21607. for (var index = 0; index < sceneMeshes.length; index++) {
  21608. var mesh = sceneMeshes[index];
  21609. if (this.renderListPredicate(mesh)) {
  21610. this.renderList.push(mesh);
  21611. }
  21612. }
  21613. }
  21614. if (this.renderList && this.renderList.length === 0) {
  21615. return;
  21616. }
  21617. // Prepare renderingManager
  21618. this._renderingManager.reset();
  21619. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  21620. var sceneRenderId = scene.getRenderId();
  21621. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  21622. var mesh = currentRenderList[meshIndex];
  21623. if (mesh) {
  21624. if (!mesh.isReady()) {
  21625. // Reset _currentRefreshId
  21626. this.resetRefreshCounter();
  21627. continue;
  21628. }
  21629. mesh._preActivateForIntermediateRendering(sceneRenderId);
  21630. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  21631. mesh._activate(sceneRenderId);
  21632. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  21633. var subMesh = mesh.subMeshes[subIndex];
  21634. scene._activeIndices += subMesh.indexCount;
  21635. this._renderingManager.dispatch(subMesh);
  21636. }
  21637. }
  21638. }
  21639. }
  21640. if (this.isCube) {
  21641. for (var face = 0; face < 6; face++) {
  21642. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  21643. scene.incrementRenderId();
  21644. scene.resetCachedMaterial();
  21645. }
  21646. }
  21647. else {
  21648. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  21649. }
  21650. this.onAfterUnbindObservable.notifyObservers(this);
  21651. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21652. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  21653. }
  21654. scene.resetCachedMaterial();
  21655. };
  21656. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  21657. var scene = this.getScene();
  21658. var engine = scene.getEngine();
  21659. // Bind
  21660. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  21661. if (this.isCube) {
  21662. engine.bindFramebuffer(this._texture, faceIndex);
  21663. }
  21664. else {
  21665. engine.bindFramebuffer(this._texture);
  21666. }
  21667. }
  21668. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  21669. // Clear
  21670. if (this.onClearObservable.hasObservers()) {
  21671. this.onClearObservable.notifyObservers(engine);
  21672. }
  21673. else {
  21674. engine.clear(scene.clearColor, true, true);
  21675. }
  21676. if (!this._doNotChangeAspectRatio) {
  21677. scene.updateTransformMatrix(true);
  21678. }
  21679. // Render
  21680. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  21681. if (useCameraPostProcess) {
  21682. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  21683. }
  21684. if (!this._doNotChangeAspectRatio) {
  21685. scene.updateTransformMatrix(true);
  21686. }
  21687. this.onAfterRenderObservable.notifyObservers(faceIndex);
  21688. // Dump ?
  21689. if (dumpForDebug) {
  21690. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21691. }
  21692. // Unbind
  21693. if (!this.isCube || faceIndex === 5) {
  21694. if (this.isCube) {
  21695. if (faceIndex === 5) {
  21696. engine.generateMipMapsForCubemap(this._texture);
  21697. }
  21698. }
  21699. engine.unBindFramebuffer(this._texture, this.isCube);
  21700. }
  21701. };
  21702. RenderTargetTexture.prototype.clone = function () {
  21703. var textureSize = this.getSize();
  21704. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21705. // Base texture
  21706. newTexture.hasAlpha = this.hasAlpha;
  21707. newTexture.level = this.level;
  21708. // RenderTarget Texture
  21709. newTexture.coordinatesMode = this.coordinatesMode;
  21710. newTexture.renderList = this.renderList.slice(0);
  21711. return newTexture;
  21712. };
  21713. RenderTargetTexture.prototype.serialize = function () {
  21714. if (!this.name) {
  21715. return null;
  21716. }
  21717. var serializationObject = _super.prototype.serialize.call(this);
  21718. serializationObject.renderTargetSize = this.getRenderSize();
  21719. serializationObject.renderList = [];
  21720. for (var index = 0; index < this.renderList.length; index++) {
  21721. serializationObject.renderList.push(this.renderList[index].id);
  21722. }
  21723. return serializationObject;
  21724. };
  21725. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21726. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21727. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21728. return RenderTargetTexture;
  21729. })(BABYLON.Texture);
  21730. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21731. })(BABYLON || (BABYLON = {}));
  21732. var BABYLON;
  21733. (function (BABYLON) {
  21734. var ProceduralTexture = (function (_super) {
  21735. __extends(ProceduralTexture, _super);
  21736. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21737. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21738. if (isCube === void 0) { isCube = false; }
  21739. _super.call(this, null, scene, !generateMipMaps);
  21740. this.isCube = isCube;
  21741. this.isEnabled = true;
  21742. this._currentRefreshId = -1;
  21743. this._refreshRate = 1;
  21744. this._vertexBuffers = {};
  21745. this._uniforms = new Array();
  21746. this._samplers = new Array();
  21747. this._textures = new Array();
  21748. this._floats = new Array();
  21749. this._floatsArrays = {};
  21750. this._colors3 = new Array();
  21751. this._colors4 = new Array();
  21752. this._vectors2 = new Array();
  21753. this._vectors3 = new Array();
  21754. this._matrices = new Array();
  21755. this._fallbackTextureUsed = false;
  21756. scene._proceduralTextures.push(this);
  21757. this.name = name;
  21758. this.isRenderTarget = true;
  21759. this._size = size;
  21760. this._generateMipMaps = generateMipMaps;
  21761. this.setFragment(fragment);
  21762. this._fallbackTexture = fallbackTexture;
  21763. var engine = scene.getEngine();
  21764. if (isCube) {
  21765. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21766. this.setFloat("face", 0);
  21767. }
  21768. else {
  21769. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  21770. }
  21771. // VBO
  21772. var vertices = [];
  21773. vertices.push(1, 1);
  21774. vertices.push(-1, 1);
  21775. vertices.push(-1, -1);
  21776. vertices.push(1, -1);
  21777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  21778. // Indices
  21779. var indices = [];
  21780. indices.push(0);
  21781. indices.push(1);
  21782. indices.push(2);
  21783. indices.push(0);
  21784. indices.push(2);
  21785. indices.push(3);
  21786. this._indexBuffer = engine.createIndexBuffer(indices);
  21787. }
  21788. ProceduralTexture.prototype.reset = function () {
  21789. if (this._effect === undefined) {
  21790. return;
  21791. }
  21792. var engine = this.getScene().getEngine();
  21793. engine._releaseEffect(this._effect);
  21794. };
  21795. ProceduralTexture.prototype.isReady = function () {
  21796. var _this = this;
  21797. var engine = this.getScene().getEngine();
  21798. var shaders;
  21799. if (!this._fragment) {
  21800. return false;
  21801. }
  21802. if (this._fallbackTextureUsed) {
  21803. return true;
  21804. }
  21805. if (this._fragment.fragmentElement !== undefined) {
  21806. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21807. }
  21808. else {
  21809. shaders = { vertex: "procedural", fragment: this._fragment };
  21810. }
  21811. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  21812. _this.releaseInternalTexture();
  21813. if (_this._fallbackTexture) {
  21814. _this._texture = _this._fallbackTexture._texture;
  21815. _this._texture.references++;
  21816. }
  21817. _this._fallbackTextureUsed = true;
  21818. });
  21819. return this._effect.isReady();
  21820. };
  21821. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21822. this._currentRefreshId = -1;
  21823. };
  21824. ProceduralTexture.prototype.setFragment = function (fragment) {
  21825. this._fragment = fragment;
  21826. };
  21827. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21828. get: function () {
  21829. return this._refreshRate;
  21830. },
  21831. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21832. set: function (value) {
  21833. this._refreshRate = value;
  21834. this.resetRefreshCounter();
  21835. },
  21836. enumerable: true,
  21837. configurable: true
  21838. });
  21839. ProceduralTexture.prototype._shouldRender = function () {
  21840. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21841. return false;
  21842. }
  21843. if (this._fallbackTextureUsed) {
  21844. return false;
  21845. }
  21846. if (this._currentRefreshId === -1) {
  21847. this._currentRefreshId = 1;
  21848. return true;
  21849. }
  21850. if (this.refreshRate === this._currentRefreshId) {
  21851. this._currentRefreshId = 1;
  21852. return true;
  21853. }
  21854. this._currentRefreshId++;
  21855. return false;
  21856. };
  21857. ProceduralTexture.prototype.getRenderSize = function () {
  21858. return this._size;
  21859. };
  21860. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21861. if (this._fallbackTextureUsed) {
  21862. return;
  21863. }
  21864. this.releaseInternalTexture();
  21865. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21866. };
  21867. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21868. if (this._uniforms.indexOf(uniformName) === -1) {
  21869. this._uniforms.push(uniformName);
  21870. }
  21871. };
  21872. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21873. if (this._samplers.indexOf(name) === -1) {
  21874. this._samplers.push(name);
  21875. }
  21876. this._textures[name] = texture;
  21877. return this;
  21878. };
  21879. ProceduralTexture.prototype.setFloat = function (name, value) {
  21880. this._checkUniform(name);
  21881. this._floats[name] = value;
  21882. return this;
  21883. };
  21884. ProceduralTexture.prototype.setFloats = function (name, value) {
  21885. this._checkUniform(name);
  21886. this._floatsArrays[name] = value;
  21887. return this;
  21888. };
  21889. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21890. this._checkUniform(name);
  21891. this._colors3[name] = value;
  21892. return this;
  21893. };
  21894. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21895. this._checkUniform(name);
  21896. this._colors4[name] = value;
  21897. return this;
  21898. };
  21899. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21900. this._checkUniform(name);
  21901. this._vectors2[name] = value;
  21902. return this;
  21903. };
  21904. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21905. this._checkUniform(name);
  21906. this._vectors3[name] = value;
  21907. return this;
  21908. };
  21909. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21910. this._checkUniform(name);
  21911. this._matrices[name] = value;
  21912. return this;
  21913. };
  21914. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21915. var scene = this.getScene();
  21916. var engine = scene.getEngine();
  21917. // Render
  21918. engine.enableEffect(this._effect);
  21919. engine.setState(false);
  21920. // Texture
  21921. for (var name in this._textures) {
  21922. this._effect.setTexture(name, this._textures[name]);
  21923. }
  21924. // Float
  21925. for (name in this._floats) {
  21926. this._effect.setFloat(name, this._floats[name]);
  21927. }
  21928. // Floats
  21929. for (name in this._floatsArrays) {
  21930. this._effect.setArray(name, this._floatsArrays[name]);
  21931. }
  21932. // Color3
  21933. for (name in this._colors3) {
  21934. this._effect.setColor3(name, this._colors3[name]);
  21935. }
  21936. // Color4
  21937. for (name in this._colors4) {
  21938. var color = this._colors4[name];
  21939. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21940. }
  21941. // Vector2
  21942. for (name in this._vectors2) {
  21943. this._effect.setVector2(name, this._vectors2[name]);
  21944. }
  21945. // Vector3
  21946. for (name in this._vectors3) {
  21947. this._effect.setVector3(name, this._vectors3[name]);
  21948. }
  21949. // Matrix
  21950. for (name in this._matrices) {
  21951. this._effect.setMatrix(name, this._matrices[name]);
  21952. }
  21953. // VBOs
  21954. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  21955. if (this.isCube) {
  21956. for (var face = 0; face < 6; face++) {
  21957. engine.bindFramebuffer(this._texture, face);
  21958. this._effect.setFloat("face", face);
  21959. // Clear
  21960. engine.clear(scene.clearColor, true, true);
  21961. // Draw order
  21962. engine.draw(true, 0, 6);
  21963. // Mipmaps
  21964. if (face === 5) {
  21965. engine.generateMipMapsForCubemap(this._texture);
  21966. }
  21967. }
  21968. }
  21969. else {
  21970. engine.bindFramebuffer(this._texture);
  21971. // Clear
  21972. engine.clear(scene.clearColor, true, true);
  21973. // Draw order
  21974. engine.draw(true, 0, 6);
  21975. }
  21976. // Unbind
  21977. engine.unBindFramebuffer(this._texture, this.isCube);
  21978. if (this.onGenerated) {
  21979. this.onGenerated();
  21980. }
  21981. };
  21982. ProceduralTexture.prototype.clone = function () {
  21983. var textureSize = this.getSize();
  21984. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21985. // Base texture
  21986. newTexture.hasAlpha = this.hasAlpha;
  21987. newTexture.level = this.level;
  21988. // RenderTarget Texture
  21989. newTexture.coordinatesMode = this.coordinatesMode;
  21990. return newTexture;
  21991. };
  21992. ProceduralTexture.prototype.dispose = function () {
  21993. var index = this.getScene()._proceduralTextures.indexOf(this);
  21994. if (index >= 0) {
  21995. this.getScene()._proceduralTextures.splice(index, 1);
  21996. }
  21997. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  21998. if (vertexBuffer) {
  21999. vertexBuffer.dispose();
  22000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22001. }
  22002. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22003. this._indexBuffer = null;
  22004. }
  22005. _super.prototype.dispose.call(this);
  22006. };
  22007. return ProceduralTexture;
  22008. })(BABYLON.Texture);
  22009. BABYLON.ProceduralTexture = ProceduralTexture;
  22010. })(BABYLON || (BABYLON = {}));
  22011. var BABYLON;
  22012. (function (BABYLON) {
  22013. var MirrorTexture = (function (_super) {
  22014. __extends(MirrorTexture, _super);
  22015. function MirrorTexture(name, size, scene, generateMipMaps) {
  22016. var _this = this;
  22017. _super.call(this, name, size, scene, generateMipMaps, true);
  22018. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22019. this._transformMatrix = BABYLON.Matrix.Zero();
  22020. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22021. this.onBeforeRenderObservable.add(function () {
  22022. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22023. _this._savedViewMatrix = scene.getViewMatrix();
  22024. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22025. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22026. scene.clipPlane = _this.mirrorPlane;
  22027. scene.getEngine().cullBackFaces = false;
  22028. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22029. });
  22030. this.onAfterRenderObservable.add(function () {
  22031. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22032. scene.getEngine().cullBackFaces = true;
  22033. scene._mirroredCameraPosition = null;
  22034. delete scene.clipPlane;
  22035. });
  22036. }
  22037. MirrorTexture.prototype.clone = function () {
  22038. var textureSize = this.getSize();
  22039. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22040. // Base texture
  22041. newTexture.hasAlpha = this.hasAlpha;
  22042. newTexture.level = this.level;
  22043. // Mirror Texture
  22044. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22045. newTexture.renderList = this.renderList.slice(0);
  22046. return newTexture;
  22047. };
  22048. MirrorTexture.prototype.serialize = function () {
  22049. if (!this.name) {
  22050. return null;
  22051. }
  22052. var serializationObject = _super.prototype.serialize.call(this);
  22053. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22054. return serializationObject;
  22055. };
  22056. return MirrorTexture;
  22057. })(BABYLON.RenderTargetTexture);
  22058. BABYLON.MirrorTexture = MirrorTexture;
  22059. })(BABYLON || (BABYLON = {}));
  22060. var BABYLON;
  22061. (function (BABYLON) {
  22062. /**
  22063. * Creates a refraction texture used by refraction channel of the standard material.
  22064. * @param name the texture name
  22065. * @param size size of the underlying texture
  22066. * @param scene root scene
  22067. */
  22068. var RefractionTexture = (function (_super) {
  22069. __extends(RefractionTexture, _super);
  22070. function RefractionTexture(name, size, scene, generateMipMaps) {
  22071. var _this = this;
  22072. _super.call(this, name, size, scene, generateMipMaps, true);
  22073. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22074. this.depth = 2.0;
  22075. this.onBeforeRenderObservable.add(function () {
  22076. scene.clipPlane = _this.refractionPlane;
  22077. });
  22078. this.onAfterRenderObservable.add(function () {
  22079. delete scene.clipPlane;
  22080. });
  22081. }
  22082. RefractionTexture.prototype.clone = function () {
  22083. var textureSize = this.getSize();
  22084. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22085. // Base texture
  22086. newTexture.hasAlpha = this.hasAlpha;
  22087. newTexture.level = this.level;
  22088. // Refraction Texture
  22089. newTexture.refractionPlane = this.refractionPlane.clone();
  22090. newTexture.renderList = this.renderList.slice(0);
  22091. newTexture.depth = this.depth;
  22092. return newTexture;
  22093. };
  22094. RefractionTexture.prototype.serialize = function () {
  22095. if (!this.name) {
  22096. return null;
  22097. }
  22098. var serializationObject = _super.prototype.serialize.call(this);
  22099. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22100. serializationObject.depth = this.depth;
  22101. return serializationObject;
  22102. };
  22103. return RefractionTexture;
  22104. })(BABYLON.RenderTargetTexture);
  22105. BABYLON.RefractionTexture = RefractionTexture;
  22106. })(BABYLON || (BABYLON = {}));
  22107. var BABYLON;
  22108. (function (BABYLON) {
  22109. var DynamicTexture = (function (_super) {
  22110. __extends(DynamicTexture, _super);
  22111. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22113. _super.call(this, null, scene, !generateMipMaps);
  22114. this.name = name;
  22115. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22116. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22117. this._generateMipMaps = generateMipMaps;
  22118. if (options.getContext) {
  22119. this._canvas = options;
  22120. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22121. }
  22122. else {
  22123. this._canvas = document.createElement("canvas");
  22124. if (options.width) {
  22125. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22126. }
  22127. else {
  22128. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22129. }
  22130. }
  22131. var textureSize = this.getSize();
  22132. this._canvas.width = textureSize.width;
  22133. this._canvas.height = textureSize.height;
  22134. this._context = this._canvas.getContext("2d");
  22135. }
  22136. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22137. get: function () {
  22138. return true;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. DynamicTexture.prototype.scale = function (ratio) {
  22144. var textureSize = this.getSize();
  22145. textureSize.width *= ratio;
  22146. textureSize.height *= ratio;
  22147. this._canvas.width = textureSize.width;
  22148. this._canvas.height = textureSize.height;
  22149. this.releaseInternalTexture();
  22150. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22151. };
  22152. DynamicTexture.prototype.getContext = function () {
  22153. return this._context;
  22154. };
  22155. DynamicTexture.prototype.clear = function () {
  22156. var size = this.getSize();
  22157. this._context.fillRect(0, 0, size.width, size.height);
  22158. };
  22159. DynamicTexture.prototype.update = function (invertY) {
  22160. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22161. };
  22162. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22163. if (update === void 0) { update = true; }
  22164. var size = this.getSize();
  22165. if (clearColor) {
  22166. this._context.fillStyle = clearColor;
  22167. this._context.fillRect(0, 0, size.width, size.height);
  22168. }
  22169. this._context.font = font;
  22170. if (x === null) {
  22171. var textSize = this._context.measureText(text);
  22172. x = (size.width - textSize.width) / 2;
  22173. }
  22174. this._context.fillStyle = color;
  22175. this._context.fillText(text, x, y);
  22176. if (update) {
  22177. this.update(invertY);
  22178. }
  22179. };
  22180. DynamicTexture.prototype.clone = function () {
  22181. var textureSize = this.getSize();
  22182. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22183. // Base texture
  22184. newTexture.hasAlpha = this.hasAlpha;
  22185. newTexture.level = this.level;
  22186. // Dynamic Texture
  22187. newTexture.wrapU = this.wrapU;
  22188. newTexture.wrapV = this.wrapV;
  22189. return newTexture;
  22190. };
  22191. return DynamicTexture;
  22192. })(BABYLON.Texture);
  22193. BABYLON.DynamicTexture = DynamicTexture;
  22194. })(BABYLON || (BABYLON = {}));
  22195. var BABYLON;
  22196. (function (BABYLON) {
  22197. var VideoTexture = (function (_super) {
  22198. __extends(VideoTexture, _super);
  22199. /**
  22200. * Creates a video texture.
  22201. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22202. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22203. * @param {BABYLON.Scene} scene is obviously the current scene.
  22204. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22205. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22206. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22207. */
  22208. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22209. var _this = this;
  22210. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22211. if (invertY === void 0) { invertY = false; }
  22212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22213. _super.call(this, null, scene, !generateMipMaps, invertY);
  22214. this._autoLaunch = true;
  22215. var urls;
  22216. this.name = name;
  22217. if (urlsOrVideo instanceof HTMLVideoElement) {
  22218. this.video = urlsOrVideo;
  22219. }
  22220. else {
  22221. urls = urlsOrVideo;
  22222. this.video = document.createElement("video");
  22223. this.video.autoplay = false;
  22224. this.video.loop = true;
  22225. }
  22226. this._generateMipMaps = generateMipMaps;
  22227. this._samplingMode = samplingMode;
  22228. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22229. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22230. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22231. }
  22232. else {
  22233. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22234. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22235. this._generateMipMaps = false;
  22236. }
  22237. if (urls) {
  22238. this.video.addEventListener("canplaythrough", function () {
  22239. _this._createTexture();
  22240. });
  22241. urls.forEach(function (url) {
  22242. var source = document.createElement("source");
  22243. source.src = url;
  22244. _this.video.appendChild(source);
  22245. });
  22246. }
  22247. else {
  22248. this._createTexture();
  22249. }
  22250. this._lastUpdate = BABYLON.Tools.Now;
  22251. }
  22252. VideoTexture.prototype._createTexture = function () {
  22253. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  22254. this._texture.isReady = true;
  22255. };
  22256. VideoTexture.prototype.update = function () {
  22257. if (this._autoLaunch) {
  22258. this._autoLaunch = false;
  22259. this.video.play();
  22260. }
  22261. var now = BABYLON.Tools.Now;
  22262. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22263. return false;
  22264. }
  22265. this._lastUpdate = now;
  22266. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22267. return true;
  22268. };
  22269. return VideoTexture;
  22270. })(BABYLON.Texture);
  22271. BABYLON.VideoTexture = VideoTexture;
  22272. })(BABYLON || (BABYLON = {}));
  22273. var BABYLON;
  22274. (function (BABYLON) {
  22275. var CustomProceduralTexture = (function (_super) {
  22276. __extends(CustomProceduralTexture, _super);
  22277. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22278. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22279. this._animate = true;
  22280. this._time = 0;
  22281. this._texturePath = texturePath;
  22282. //Try to load json
  22283. this.loadJson(texturePath);
  22284. this.refreshRate = 1;
  22285. }
  22286. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22287. var _this = this;
  22288. var that = this;
  22289. function noConfigFile() {
  22290. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22291. try {
  22292. that.setFragment(that._texturePath);
  22293. }
  22294. catch (ex) {
  22295. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22296. }
  22297. }
  22298. var configFileUrl = jsonUrl + "/config.json";
  22299. var xhr = new XMLHttpRequest();
  22300. xhr.open("GET", configFileUrl, true);
  22301. xhr.addEventListener("load", function () {
  22302. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22303. try {
  22304. _this._config = JSON.parse(xhr.response);
  22305. _this.updateShaderUniforms();
  22306. _this.updateTextures();
  22307. _this.setFragment(_this._texturePath + "/custom");
  22308. _this._animate = _this._config.animate;
  22309. _this.refreshRate = _this._config.refreshrate;
  22310. }
  22311. catch (ex) {
  22312. noConfigFile();
  22313. }
  22314. }
  22315. else {
  22316. noConfigFile();
  22317. }
  22318. }, false);
  22319. xhr.addEventListener("error", function () {
  22320. noConfigFile();
  22321. }, false);
  22322. try {
  22323. xhr.send();
  22324. }
  22325. catch (ex) {
  22326. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22327. }
  22328. };
  22329. CustomProceduralTexture.prototype.isReady = function () {
  22330. if (!_super.prototype.isReady.call(this)) {
  22331. return false;
  22332. }
  22333. for (var name in this._textures) {
  22334. var texture = this._textures[name];
  22335. if (!texture.isReady()) {
  22336. return false;
  22337. }
  22338. }
  22339. return true;
  22340. };
  22341. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22342. if (this._animate) {
  22343. this._time += this.getScene().getAnimationRatio() * 0.03;
  22344. this.updateShaderUniforms();
  22345. }
  22346. _super.prototype.render.call(this, useCameraPostProcess);
  22347. };
  22348. CustomProceduralTexture.prototype.updateTextures = function () {
  22349. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22350. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22351. }
  22352. };
  22353. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22354. if (this._config) {
  22355. for (var j = 0; j < this._config.uniforms.length; j++) {
  22356. var uniform = this._config.uniforms[j];
  22357. switch (uniform.type) {
  22358. case "float":
  22359. this.setFloat(uniform.name, uniform.value);
  22360. break;
  22361. case "color3":
  22362. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22363. break;
  22364. case "color4":
  22365. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22366. break;
  22367. case "vector2":
  22368. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22369. break;
  22370. case "vector3":
  22371. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22372. break;
  22373. }
  22374. }
  22375. }
  22376. this.setFloat("time", this._time);
  22377. };
  22378. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22379. get: function () {
  22380. return this._animate;
  22381. },
  22382. set: function (value) {
  22383. this._animate = value;
  22384. },
  22385. enumerable: true,
  22386. configurable: true
  22387. });
  22388. return CustomProceduralTexture;
  22389. })(BABYLON.ProceduralTexture);
  22390. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22391. })(BABYLON || (BABYLON = {}));
  22392. var BABYLON;
  22393. (function (BABYLON) {
  22394. var EffectFallbacks = (function () {
  22395. function EffectFallbacks() {
  22396. this._defines = {};
  22397. this._currentRank = 32;
  22398. this._maxRank = -1;
  22399. }
  22400. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22401. if (!this._defines[rank]) {
  22402. if (rank < this._currentRank) {
  22403. this._currentRank = rank;
  22404. }
  22405. if (rank > this._maxRank) {
  22406. this._maxRank = rank;
  22407. }
  22408. this._defines[rank] = new Array();
  22409. }
  22410. this._defines[rank].push(define);
  22411. };
  22412. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22413. this._meshRank = rank;
  22414. this._mesh = mesh;
  22415. if (rank > this._maxRank) {
  22416. this._maxRank = rank;
  22417. }
  22418. };
  22419. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22420. get: function () {
  22421. return this._currentRank <= this._maxRank;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22427. var currentFallbacks = this._defines[this._currentRank];
  22428. for (var index = 0; index < currentFallbacks.length; index++) {
  22429. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22430. }
  22431. if (this._mesh && this._currentRank === this._meshRank) {
  22432. this._mesh.computeBonesUsingShaders = false;
  22433. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22434. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22435. }
  22436. this._currentRank++;
  22437. return currentDefines;
  22438. };
  22439. return EffectFallbacks;
  22440. })();
  22441. BABYLON.EffectFallbacks = EffectFallbacks;
  22442. var Effect = (function () {
  22443. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22444. var _this = this;
  22445. this._isReady = false;
  22446. this._compilationError = "";
  22447. this._valueCache = [];
  22448. this._engine = engine;
  22449. this.name = baseName;
  22450. this.defines = defines;
  22451. this._uniformsNames = uniformsNames.concat(samplers);
  22452. this._samplers = samplers;
  22453. this._attributesNames = attributesNames;
  22454. this.onError = onError;
  22455. this.onCompiled = onCompiled;
  22456. this._indexParameters = indexParameters;
  22457. var vertexSource;
  22458. var fragmentSource;
  22459. if (baseName.vertexElement) {
  22460. vertexSource = document.getElementById(baseName.vertexElement);
  22461. if (!vertexSource) {
  22462. vertexSource = baseName.vertexElement;
  22463. }
  22464. }
  22465. else {
  22466. vertexSource = baseName.vertex || baseName;
  22467. }
  22468. if (baseName.fragmentElement) {
  22469. fragmentSource = document.getElementById(baseName.fragmentElement);
  22470. if (!fragmentSource) {
  22471. fragmentSource = baseName.fragmentElement;
  22472. }
  22473. }
  22474. else {
  22475. fragmentSource = baseName.fragment || baseName;
  22476. }
  22477. this._loadVertexShader(vertexSource, function (vertexCode) {
  22478. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22479. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22480. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22481. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22482. });
  22483. });
  22484. });
  22485. });
  22486. }
  22487. // Properties
  22488. Effect.prototype.isReady = function () {
  22489. return this._isReady;
  22490. };
  22491. Effect.prototype.getProgram = function () {
  22492. return this._program;
  22493. };
  22494. Effect.prototype.getAttributesNames = function () {
  22495. return this._attributesNames;
  22496. };
  22497. Effect.prototype.getAttributeLocation = function (index) {
  22498. return this._attributes[index];
  22499. };
  22500. Effect.prototype.getAttributeLocationByName = function (name) {
  22501. var index = this._attributesNames.indexOf(name);
  22502. return this._attributes[index];
  22503. };
  22504. Effect.prototype.getAttributesCount = function () {
  22505. return this._attributes.length;
  22506. };
  22507. Effect.prototype.getUniformIndex = function (uniformName) {
  22508. return this._uniformsNames.indexOf(uniformName);
  22509. };
  22510. Effect.prototype.getUniform = function (uniformName) {
  22511. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22512. };
  22513. Effect.prototype.getSamplers = function () {
  22514. return this._samplers;
  22515. };
  22516. Effect.prototype.getCompilationError = function () {
  22517. return this._compilationError;
  22518. };
  22519. // Methods
  22520. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22521. // DOM element ?
  22522. if (vertex instanceof HTMLElement) {
  22523. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22524. callback(vertexCode);
  22525. return;
  22526. }
  22527. // Is in local store ?
  22528. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22529. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22530. return;
  22531. }
  22532. var vertexShaderUrl;
  22533. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22534. vertexShaderUrl = vertex;
  22535. }
  22536. else {
  22537. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22538. }
  22539. // Vertex shader
  22540. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22541. };
  22542. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22543. // DOM element ?
  22544. if (fragment instanceof HTMLElement) {
  22545. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22546. callback(fragmentCode);
  22547. return;
  22548. }
  22549. // Is in local store ?
  22550. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22551. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22552. return;
  22553. }
  22554. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22555. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22556. return;
  22557. }
  22558. var fragmentShaderUrl;
  22559. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22560. fragmentShaderUrl = fragment;
  22561. }
  22562. else {
  22563. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22564. }
  22565. // Fragment shader
  22566. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22567. };
  22568. Effect.prototype._dumpShadersName = function () {
  22569. if (this.name.vertexElement) {
  22570. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22571. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22572. }
  22573. else if (this.name.vertex) {
  22574. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22575. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22576. }
  22577. else {
  22578. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22579. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22580. }
  22581. };
  22582. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22583. var _this = this;
  22584. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22585. var match = regex.exec(sourceCode);
  22586. var returnValue = new String(sourceCode);
  22587. while (match != null) {
  22588. var includeFile = match[1];
  22589. if (Effect.IncludesShadersStore[includeFile]) {
  22590. // Substitution
  22591. var includeContent = Effect.IncludesShadersStore[includeFile];
  22592. if (match[2]) {
  22593. var splits = match[3].split(",");
  22594. for (var index = 0; index < splits.length; index += 2) {
  22595. var source = new RegExp(splits[index], "g");
  22596. var dest = splits[index + 1];
  22597. includeContent = includeContent.replace(source, dest);
  22598. }
  22599. }
  22600. if (match[4]) {
  22601. var indexString = match[5];
  22602. if (indexString.indexOf("..") !== -1) {
  22603. var indexSplits = indexString.split("..");
  22604. var minIndex = parseInt(indexSplits[0]);
  22605. var maxIndex = parseInt(indexSplits[1]);
  22606. var sourceIncludeContent = includeContent.slice(0);
  22607. includeContent = "";
  22608. if (isNaN(maxIndex)) {
  22609. maxIndex = this._indexParameters[indexSplits[1]];
  22610. }
  22611. for (var i = minIndex; i <= maxIndex; i++) {
  22612. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22613. }
  22614. }
  22615. else {
  22616. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22617. }
  22618. }
  22619. // Replace
  22620. returnValue = returnValue.replace(match[0], includeContent);
  22621. }
  22622. else {
  22623. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22624. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22625. Effect.IncludesShadersStore[includeFile] = fileContent;
  22626. _this._processIncludes(returnValue, callback);
  22627. });
  22628. return;
  22629. }
  22630. match = regex.exec(sourceCode);
  22631. }
  22632. callback(returnValue);
  22633. };
  22634. Effect.prototype._processPrecision = function (source) {
  22635. if (source.indexOf("precision highp float") === -1) {
  22636. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22637. source = "precision mediump float;\n" + source;
  22638. }
  22639. else {
  22640. source = "precision highp float;\n" + source;
  22641. }
  22642. }
  22643. else {
  22644. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22645. source = source.replace("precision highp float", "precision mediump float");
  22646. }
  22647. }
  22648. return source;
  22649. };
  22650. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22651. try {
  22652. var engine = this._engine;
  22653. // Precision
  22654. vertexSourceCode = this._processPrecision(vertexSourceCode);
  22655. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  22656. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22657. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22658. this._attributes = engine.getAttributes(this._program, attributesNames);
  22659. for (var index = 0; index < this._samplers.length; index++) {
  22660. var sampler = this.getUniform(this._samplers[index]);
  22661. if (sampler == null) {
  22662. this._samplers.splice(index, 1);
  22663. index--;
  22664. }
  22665. }
  22666. engine.bindSamplers(this);
  22667. this._isReady = true;
  22668. if (this.onCompiled) {
  22669. this.onCompiled(this);
  22670. }
  22671. }
  22672. catch (e) {
  22673. // Is it a problem with precision?
  22674. if (e.message.indexOf("highp") !== -1) {
  22675. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  22676. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  22677. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22678. return;
  22679. }
  22680. // Let's go through fallbacks then
  22681. if (fallbacks && fallbacks.isMoreFallbacks) {
  22682. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  22683. this._dumpShadersName();
  22684. defines = fallbacks.reduce(defines);
  22685. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22686. }
  22687. else {
  22688. BABYLON.Tools.Error("Unable to compile effect: ");
  22689. this._dumpShadersName();
  22690. BABYLON.Tools.Error("Defines: " + defines);
  22691. BABYLON.Tools.Error("Error: " + e.message);
  22692. this._compilationError = e.message;
  22693. if (this.onError) {
  22694. this.onError(this, this._compilationError);
  22695. }
  22696. }
  22697. }
  22698. };
  22699. Object.defineProperty(Effect.prototype, "isSupported", {
  22700. get: function () {
  22701. return this._compilationError === "";
  22702. },
  22703. enumerable: true,
  22704. configurable: true
  22705. });
  22706. Effect.prototype._bindTexture = function (channel, texture) {
  22707. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22708. };
  22709. Effect.prototype.setTexture = function (channel, texture) {
  22710. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22711. };
  22712. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22713. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22714. };
  22715. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22716. if (!this._valueCache[uniformName]) {
  22717. this._valueCache[uniformName] = new BABYLON.Matrix();
  22718. }
  22719. for (var index = 0; index < 16; index++) {
  22720. this._valueCache[uniformName].m[index] = matrix.m[index];
  22721. }
  22722. };
  22723. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22724. if (!this._valueCache[uniformName]) {
  22725. this._valueCache[uniformName] = [x, y];
  22726. return;
  22727. }
  22728. this._valueCache[uniformName][0] = x;
  22729. this._valueCache[uniformName][1] = y;
  22730. };
  22731. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22732. if (!this._valueCache[uniformName]) {
  22733. this._valueCache[uniformName] = [x, y, z];
  22734. return;
  22735. }
  22736. this._valueCache[uniformName][0] = x;
  22737. this._valueCache[uniformName][1] = y;
  22738. this._valueCache[uniformName][2] = z;
  22739. };
  22740. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22741. if (!this._valueCache[uniformName]) {
  22742. this._valueCache[uniformName] = [x, y, z, w];
  22743. return;
  22744. }
  22745. this._valueCache[uniformName][0] = x;
  22746. this._valueCache[uniformName][1] = y;
  22747. this._valueCache[uniformName][2] = z;
  22748. this._valueCache[uniformName][3] = w;
  22749. };
  22750. Effect.prototype.setArray = function (uniformName, array) {
  22751. this._engine.setArray(this.getUniform(uniformName), array);
  22752. return this;
  22753. };
  22754. Effect.prototype.setArray2 = function (uniformName, array) {
  22755. this._engine.setArray2(this.getUniform(uniformName), array);
  22756. return this;
  22757. };
  22758. Effect.prototype.setArray3 = function (uniformName, array) {
  22759. this._engine.setArray3(this.getUniform(uniformName), array);
  22760. return this;
  22761. };
  22762. Effect.prototype.setArray4 = function (uniformName, array) {
  22763. this._engine.setArray4(this.getUniform(uniformName), array);
  22764. return this;
  22765. };
  22766. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22767. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22768. return this;
  22769. };
  22770. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22771. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22772. // return this;
  22773. // this._cacheMatrix(uniformName, matrix);
  22774. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22775. return this;
  22776. };
  22777. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22778. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22779. return this;
  22780. };
  22781. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22782. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22783. return this;
  22784. };
  22785. Effect.prototype.setFloat = function (uniformName, value) {
  22786. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22787. return this;
  22788. this._valueCache[uniformName] = value;
  22789. this._engine.setFloat(this.getUniform(uniformName), value);
  22790. return this;
  22791. };
  22792. Effect.prototype.setBool = function (uniformName, bool) {
  22793. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22794. return this;
  22795. this._valueCache[uniformName] = bool;
  22796. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22797. return this;
  22798. };
  22799. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22800. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22801. return this;
  22802. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22803. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22804. return this;
  22805. };
  22806. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22807. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22808. return this;
  22809. this._cacheFloat2(uniformName, x, y);
  22810. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22811. return this;
  22812. };
  22813. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22814. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22815. return this;
  22816. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22817. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22818. return this;
  22819. };
  22820. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22821. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22822. return this;
  22823. this._cacheFloat3(uniformName, x, y, z);
  22824. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22825. return this;
  22826. };
  22827. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22828. 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)
  22829. return this;
  22830. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22831. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22832. return this;
  22833. };
  22834. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22835. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22836. return this;
  22837. this._cacheFloat4(uniformName, x, y, z, w);
  22838. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22839. return this;
  22840. };
  22841. Effect.prototype.setColor3 = function (uniformName, color3) {
  22842. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22843. return this;
  22844. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22845. this._engine.setColor3(this.getUniform(uniformName), color3);
  22846. return this;
  22847. };
  22848. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22849. 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)
  22850. return this;
  22851. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22852. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22853. return this;
  22854. };
  22855. // Statics
  22856. Effect.ShadersStore = {};
  22857. Effect.IncludesShadersStore = {};
  22858. return Effect;
  22859. })();
  22860. BABYLON.Effect = Effect;
  22861. })(BABYLON || (BABYLON = {}));
  22862. var BABYLON;
  22863. (function (BABYLON) {
  22864. var MaterialHelper = (function () {
  22865. function MaterialHelper() {
  22866. }
  22867. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22868. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22869. var lightIndex = 0;
  22870. var needNormals = false;
  22871. var needRebuild = false;
  22872. for (var index = 0; index < scene.lights.length; index++) {
  22873. var light = scene.lights[index];
  22874. if (!light.isEnabled()) {
  22875. continue;
  22876. }
  22877. // Excluded check
  22878. if (light._excludedMeshesIds.length > 0) {
  22879. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22880. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22881. if (excludedMesh) {
  22882. light.excludedMeshes.push(excludedMesh);
  22883. }
  22884. }
  22885. light._excludedMeshesIds = [];
  22886. }
  22887. // Included check
  22888. if (light._includedOnlyMeshesIds.length > 0) {
  22889. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22890. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22891. if (includedOnlyMesh) {
  22892. light.includedOnlyMeshes.push(includedOnlyMesh);
  22893. }
  22894. }
  22895. light._includedOnlyMeshesIds = [];
  22896. }
  22897. if (!light.canAffectMesh(mesh)) {
  22898. continue;
  22899. }
  22900. needNormals = true;
  22901. if (defines["LIGHT" + lightIndex] === undefined) {
  22902. needRebuild = true;
  22903. }
  22904. defines["LIGHT" + lightIndex] = true;
  22905. var type;
  22906. if (light instanceof BABYLON.SpotLight) {
  22907. type = "SPOTLIGHT" + lightIndex;
  22908. }
  22909. else if (light instanceof BABYLON.HemisphericLight) {
  22910. type = "HEMILIGHT" + lightIndex;
  22911. }
  22912. else if (light instanceof BABYLON.PointLight) {
  22913. type = "POINTLIGHT" + lightIndex;
  22914. }
  22915. else {
  22916. type = "DIRLIGHT" + lightIndex;
  22917. }
  22918. if (defines[type] === undefined) {
  22919. needRebuild = true;
  22920. }
  22921. defines[type] = true;
  22922. // Specular
  22923. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22924. defines["SPECULARTERM"] = true;
  22925. }
  22926. // Shadows
  22927. if (scene.shadowsEnabled) {
  22928. var shadowGenerator = light.getShadowGenerator();
  22929. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22930. if (defines["SHADOW" + lightIndex] === undefined) {
  22931. needRebuild = true;
  22932. }
  22933. defines["SHADOW" + lightIndex] = true;
  22934. defines["SHADOWS"] = true;
  22935. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22936. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22937. needRebuild = true;
  22938. }
  22939. defines["SHADOWVSM" + lightIndex] = true;
  22940. }
  22941. if (shadowGenerator.usePoissonSampling) {
  22942. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22943. needRebuild = true;
  22944. }
  22945. defines["SHADOWPCF" + lightIndex] = true;
  22946. }
  22947. }
  22948. }
  22949. lightIndex++;
  22950. if (lightIndex === maxSimultaneousLights)
  22951. break;
  22952. }
  22953. if (needRebuild) {
  22954. defines.rebuild();
  22955. }
  22956. return needNormals;
  22957. };
  22958. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22959. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22960. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22961. if (!defines["LIGHT" + lightIndex]) {
  22962. break;
  22963. }
  22964. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22965. samplersList.push("shadowSampler" + lightIndex);
  22966. }
  22967. };
  22968. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22969. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22970. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22971. if (!defines["LIGHT" + lightIndex]) {
  22972. break;
  22973. }
  22974. if (lightIndex > 0) {
  22975. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22976. }
  22977. if (defines["SHADOW" + lightIndex]) {
  22978. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22979. }
  22980. if (defines["SHADOWPCF" + lightIndex]) {
  22981. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22982. }
  22983. if (defines["SHADOWVSM" + lightIndex]) {
  22984. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22985. }
  22986. }
  22987. };
  22988. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22989. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22990. fallbacks.addCPUSkinningFallback(0, mesh);
  22991. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22992. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22993. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22996. }
  22997. }
  22998. };
  22999. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23000. if (defines["INSTANCES"]) {
  23001. attribs.push("world0");
  23002. attribs.push("world1");
  23003. attribs.push("world2");
  23004. attribs.push("world3");
  23005. }
  23006. };
  23007. // Bindings
  23008. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23009. var shadowGenerator = light.getShadowGenerator();
  23010. if (mesh.receiveShadows && shadowGenerator) {
  23011. if (!light.needCube()) {
  23012. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23013. }
  23014. else {
  23015. if (!depthValuesAlreadySet) {
  23016. depthValuesAlreadySet = true;
  23017. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23018. }
  23019. }
  23020. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23021. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23022. }
  23023. return depthValuesAlreadySet;
  23024. };
  23025. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23026. if (light instanceof BABYLON.PointLight) {
  23027. // Point Light
  23028. light.transferToEffect(effect, "vLightData" + lightIndex);
  23029. }
  23030. else if (light instanceof BABYLON.DirectionalLight) {
  23031. // Directional Light
  23032. light.transferToEffect(effect, "vLightData" + lightIndex);
  23033. }
  23034. else if (light instanceof BABYLON.SpotLight) {
  23035. // Spot Light
  23036. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23037. }
  23038. else if (light instanceof BABYLON.HemisphericLight) {
  23039. // Hemispheric Light
  23040. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23041. }
  23042. };
  23043. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23044. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23045. var lightIndex = 0;
  23046. var depthValuesAlreadySet = false;
  23047. for (var index = 0; index < scene.lights.length; index++) {
  23048. var light = scene.lights[index];
  23049. if (!light.isEnabled()) {
  23050. continue;
  23051. }
  23052. if (!light.canAffectMesh(mesh)) {
  23053. continue;
  23054. }
  23055. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23056. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23057. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23058. if (defines["SPECULARTERM"]) {
  23059. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23060. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23061. }
  23062. // Shadows
  23063. if (scene.shadowsEnabled) {
  23064. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23065. }
  23066. lightIndex++;
  23067. if (lightIndex === maxSimultaneousLights)
  23068. break;
  23069. }
  23070. };
  23071. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23072. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23073. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23074. effect.setColor3("vFogColor", scene.fogColor);
  23075. }
  23076. };
  23077. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23078. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23079. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23080. }
  23081. };
  23082. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23083. if (defines["LOGARITHMICDEPTH"]) {
  23084. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23085. }
  23086. };
  23087. MaterialHelper.BindClipPlane = function (effect, scene) {
  23088. if (scene.clipPlane) {
  23089. var clipPlane = scene.clipPlane;
  23090. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23091. }
  23092. };
  23093. return MaterialHelper;
  23094. })();
  23095. BABYLON.MaterialHelper = MaterialHelper;
  23096. })(BABYLON || (BABYLON = {}));
  23097. var BABYLON;
  23098. (function (BABYLON) {
  23099. var FresnelParameters = (function () {
  23100. function FresnelParameters() {
  23101. this.isEnabled = true;
  23102. this.leftColor = BABYLON.Color3.White();
  23103. this.rightColor = BABYLON.Color3.Black();
  23104. this.bias = 0;
  23105. this.power = 1;
  23106. }
  23107. FresnelParameters.prototype.clone = function () {
  23108. var newFresnelParameters = new FresnelParameters();
  23109. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23110. return new FresnelParameters;
  23111. };
  23112. FresnelParameters.prototype.serialize = function () {
  23113. var serializationObject = {};
  23114. serializationObject.isEnabled = this.isEnabled;
  23115. serializationObject.leftColor = this.leftColor;
  23116. serializationObject.rightColor = this.rightColor;
  23117. serializationObject.bias = this.bias;
  23118. serializationObject.power = this.power;
  23119. return serializationObject;
  23120. };
  23121. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23122. var fresnelParameters = new FresnelParameters();
  23123. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23124. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23125. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23126. fresnelParameters.bias = parsedFresnelParameters.bias;
  23127. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23128. return fresnelParameters;
  23129. };
  23130. return FresnelParameters;
  23131. })();
  23132. BABYLON.FresnelParameters = FresnelParameters;
  23133. })(BABYLON || (BABYLON = {}));
  23134. var BABYLON;
  23135. (function (BABYLON) {
  23136. var MaterialDefines = (function () {
  23137. function MaterialDefines() {
  23138. }
  23139. MaterialDefines.prototype.rebuild = function () {
  23140. if (this._keys) {
  23141. delete this._keys;
  23142. }
  23143. this._keys = Object.keys(this);
  23144. };
  23145. MaterialDefines.prototype.isEqual = function (other) {
  23146. if (this._keys.length !== other._keys.length) {
  23147. return false;
  23148. }
  23149. for (var index = 0; index < this._keys.length; index++) {
  23150. var prop = this._keys[index];
  23151. if (this[prop] !== other[prop]) {
  23152. return false;
  23153. }
  23154. }
  23155. return true;
  23156. };
  23157. MaterialDefines.prototype.cloneTo = function (other) {
  23158. if (this._keys.length !== other._keys.length) {
  23159. other._keys = this._keys.slice(0);
  23160. }
  23161. for (var index = 0; index < this._keys.length; index++) {
  23162. var prop = this._keys[index];
  23163. other[prop] = this[prop];
  23164. }
  23165. };
  23166. MaterialDefines.prototype.reset = function () {
  23167. for (var index = 0; index < this._keys.length; index++) {
  23168. var prop = this._keys[index];
  23169. if (typeof (this[prop]) === "number") {
  23170. this[prop] = 0;
  23171. }
  23172. else {
  23173. this[prop] = false;
  23174. }
  23175. }
  23176. };
  23177. MaterialDefines.prototype.toString = function () {
  23178. var result = "";
  23179. for (var index = 0; index < this._keys.length; index++) {
  23180. var prop = this._keys[index];
  23181. if (typeof (this[prop]) === "number") {
  23182. result += "#define " + prop + " " + this[prop] + "\n";
  23183. }
  23184. else if (this[prop]) {
  23185. result += "#define " + prop + "\n";
  23186. }
  23187. }
  23188. return result;
  23189. };
  23190. return MaterialDefines;
  23191. })();
  23192. BABYLON.MaterialDefines = MaterialDefines;
  23193. var Material = (function () {
  23194. function Material(name, scene, doNotAdd) {
  23195. this.name = name;
  23196. this.checkReadyOnEveryCall = false;
  23197. this.checkReadyOnlyOnce = false;
  23198. this.state = "";
  23199. this.alpha = 1.0;
  23200. this.backFaceCulling = true;
  23201. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23202. /**
  23203. * An event triggered when the material is disposed.
  23204. * @type {BABYLON.Observable}
  23205. */
  23206. this.onDisposeObservable = new BABYLON.Observable();
  23207. /**
  23208. * An event triggered when the material is compiled.
  23209. * @type {BABYLON.Observable}
  23210. */
  23211. this.onBindObservable = new BABYLON.Observable();
  23212. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23213. this.disableDepthWrite = false;
  23214. this.fogEnabled = true;
  23215. this.pointSize = 1.0;
  23216. this.zOffset = 0;
  23217. this._wasPreviouslyReady = false;
  23218. this._fillMode = Material.TriangleFillMode;
  23219. this.id = name;
  23220. this._scene = scene;
  23221. if (!doNotAdd) {
  23222. scene.materials.push(this);
  23223. }
  23224. }
  23225. Object.defineProperty(Material, "TriangleFillMode", {
  23226. get: function () {
  23227. return Material._TriangleFillMode;
  23228. },
  23229. enumerable: true,
  23230. configurable: true
  23231. });
  23232. Object.defineProperty(Material, "WireFrameFillMode", {
  23233. get: function () {
  23234. return Material._WireFrameFillMode;
  23235. },
  23236. enumerable: true,
  23237. configurable: true
  23238. });
  23239. Object.defineProperty(Material, "PointFillMode", {
  23240. get: function () {
  23241. return Material._PointFillMode;
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23247. get: function () {
  23248. return Material._ClockWiseSideOrientation;
  23249. },
  23250. enumerable: true,
  23251. configurable: true
  23252. });
  23253. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23254. get: function () {
  23255. return Material._CounterClockWiseSideOrientation;
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. Object.defineProperty(Material.prototype, "onDispose", {
  23261. set: function (callback) {
  23262. if (this._onDisposeObserver) {
  23263. this.onDisposeObservable.remove(this._onDisposeObserver);
  23264. }
  23265. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23266. },
  23267. enumerable: true,
  23268. configurable: true
  23269. });
  23270. Object.defineProperty(Material.prototype, "onBind", {
  23271. set: function (callback) {
  23272. if (this._onBindObserver) {
  23273. this.onBindObservable.remove(this._onBindObserver);
  23274. }
  23275. this._onBindObserver = this.onBindObservable.add(callback);
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. Object.defineProperty(Material.prototype, "wireframe", {
  23281. get: function () {
  23282. return this._fillMode === Material.WireFrameFillMode;
  23283. },
  23284. set: function (value) {
  23285. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. Object.defineProperty(Material.prototype, "pointsCloud", {
  23291. get: function () {
  23292. return this._fillMode === Material.PointFillMode;
  23293. },
  23294. set: function (value) {
  23295. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23296. },
  23297. enumerable: true,
  23298. configurable: true
  23299. });
  23300. Object.defineProperty(Material.prototype, "fillMode", {
  23301. get: function () {
  23302. return this._fillMode;
  23303. },
  23304. set: function (value) {
  23305. this._fillMode = value;
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. /**
  23311. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23312. * subclasses should override adding information pertainent to themselves
  23313. */
  23314. Material.prototype.toString = function (fullDetails) {
  23315. var ret = "Name: " + this.name;
  23316. if (fullDetails) {
  23317. }
  23318. return ret;
  23319. };
  23320. Object.defineProperty(Material.prototype, "isFrozen", {
  23321. get: function () {
  23322. return this.checkReadyOnlyOnce;
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. Material.prototype.freeze = function () {
  23328. this.checkReadyOnlyOnce = true;
  23329. };
  23330. Material.prototype.unfreeze = function () {
  23331. this.checkReadyOnlyOnce = false;
  23332. };
  23333. Material.prototype.isReady = function (mesh, useInstances) {
  23334. return true;
  23335. };
  23336. Material.prototype.getEffect = function () {
  23337. return this._effect;
  23338. };
  23339. Material.prototype.getScene = function () {
  23340. return this._scene;
  23341. };
  23342. Material.prototype.needAlphaBlending = function () {
  23343. return (this.alpha < 1.0);
  23344. };
  23345. Material.prototype.needAlphaTesting = function () {
  23346. return false;
  23347. };
  23348. Material.prototype.getAlphaTestTexture = function () {
  23349. return null;
  23350. };
  23351. Material.prototype.markDirty = function () {
  23352. this._wasPreviouslyReady = false;
  23353. };
  23354. Material.prototype._preBind = function () {
  23355. var engine = this._scene.getEngine();
  23356. engine.enableEffect(this._effect);
  23357. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23358. };
  23359. Material.prototype.bind = function (world, mesh) {
  23360. this._scene._cachedMaterial = this;
  23361. this.onBindObservable.notifyObservers(mesh);
  23362. if (this.disableDepthWrite) {
  23363. var engine = this._scene.getEngine();
  23364. this._cachedDepthWriteState = engine.getDepthWrite();
  23365. engine.setDepthWrite(false);
  23366. }
  23367. };
  23368. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23369. };
  23370. Material.prototype.unbind = function () {
  23371. if (this.disableDepthWrite) {
  23372. var engine = this._scene.getEngine();
  23373. engine.setDepthWrite(this._cachedDepthWriteState);
  23374. }
  23375. };
  23376. Material.prototype.clone = function (name) {
  23377. return null;
  23378. };
  23379. Material.prototype.getBindedMeshes = function () {
  23380. var result = new Array();
  23381. for (var index = 0; index < this._scene.meshes.length; index++) {
  23382. var mesh = this._scene.meshes[index];
  23383. if (mesh.material === this) {
  23384. result.push(mesh);
  23385. }
  23386. }
  23387. return result;
  23388. };
  23389. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23390. // Animations
  23391. this.getScene().stopAnimation(this);
  23392. // Remove from scene
  23393. var index = this._scene.materials.indexOf(this);
  23394. if (index >= 0) {
  23395. this._scene.materials.splice(index, 1);
  23396. }
  23397. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23398. if (forceDisposeEffect && this._effect) {
  23399. this._scene.getEngine()._releaseEffect(this._effect);
  23400. this._effect = null;
  23401. }
  23402. // Remove from meshes
  23403. for (index = 0; index < this._scene.meshes.length; index++) {
  23404. var mesh = this._scene.meshes[index];
  23405. if (mesh.material === this) {
  23406. mesh.material = null;
  23407. }
  23408. }
  23409. // Callback
  23410. this.onDisposeObservable.notifyObservers(this);
  23411. this.onDisposeObservable.clear();
  23412. this.onBindObservable.clear();
  23413. };
  23414. Material.prototype.serialize = function () {
  23415. return BABYLON.SerializationHelper.Serialize(this);
  23416. };
  23417. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23418. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23419. multiMaterial.id = parsedMultiMaterial.id;
  23420. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23421. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23422. var subMatId = parsedMultiMaterial.materials[matIndex];
  23423. if (subMatId) {
  23424. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23425. }
  23426. else {
  23427. multiMaterial.subMaterials.push(null);
  23428. }
  23429. }
  23430. return multiMaterial;
  23431. };
  23432. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23433. if (!parsedMaterial.customType) {
  23434. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23435. }
  23436. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23437. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23438. ;
  23439. };
  23440. Material._TriangleFillMode = 0;
  23441. Material._WireFrameFillMode = 1;
  23442. Material._PointFillMode = 2;
  23443. Material._ClockWiseSideOrientation = 0;
  23444. Material._CounterClockWiseSideOrientation = 1;
  23445. __decorate([
  23446. BABYLON.serialize()
  23447. ], Material.prototype, "id", void 0);
  23448. __decorate([
  23449. BABYLON.serialize()
  23450. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23451. __decorate([
  23452. BABYLON.serialize()
  23453. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23454. __decorate([
  23455. BABYLON.serialize()
  23456. ], Material.prototype, "state", void 0);
  23457. __decorate([
  23458. BABYLON.serialize()
  23459. ], Material.prototype, "alpha", void 0);
  23460. __decorate([
  23461. BABYLON.serialize()
  23462. ], Material.prototype, "backFaceCulling", void 0);
  23463. __decorate([
  23464. BABYLON.serialize()
  23465. ], Material.prototype, "sideOrientation", void 0);
  23466. __decorate([
  23467. BABYLON.serialize()
  23468. ], Material.prototype, "alphaMode", void 0);
  23469. __decorate([
  23470. BABYLON.serialize()
  23471. ], Material.prototype, "disableDepthWrite", void 0);
  23472. __decorate([
  23473. BABYLON.serialize()
  23474. ], Material.prototype, "fogEnabled", void 0);
  23475. __decorate([
  23476. BABYLON.serialize()
  23477. ], Material.prototype, "pointSize", void 0);
  23478. __decorate([
  23479. BABYLON.serialize()
  23480. ], Material.prototype, "zOffset", void 0);
  23481. __decorate([
  23482. BABYLON.serialize()
  23483. ], Material.prototype, "wireframe", null);
  23484. __decorate([
  23485. BABYLON.serialize()
  23486. ], Material.prototype, "pointsCloud", null);
  23487. __decorate([
  23488. BABYLON.serialize()
  23489. ], Material.prototype, "fillMode", null);
  23490. return Material;
  23491. })();
  23492. BABYLON.Material = Material;
  23493. })(BABYLON || (BABYLON = {}));
  23494. var BABYLON;
  23495. (function (BABYLON) {
  23496. var StandardMaterialDefines = (function (_super) {
  23497. __extends(StandardMaterialDefines, _super);
  23498. function StandardMaterialDefines() {
  23499. _super.call(this);
  23500. this.DIFFUSE = false;
  23501. this.AMBIENT = false;
  23502. this.OPACITY = false;
  23503. this.OPACITYRGB = false;
  23504. this.REFLECTION = false;
  23505. this.EMISSIVE = false;
  23506. this.SPECULAR = false;
  23507. this.BUMP = false;
  23508. this.PARALLAX = false;
  23509. this.PARALLAXOCCLUSION = false;
  23510. this.SPECULAROVERALPHA = false;
  23511. this.CLIPPLANE = false;
  23512. this.ALPHATEST = false;
  23513. this.ALPHAFROMDIFFUSE = false;
  23514. this.POINTSIZE = false;
  23515. this.FOG = false;
  23516. this.SPECULARTERM = false;
  23517. this.DIFFUSEFRESNEL = false;
  23518. this.OPACITYFRESNEL = false;
  23519. this.REFLECTIONFRESNEL = false;
  23520. this.REFRACTIONFRESNEL = false;
  23521. this.EMISSIVEFRESNEL = false;
  23522. this.FRESNEL = false;
  23523. this.NORMAL = false;
  23524. this.UV1 = false;
  23525. this.UV2 = false;
  23526. this.VERTEXCOLOR = false;
  23527. this.VERTEXALPHA = false;
  23528. this.NUM_BONE_INFLUENCERS = 0;
  23529. this.BonesPerMesh = 0;
  23530. this.INSTANCES = false;
  23531. this.GLOSSINESS = false;
  23532. this.ROUGHNESS = false;
  23533. this.EMISSIVEASILLUMINATION = false;
  23534. this.LINKEMISSIVEWITHDIFFUSE = false;
  23535. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23536. this.LIGHTMAP = false;
  23537. this.USELIGHTMAPASSHADOWMAP = false;
  23538. this.REFLECTIONMAP_3D = false;
  23539. this.REFLECTIONMAP_SPHERICAL = false;
  23540. this.REFLECTIONMAP_PLANAR = false;
  23541. this.REFLECTIONMAP_CUBIC = false;
  23542. this.REFLECTIONMAP_PROJECTION = false;
  23543. this.REFLECTIONMAP_SKYBOX = false;
  23544. this.REFLECTIONMAP_EXPLICIT = false;
  23545. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23546. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23547. this.INVERTCUBICMAP = false;
  23548. this.LOGARITHMICDEPTH = false;
  23549. this.REFRACTION = false;
  23550. this.REFRACTIONMAP_3D = false;
  23551. this.REFLECTIONOVERALPHA = false;
  23552. this.INVERTNORMALMAPX = false;
  23553. this.INVERTNORMALMAPY = false;
  23554. this.rebuild();
  23555. }
  23556. return StandardMaterialDefines;
  23557. })(BABYLON.MaterialDefines);
  23558. var StandardMaterial = (function (_super) {
  23559. __extends(StandardMaterial, _super);
  23560. function StandardMaterial(name, scene) {
  23561. var _this = this;
  23562. _super.call(this, name, scene);
  23563. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23564. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  23565. this.specularColor = new BABYLON.Color3(1, 1, 1);
  23566. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  23567. this.specularPower = 64;
  23568. this.useAlphaFromDiffuseTexture = false;
  23569. this.useEmissiveAsIllumination = false;
  23570. this.linkEmissiveWithDiffuse = false;
  23571. this.useReflectionFresnelFromSpecular = false;
  23572. this.useSpecularOverAlpha = false;
  23573. this.useReflectionOverAlpha = false;
  23574. this.disableLighting = false;
  23575. this.useParallax = false;
  23576. this.useParallaxOcclusion = false;
  23577. this.parallaxScaleBias = 0.05;
  23578. this.roughness = 0;
  23579. this.indexOfRefraction = 0.98;
  23580. this.invertRefractionY = true;
  23581. this.useLightmapAsShadowmap = false;
  23582. this.useGlossinessFromSpecularMapAlpha = false;
  23583. this.maxSimultaneousLights = 4;
  23584. /**
  23585. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  23586. */
  23587. this.invertNormalMapX = false;
  23588. /**
  23589. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  23590. */
  23591. this.invertNormalMapY = false;
  23592. this._renderTargets = new BABYLON.SmartArray(16);
  23593. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  23594. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  23595. this._defines = new StandardMaterialDefines();
  23596. this._cachedDefines = new StandardMaterialDefines();
  23597. this._cachedDefines.BonesPerMesh = -1;
  23598. this.getRenderTargetTextures = function () {
  23599. _this._renderTargets.reset();
  23600. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  23601. _this._renderTargets.push(_this.reflectionTexture);
  23602. }
  23603. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  23604. _this._renderTargets.push(_this.refractionTexture);
  23605. }
  23606. return _this._renderTargets;
  23607. };
  23608. }
  23609. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  23610. get: function () {
  23611. return this._useLogarithmicDepth;
  23612. },
  23613. set: function (value) {
  23614. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  23615. },
  23616. enumerable: true,
  23617. configurable: true
  23618. });
  23619. StandardMaterial.prototype.needAlphaBlending = function () {
  23620. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  23621. };
  23622. StandardMaterial.prototype.needAlphaTesting = function () {
  23623. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  23624. };
  23625. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  23626. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  23627. };
  23628. StandardMaterial.prototype.getAlphaTestTexture = function () {
  23629. return this.diffuseTexture;
  23630. };
  23631. // Methods
  23632. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  23633. if (!mesh) {
  23634. return true;
  23635. }
  23636. if (this._defines.INSTANCES !== useInstances) {
  23637. return false;
  23638. }
  23639. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  23640. return true;
  23641. }
  23642. return false;
  23643. };
  23644. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  23645. if (this.isFrozen) {
  23646. if (this._wasPreviouslyReady) {
  23647. return true;
  23648. }
  23649. }
  23650. var scene = this.getScene();
  23651. if (!this.checkReadyOnEveryCall) {
  23652. if (this._renderId === scene.getRenderId()) {
  23653. if (this._checkCache(scene, mesh, useInstances)) {
  23654. return true;
  23655. }
  23656. }
  23657. }
  23658. var engine = scene.getEngine();
  23659. var needNormals = false;
  23660. var needUVs = false;
  23661. this._defines.reset();
  23662. // Textures
  23663. if (scene.texturesEnabled) {
  23664. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23665. if (!this.diffuseTexture.isReady()) {
  23666. return false;
  23667. }
  23668. else {
  23669. needUVs = true;
  23670. this._defines.DIFFUSE = true;
  23671. }
  23672. }
  23673. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23674. if (!this.ambientTexture.isReady()) {
  23675. return false;
  23676. }
  23677. else {
  23678. needUVs = true;
  23679. this._defines.AMBIENT = true;
  23680. }
  23681. }
  23682. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23683. if (!this.opacityTexture.isReady()) {
  23684. return false;
  23685. }
  23686. else {
  23687. needUVs = true;
  23688. this._defines.OPACITY = true;
  23689. if (this.opacityTexture.getAlphaFromRGB) {
  23690. this._defines.OPACITYRGB = true;
  23691. }
  23692. }
  23693. }
  23694. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23695. if (!this.reflectionTexture.isReady()) {
  23696. return false;
  23697. }
  23698. else {
  23699. needNormals = true;
  23700. this._defines.REFLECTION = true;
  23701. if (this.roughness > 0) {
  23702. this._defines.ROUGHNESS = true;
  23703. }
  23704. if (this.useReflectionOverAlpha) {
  23705. this._defines.REFLECTIONOVERALPHA = true;
  23706. }
  23707. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  23708. this._defines.INVERTCUBICMAP = true;
  23709. }
  23710. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  23711. switch (this.reflectionTexture.coordinatesMode) {
  23712. case BABYLON.Texture.CUBIC_MODE:
  23713. case BABYLON.Texture.INVCUBIC_MODE:
  23714. this._defines.REFLECTIONMAP_CUBIC = true;
  23715. break;
  23716. case BABYLON.Texture.EXPLICIT_MODE:
  23717. this._defines.REFLECTIONMAP_EXPLICIT = true;
  23718. break;
  23719. case BABYLON.Texture.PLANAR_MODE:
  23720. this._defines.REFLECTIONMAP_PLANAR = true;
  23721. break;
  23722. case BABYLON.Texture.PROJECTION_MODE:
  23723. this._defines.REFLECTIONMAP_PROJECTION = true;
  23724. break;
  23725. case BABYLON.Texture.SKYBOX_MODE:
  23726. this._defines.REFLECTIONMAP_SKYBOX = true;
  23727. break;
  23728. case BABYLON.Texture.SPHERICAL_MODE:
  23729. this._defines.REFLECTIONMAP_SPHERICAL = true;
  23730. break;
  23731. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23732. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23733. break;
  23734. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23735. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23736. break;
  23737. }
  23738. }
  23739. }
  23740. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23741. if (!this.emissiveTexture.isReady()) {
  23742. return false;
  23743. }
  23744. else {
  23745. needUVs = true;
  23746. this._defines.EMISSIVE = true;
  23747. }
  23748. }
  23749. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23750. if (!this.lightmapTexture.isReady()) {
  23751. return false;
  23752. }
  23753. else {
  23754. needUVs = true;
  23755. this._defines.LIGHTMAP = true;
  23756. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23757. }
  23758. }
  23759. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23760. if (!this.specularTexture.isReady()) {
  23761. return false;
  23762. }
  23763. else {
  23764. needUVs = true;
  23765. this._defines.SPECULAR = true;
  23766. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23767. }
  23768. }
  23769. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23770. if (!this.bumpTexture.isReady()) {
  23771. return false;
  23772. }
  23773. else {
  23774. needUVs = true;
  23775. this._defines.BUMP = true;
  23776. if (this.useParallax) {
  23777. this._defines.PARALLAX = true;
  23778. if (this.useParallaxOcclusion) {
  23779. this._defines.PARALLAXOCCLUSION = true;
  23780. }
  23781. }
  23782. if (this.invertNormalMapX) {
  23783. this._defines.INVERTNORMALMAPX = true;
  23784. }
  23785. if (this.invertNormalMapY) {
  23786. this._defines.INVERTNORMALMAPY = true;
  23787. }
  23788. }
  23789. }
  23790. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23791. if (!this.refractionTexture.isReady()) {
  23792. return false;
  23793. }
  23794. else {
  23795. needUVs = true;
  23796. this._defines.REFRACTION = true;
  23797. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23798. }
  23799. }
  23800. }
  23801. // Effect
  23802. if (scene.clipPlane) {
  23803. this._defines.CLIPPLANE = true;
  23804. }
  23805. if (engine.getAlphaTesting()) {
  23806. this._defines.ALPHATEST = true;
  23807. }
  23808. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23809. this._defines.ALPHAFROMDIFFUSE = true;
  23810. }
  23811. if (this.useEmissiveAsIllumination) {
  23812. this._defines.EMISSIVEASILLUMINATION = true;
  23813. }
  23814. if (this.linkEmissiveWithDiffuse) {
  23815. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23816. }
  23817. if (this.useLogarithmicDepth) {
  23818. this._defines.LOGARITHMICDEPTH = true;
  23819. }
  23820. // Point size
  23821. if (this.pointsCloud || scene.forcePointsCloud) {
  23822. this._defines.POINTSIZE = true;
  23823. }
  23824. // Fog
  23825. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23826. this._defines.FOG = true;
  23827. }
  23828. if (scene.lightsEnabled && !this.disableLighting) {
  23829. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23830. }
  23831. if (StandardMaterial.FresnelEnabled) {
  23832. // Fresnel
  23833. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23834. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23835. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23836. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23837. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23838. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23839. this._defines.DIFFUSEFRESNEL = true;
  23840. }
  23841. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23842. this._defines.OPACITYFRESNEL = true;
  23843. }
  23844. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23845. this._defines.REFLECTIONFRESNEL = true;
  23846. if (this.useReflectionFresnelFromSpecular) {
  23847. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23848. }
  23849. }
  23850. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23851. this._defines.REFRACTIONFRESNEL = true;
  23852. }
  23853. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23854. this._defines.EMISSIVEFRESNEL = true;
  23855. }
  23856. needNormals = true;
  23857. this._defines.FRESNEL = true;
  23858. }
  23859. }
  23860. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23861. this._defines.SPECULAROVERALPHA = true;
  23862. }
  23863. // Attribs
  23864. if (mesh) {
  23865. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23866. this._defines.NORMAL = true;
  23867. }
  23868. if (needUVs) {
  23869. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23870. this._defines.UV1 = true;
  23871. }
  23872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23873. this._defines.UV2 = true;
  23874. }
  23875. }
  23876. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23877. this._defines.VERTEXCOLOR = true;
  23878. if (mesh.hasVertexAlpha) {
  23879. this._defines.VERTEXALPHA = true;
  23880. }
  23881. }
  23882. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23883. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23884. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23885. }
  23886. // Instances
  23887. if (useInstances) {
  23888. this._defines.INSTANCES = true;
  23889. }
  23890. }
  23891. // Get correct effect
  23892. if (!this._defines.isEqual(this._cachedDefines)) {
  23893. this._defines.cloneTo(this._cachedDefines);
  23894. scene.resetCachedMaterial();
  23895. // Fallbacks
  23896. var fallbacks = new BABYLON.EffectFallbacks();
  23897. if (this._defines.REFLECTION) {
  23898. fallbacks.addFallback(0, "REFLECTION");
  23899. }
  23900. if (this._defines.SPECULAR) {
  23901. fallbacks.addFallback(0, "SPECULAR");
  23902. }
  23903. if (this._defines.BUMP) {
  23904. fallbacks.addFallback(0, "BUMP");
  23905. }
  23906. if (this._defines.PARALLAX) {
  23907. fallbacks.addFallback(1, "PARALLAX");
  23908. }
  23909. if (this._defines.PARALLAXOCCLUSION) {
  23910. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23911. }
  23912. if (this._defines.SPECULAROVERALPHA) {
  23913. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23914. }
  23915. if (this._defines.FOG) {
  23916. fallbacks.addFallback(1, "FOG");
  23917. }
  23918. if (this._defines.POINTSIZE) {
  23919. fallbacks.addFallback(0, "POINTSIZE");
  23920. }
  23921. if (this._defines.LOGARITHMICDEPTH) {
  23922. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23923. }
  23924. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23925. if (this._defines.SPECULARTERM) {
  23926. fallbacks.addFallback(0, "SPECULARTERM");
  23927. }
  23928. if (this._defines.DIFFUSEFRESNEL) {
  23929. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23930. }
  23931. if (this._defines.OPACITYFRESNEL) {
  23932. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23933. }
  23934. if (this._defines.REFLECTIONFRESNEL) {
  23935. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23936. }
  23937. if (this._defines.EMISSIVEFRESNEL) {
  23938. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23939. }
  23940. if (this._defines.FRESNEL) {
  23941. fallbacks.addFallback(4, "FRESNEL");
  23942. }
  23943. //Attributes
  23944. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23945. if (this._defines.NORMAL) {
  23946. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23947. }
  23948. if (this._defines.UV1) {
  23949. attribs.push(BABYLON.VertexBuffer.UVKind);
  23950. }
  23951. if (this._defines.UV2) {
  23952. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23953. }
  23954. if (this._defines.VERTEXCOLOR) {
  23955. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23956. }
  23957. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23958. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23959. // Legacy browser patch
  23960. var shaderName = "default";
  23961. if (!scene.getEngine().getCaps().standardDerivatives) {
  23962. shaderName = "legacydefault";
  23963. }
  23964. var join = this._defines.toString();
  23965. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23966. "vFogInfos", "vFogColor", "pointSize",
  23967. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23968. "mBones",
  23969. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23970. "depthValues",
  23971. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23972. "logarithmicDepthConstant"
  23973. ];
  23974. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  23975. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  23976. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23977. }
  23978. if (!this._effect.isReady()) {
  23979. return false;
  23980. }
  23981. this._renderId = scene.getRenderId();
  23982. this._wasPreviouslyReady = true;
  23983. if (mesh) {
  23984. if (!mesh._materialDefines) {
  23985. mesh._materialDefines = new StandardMaterialDefines();
  23986. }
  23987. this._defines.cloneTo(mesh._materialDefines);
  23988. }
  23989. return true;
  23990. };
  23991. StandardMaterial.prototype.unbind = function () {
  23992. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23993. this._effect.setTexture("reflection2DSampler", null);
  23994. }
  23995. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23996. this._effect.setTexture("refraction2DSampler", null);
  23997. }
  23998. _super.prototype.unbind.call(this);
  23999. };
  24000. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24001. this._effect.setMatrix("world", world);
  24002. };
  24003. StandardMaterial.prototype.bind = function (world, mesh) {
  24004. var scene = this.getScene();
  24005. // Matrices
  24006. this.bindOnlyWorldMatrix(world);
  24007. // Bones
  24008. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24009. if (scene.getCachedMaterial() !== this) {
  24010. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24011. if (StandardMaterial.FresnelEnabled) {
  24012. // Fresnel
  24013. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24014. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24015. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24016. }
  24017. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24018. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24019. }
  24020. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24021. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24022. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24023. }
  24024. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24025. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24026. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24027. }
  24028. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24029. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24030. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24031. }
  24032. }
  24033. // Textures
  24034. if (scene.texturesEnabled) {
  24035. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24036. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24037. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24038. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24039. }
  24040. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24041. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24042. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24043. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24044. }
  24045. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24046. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24047. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24048. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24049. }
  24050. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24051. if (this.reflectionTexture.isCube) {
  24052. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24053. }
  24054. else {
  24055. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24056. }
  24057. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24058. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24059. }
  24060. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24061. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24062. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24063. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24064. }
  24065. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24066. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24067. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24068. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24069. }
  24070. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24071. this._effect.setTexture("specularSampler", this.specularTexture);
  24072. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24073. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24074. }
  24075. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24076. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24077. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24078. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24079. }
  24080. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24081. var depth = 1.0;
  24082. if (this.refractionTexture.isCube) {
  24083. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24084. }
  24085. else {
  24086. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24087. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24088. if (this.refractionTexture.depth) {
  24089. depth = this.refractionTexture.depth;
  24090. }
  24091. }
  24092. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24093. }
  24094. }
  24095. // Clip plane
  24096. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24097. // Point size
  24098. if (this.pointsCloud) {
  24099. this._effect.setFloat("pointSize", this.pointSize);
  24100. }
  24101. // Colors
  24102. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24103. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24104. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24105. if (this._defines.SPECULARTERM) {
  24106. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24107. }
  24108. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24109. }
  24110. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24111. // Diffuse
  24112. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24113. // Lights
  24114. if (scene.lightsEnabled && !this.disableLighting) {
  24115. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24116. }
  24117. // View
  24118. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24119. this._effect.setMatrix("view", scene.getViewMatrix());
  24120. }
  24121. // Fog
  24122. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24123. // Log. depth
  24124. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24125. }
  24126. _super.prototype.bind.call(this, world, mesh);
  24127. };
  24128. StandardMaterial.prototype.getAnimatables = function () {
  24129. var results = [];
  24130. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24131. results.push(this.diffuseTexture);
  24132. }
  24133. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24134. results.push(this.ambientTexture);
  24135. }
  24136. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24137. results.push(this.opacityTexture);
  24138. }
  24139. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24140. results.push(this.reflectionTexture);
  24141. }
  24142. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24143. results.push(this.emissiveTexture);
  24144. }
  24145. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24146. results.push(this.specularTexture);
  24147. }
  24148. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24149. results.push(this.bumpTexture);
  24150. }
  24151. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24152. results.push(this.lightmapTexture);
  24153. }
  24154. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24155. results.push(this.refractionTexture);
  24156. }
  24157. return results;
  24158. };
  24159. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24160. if (forceDisposeTextures) {
  24161. if (this.diffuseTexture) {
  24162. this.diffuseTexture.dispose();
  24163. }
  24164. if (this.ambientTexture) {
  24165. this.ambientTexture.dispose();
  24166. }
  24167. if (this.opacityTexture) {
  24168. this.opacityTexture.dispose();
  24169. }
  24170. if (this.reflectionTexture) {
  24171. this.reflectionTexture.dispose();
  24172. }
  24173. if (this.emissiveTexture) {
  24174. this.emissiveTexture.dispose();
  24175. }
  24176. if (this.specularTexture) {
  24177. this.specularTexture.dispose();
  24178. }
  24179. if (this.bumpTexture) {
  24180. this.bumpTexture.dispose();
  24181. }
  24182. if (this.lightmapTexture) {
  24183. this.lightmapTexture.dispose();
  24184. }
  24185. if (this.refractionTexture) {
  24186. this.refractionTexture.dispose();
  24187. }
  24188. }
  24189. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24190. };
  24191. StandardMaterial.prototype.clone = function (name) {
  24192. var _this = this;
  24193. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24194. };
  24195. StandardMaterial.prototype.serialize = function () {
  24196. return BABYLON.SerializationHelper.Serialize(this);
  24197. };
  24198. // Statics
  24199. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24200. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24201. };
  24202. // Flags used to enable or disable a type of texture for all Standard Materials
  24203. StandardMaterial.DiffuseTextureEnabled = true;
  24204. StandardMaterial.AmbientTextureEnabled = true;
  24205. StandardMaterial.OpacityTextureEnabled = true;
  24206. StandardMaterial.ReflectionTextureEnabled = true;
  24207. StandardMaterial.EmissiveTextureEnabled = true;
  24208. StandardMaterial.SpecularTextureEnabled = true;
  24209. StandardMaterial.BumpTextureEnabled = true;
  24210. StandardMaterial.FresnelEnabled = true;
  24211. StandardMaterial.LightmapTextureEnabled = true;
  24212. StandardMaterial.RefractionTextureEnabled = true;
  24213. __decorate([
  24214. BABYLON.serializeAsTexture()
  24215. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24216. __decorate([
  24217. BABYLON.serializeAsTexture()
  24218. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24219. __decorate([
  24220. BABYLON.serializeAsTexture()
  24221. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24222. __decorate([
  24223. BABYLON.serializeAsTexture()
  24224. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24225. __decorate([
  24226. BABYLON.serializeAsTexture()
  24227. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24228. __decorate([
  24229. BABYLON.serializeAsTexture()
  24230. ], StandardMaterial.prototype, "specularTexture", void 0);
  24231. __decorate([
  24232. BABYLON.serializeAsTexture()
  24233. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24234. __decorate([
  24235. BABYLON.serializeAsTexture()
  24236. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24237. __decorate([
  24238. BABYLON.serializeAsTexture()
  24239. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24240. __decorate([
  24241. BABYLON.serializeAsColor3("ambient")
  24242. ], StandardMaterial.prototype, "ambientColor", void 0);
  24243. __decorate([
  24244. BABYLON.serializeAsColor3("diffuse")
  24245. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24246. __decorate([
  24247. BABYLON.serializeAsColor3("specular")
  24248. ], StandardMaterial.prototype, "specularColor", void 0);
  24249. __decorate([
  24250. BABYLON.serializeAsColor3("emissive")
  24251. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24252. __decorate([
  24253. BABYLON.serialize()
  24254. ], StandardMaterial.prototype, "specularPower", void 0);
  24255. __decorate([
  24256. BABYLON.serialize()
  24257. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24258. __decorate([
  24259. BABYLON.serialize()
  24260. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24261. __decorate([
  24262. BABYLON.serialize()
  24263. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24264. __decorate([
  24265. BABYLON.serialize()
  24266. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24267. __decorate([
  24268. BABYLON.serialize()
  24269. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24270. __decorate([
  24271. BABYLON.serialize()
  24272. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24273. __decorate([
  24274. BABYLON.serialize()
  24275. ], StandardMaterial.prototype, "disableLighting", void 0);
  24276. __decorate([
  24277. BABYLON.serialize()
  24278. ], StandardMaterial.prototype, "useParallax", void 0);
  24279. __decorate([
  24280. BABYLON.serialize()
  24281. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24282. __decorate([
  24283. BABYLON.serialize()
  24284. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24285. __decorate([
  24286. BABYLON.serialize()
  24287. ], StandardMaterial.prototype, "roughness", void 0);
  24288. __decorate([
  24289. BABYLON.serialize()
  24290. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24291. __decorate([
  24292. BABYLON.serialize()
  24293. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24294. __decorate([
  24295. BABYLON.serialize()
  24296. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24297. __decorate([
  24298. BABYLON.serializeAsFresnelParameters()
  24299. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24300. __decorate([
  24301. BABYLON.serializeAsFresnelParameters()
  24302. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24303. __decorate([
  24304. BABYLON.serializeAsFresnelParameters()
  24305. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24306. __decorate([
  24307. BABYLON.serializeAsFresnelParameters()
  24308. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24309. __decorate([
  24310. BABYLON.serializeAsFresnelParameters()
  24311. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24312. __decorate([
  24313. BABYLON.serialize()
  24314. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24315. __decorate([
  24316. BABYLON.serialize()
  24317. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24318. __decorate([
  24319. BABYLON.serialize()
  24320. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24321. __decorate([
  24322. BABYLON.serialize()
  24323. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24324. __decorate([
  24325. BABYLON.serialize()
  24326. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24327. return StandardMaterial;
  24328. })(BABYLON.Material);
  24329. BABYLON.StandardMaterial = StandardMaterial;
  24330. })(BABYLON || (BABYLON = {}));
  24331. var BABYLON;
  24332. (function (BABYLON) {
  24333. var MultiMaterial = (function (_super) {
  24334. __extends(MultiMaterial, _super);
  24335. function MultiMaterial(name, scene) {
  24336. _super.call(this, name, scene, true);
  24337. this.subMaterials = new Array();
  24338. scene.multiMaterials.push(this);
  24339. }
  24340. // Properties
  24341. MultiMaterial.prototype.getSubMaterial = function (index) {
  24342. if (index < 0 || index >= this.subMaterials.length) {
  24343. return this.getScene().defaultMaterial;
  24344. }
  24345. return this.subMaterials[index];
  24346. };
  24347. // Methods
  24348. MultiMaterial.prototype.isReady = function (mesh) {
  24349. for (var index = 0; index < this.subMaterials.length; index++) {
  24350. var subMaterial = this.subMaterials[index];
  24351. if (subMaterial) {
  24352. if (!this.subMaterials[index].isReady(mesh)) {
  24353. return false;
  24354. }
  24355. }
  24356. }
  24357. return true;
  24358. };
  24359. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24360. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24361. for (var index = 0; index < this.subMaterials.length; index++) {
  24362. var subMaterial = null;
  24363. if (cloneChildren) {
  24364. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24365. }
  24366. else {
  24367. subMaterial = this.subMaterials[index];
  24368. }
  24369. newMultiMaterial.subMaterials.push(subMaterial);
  24370. }
  24371. return newMultiMaterial;
  24372. };
  24373. MultiMaterial.prototype.serialize = function () {
  24374. var serializationObject = {};
  24375. serializationObject.name = this.name;
  24376. serializationObject.id = this.id;
  24377. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24378. serializationObject.materials = [];
  24379. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24380. var subMat = this.subMaterials[matIndex];
  24381. if (subMat) {
  24382. serializationObject.materials.push(subMat.id);
  24383. }
  24384. else {
  24385. serializationObject.materials.push(null);
  24386. }
  24387. }
  24388. return serializationObject;
  24389. };
  24390. return MultiMaterial;
  24391. })(BABYLON.Material);
  24392. BABYLON.MultiMaterial = MultiMaterial;
  24393. })(BABYLON || (BABYLON = {}));
  24394. var BABYLON;
  24395. (function (BABYLON) {
  24396. var SceneLoader = (function () {
  24397. function SceneLoader() {
  24398. }
  24399. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24400. get: function () {
  24401. return 0;
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24407. get: function () {
  24408. return 1;
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24414. get: function () {
  24415. return 2;
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24421. get: function () {
  24422. return 3;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24428. get: function () {
  24429. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24430. },
  24431. set: function (value) {
  24432. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24438. get: function () {
  24439. return SceneLoader._ShowLoadingScreen;
  24440. },
  24441. set: function (value) {
  24442. SceneLoader._ShowLoadingScreen = value;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(SceneLoader, "loggingLevel", {
  24448. get: function () {
  24449. return SceneLoader._loggingLevel;
  24450. },
  24451. set: function (value) {
  24452. SceneLoader._loggingLevel = value;
  24453. },
  24454. enumerable: true,
  24455. configurable: true
  24456. });
  24457. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24458. var dotPosition = sceneFilename.lastIndexOf(".");
  24459. var queryStringPosition = sceneFilename.indexOf("?");
  24460. if (queryStringPosition === -1) {
  24461. queryStringPosition = sceneFilename.length;
  24462. }
  24463. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24464. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24465. var plugin = this._registeredPlugins[index];
  24466. if (plugin.extensions.indexOf(extension) !== -1) {
  24467. return plugin;
  24468. }
  24469. }
  24470. return this._registeredPlugins[0];
  24471. };
  24472. // Public functions
  24473. SceneLoader.GetPluginForExtension = function (extension) {
  24474. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24475. var plugin = this._registeredPlugins[index];
  24476. if (plugin.extensions.indexOf(extension) !== -1) {
  24477. return plugin;
  24478. }
  24479. }
  24480. return null;
  24481. };
  24482. SceneLoader.RegisterPlugin = function (plugin) {
  24483. plugin.extensions = plugin.extensions.toLowerCase();
  24484. SceneLoader._registeredPlugins.push(plugin);
  24485. };
  24486. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24487. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24488. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24489. return;
  24490. }
  24491. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24492. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24493. return;
  24494. }
  24495. var loadingToken = {};
  24496. scene._addPendingData(loadingToken);
  24497. var manifestChecked = function (success) {
  24498. scene.database = database;
  24499. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24500. var importMeshFromData = function (data) {
  24501. var meshes = [];
  24502. var particleSystems = [];
  24503. var skeletons = [];
  24504. try {
  24505. if (plugin.importMesh) {
  24506. var syncedPlugin = plugin;
  24507. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24508. if (onerror) {
  24509. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24510. }
  24511. scene._removePendingData(loadingToken);
  24512. return;
  24513. }
  24514. if (onsuccess) {
  24515. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24516. onsuccess(meshes, particleSystems, skeletons);
  24517. scene._removePendingData(loadingToken);
  24518. }
  24519. }
  24520. else {
  24521. var asyncedPlugin = plugin;
  24522. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24523. if (onsuccess) {
  24524. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24525. onsuccess(meshes, particleSystems, skeletons);
  24526. scene._removePendingData(loadingToken);
  24527. }
  24528. }, function () {
  24529. if (onerror) {
  24530. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24531. }
  24532. scene._removePendingData(loadingToken);
  24533. });
  24534. }
  24535. }
  24536. catch (e) {
  24537. if (onerror) {
  24538. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24539. }
  24540. scene._removePendingData(loadingToken);
  24541. }
  24542. };
  24543. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24544. // Direct load
  24545. importMeshFromData(sceneFilename.substr(5));
  24546. return;
  24547. }
  24548. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24549. importMeshFromData(data);
  24550. }, progressCallBack, database);
  24551. };
  24552. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24553. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24554. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24555. }
  24556. else {
  24557. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24558. manifestChecked(true);
  24559. }
  24560. };
  24561. /**
  24562. * Load a scene
  24563. * @param rootUrl a string that defines the root url for scene and resources
  24564. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24565. * @param engine is the instance of BABYLON.Engine to use to create the scene
  24566. */
  24567. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  24568. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  24569. };
  24570. /**
  24571. * Append a scene
  24572. * @param rootUrl a string that defines the root url for scene and resources
  24573. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24574. * @param scene is the instance of BABYLON.Scene to append to
  24575. */
  24576. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24577. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24578. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24579. return;
  24580. }
  24581. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  24582. var database;
  24583. var loadingToken = {};
  24584. scene._addPendingData(loadingToken);
  24585. if (SceneLoader.ShowLoadingScreen) {
  24586. scene.getEngine().displayLoadingUI();
  24587. }
  24588. var loadSceneFromData = function (data) {
  24589. scene.database = database;
  24590. if (plugin.load) {
  24591. var syncedPlugin = plugin;
  24592. if (!syncedPlugin.load(scene, data, rootUrl)) {
  24593. if (onerror) {
  24594. onerror(scene);
  24595. }
  24596. scene._removePendingData(loadingToken);
  24597. scene.getEngine().hideLoadingUI();
  24598. return;
  24599. }
  24600. if (onsuccess) {
  24601. onsuccess(scene);
  24602. }
  24603. scene._removePendingData(loadingToken);
  24604. }
  24605. else {
  24606. var asyncedPlugin = plugin;
  24607. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  24608. if (onsuccess) {
  24609. onsuccess(scene);
  24610. }
  24611. }, function () {
  24612. if (onerror) {
  24613. onerror(scene);
  24614. }
  24615. scene._removePendingData(loadingToken);
  24616. scene.getEngine().hideLoadingUI();
  24617. });
  24618. }
  24619. if (SceneLoader.ShowLoadingScreen) {
  24620. scene.executeWhenReady(function () {
  24621. scene.getEngine().hideLoadingUI();
  24622. });
  24623. }
  24624. };
  24625. var manifestChecked = function (success) {
  24626. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  24627. };
  24628. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24629. // Direct load
  24630. loadSceneFromData(sceneFilename.substr(5));
  24631. return;
  24632. }
  24633. if (rootUrl.indexOf("file:") === -1) {
  24634. if (scene.getEngine().enableOfflineSupport) {
  24635. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24636. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24637. }
  24638. else {
  24639. manifestChecked(true);
  24640. }
  24641. }
  24642. else {
  24643. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  24644. }
  24645. };
  24646. // Flags
  24647. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  24648. SceneLoader._ShowLoadingScreen = true;
  24649. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  24650. // Members
  24651. SceneLoader._registeredPlugins = new Array();
  24652. return SceneLoader;
  24653. })();
  24654. BABYLON.SceneLoader = SceneLoader;
  24655. ;
  24656. })(BABYLON || (BABYLON = {}));
  24657. var BABYLON;
  24658. (function (BABYLON) {
  24659. var Internals;
  24660. (function (Internals) {
  24661. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  24662. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24663. var parsedMaterial = parsedData.materials[index];
  24664. if (parsedMaterial.id === id) {
  24665. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24666. }
  24667. }
  24668. return null;
  24669. };
  24670. var isDescendantOf = function (mesh, names, hierarchyIds) {
  24671. names = (names instanceof Array) ? names : [names];
  24672. for (var i in names) {
  24673. if (mesh.name === names[i]) {
  24674. hierarchyIds.push(mesh.id);
  24675. return true;
  24676. }
  24677. }
  24678. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  24679. hierarchyIds.push(mesh.id);
  24680. return true;
  24681. }
  24682. return false;
  24683. };
  24684. var logOperation = function (operation, producer) {
  24685. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  24686. };
  24687. BABYLON.SceneLoader.RegisterPlugin({
  24688. extensions: ".babylon",
  24689. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  24690. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24691. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24692. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24693. // and avoid problems with multiple concurrent .babylon loads.
  24694. var log = "importMesh has failed JSON parse";
  24695. try {
  24696. var parsedData = JSON.parse(data);
  24697. log = "";
  24698. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24699. var loadedSkeletonsIds = [];
  24700. var loadedMaterialsIds = [];
  24701. var hierarchyIds = [];
  24702. var index;
  24703. var cache;
  24704. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24705. var parsedMesh = parsedData.meshes[index];
  24706. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  24707. if (meshesNames instanceof Array) {
  24708. // Remove found mesh name from list.
  24709. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  24710. }
  24711. //Geometry?
  24712. if (parsedMesh.geometryId) {
  24713. //does the file contain geometries?
  24714. if (parsedData.geometries) {
  24715. //find the correct geometry and add it to the scene
  24716. var found = false;
  24717. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  24718. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  24719. return;
  24720. }
  24721. else {
  24722. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  24723. if (parsedGeometryData.id === parsedMesh.geometryId) {
  24724. switch (geometryType) {
  24725. case "boxes":
  24726. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  24727. break;
  24728. case "spheres":
  24729. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  24730. break;
  24731. case "cylinders":
  24732. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  24733. break;
  24734. case "toruses":
  24735. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  24736. break;
  24737. case "grounds":
  24738. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  24739. break;
  24740. case "planes":
  24741. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  24742. break;
  24743. case "torusKnots":
  24744. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24745. break;
  24746. case "vertexData":
  24747. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24748. break;
  24749. }
  24750. found = true;
  24751. }
  24752. });
  24753. }
  24754. });
  24755. if (!found) {
  24756. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24757. }
  24758. }
  24759. }
  24760. // Material ?
  24761. if (parsedMesh.materialId) {
  24762. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24763. if (!materialFound && parsedData.multiMaterials) {
  24764. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24765. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24766. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24767. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24768. var subMatId = parsedMultiMaterial.materials[matIndex];
  24769. loadedMaterialsIds.push(subMatId);
  24770. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24771. log += "\n\tMaterial " + mat.toString(fullDetails);
  24772. }
  24773. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24774. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24775. materialFound = true;
  24776. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24777. break;
  24778. }
  24779. }
  24780. }
  24781. if (!materialFound) {
  24782. loadedMaterialsIds.push(parsedMesh.materialId);
  24783. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24784. if (!mat) {
  24785. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24786. }
  24787. else {
  24788. log += "\n\tMaterial " + mat.toString(fullDetails);
  24789. }
  24790. }
  24791. }
  24792. // Skeleton ?
  24793. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24794. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24795. if (!skeletonAlreadyLoaded) {
  24796. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24797. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24798. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24799. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24800. skeletons.push(skeleton);
  24801. loadedSkeletonsIds.push(parsedSkeleton.id);
  24802. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24803. }
  24804. }
  24805. }
  24806. }
  24807. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24808. meshes.push(mesh);
  24809. log += "\n\tMesh " + mesh.toString(fullDetails);
  24810. }
  24811. }
  24812. // Connecting parents
  24813. var currentMesh;
  24814. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24815. currentMesh = scene.meshes[index];
  24816. if (currentMesh._waitingParentId) {
  24817. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24818. currentMesh._waitingParentId = undefined;
  24819. }
  24820. }
  24821. // freeze and compute world matrix application
  24822. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24823. currentMesh = scene.meshes[index];
  24824. if (currentMesh._waitingFreezeWorldMatrix) {
  24825. currentMesh.freezeWorldMatrix();
  24826. currentMesh._waitingFreezeWorldMatrix = undefined;
  24827. }
  24828. else {
  24829. currentMesh.computeWorldMatrix(true);
  24830. }
  24831. }
  24832. // Particles
  24833. if (parsedData.particleSystems) {
  24834. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24835. var parsedParticleSystem = parsedData.particleSystems[index];
  24836. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24837. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24838. }
  24839. }
  24840. }
  24841. return true;
  24842. }
  24843. catch (err) {
  24844. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24845. log = null;
  24846. throw err;
  24847. }
  24848. finally {
  24849. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24850. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24851. }
  24852. }
  24853. },
  24854. load: function (scene, data, rootUrl) {
  24855. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24856. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24857. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24858. // and avoid problems with multiple concurrent .babylon loads.
  24859. var log = "importScene has failed JSON parse";
  24860. try {
  24861. var parsedData = JSON.parse(data);
  24862. log = "";
  24863. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24864. // Scene
  24865. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24866. scene.autoClear = parsedData.autoClear;
  24867. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24868. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24869. if (parsedData.gravity) {
  24870. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24871. }
  24872. // Fog
  24873. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24874. scene.fogMode = parsedData.fogMode;
  24875. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24876. scene.fogStart = parsedData.fogStart;
  24877. scene.fogEnd = parsedData.fogEnd;
  24878. scene.fogDensity = parsedData.fogDensity;
  24879. log += "\tFog mode for scene: ";
  24880. switch (scene.fogMode) {
  24881. // getters not compiling, so using hardcoded
  24882. case 1:
  24883. log += "exp\n";
  24884. break;
  24885. case 2:
  24886. log += "exp2\n";
  24887. break;
  24888. case 3:
  24889. log += "linear\n";
  24890. break;
  24891. }
  24892. }
  24893. //Physics
  24894. if (parsedData.physicsEnabled) {
  24895. var physicsPlugin;
  24896. if (parsedData.physicsEngine === "cannon") {
  24897. physicsPlugin = new BABYLON.CannonJSPlugin();
  24898. }
  24899. else if (parsedData.physicsEngine === "oimo") {
  24900. physicsPlugin = new BABYLON.OimoJSPlugin();
  24901. }
  24902. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24903. //else - default engine, which is currently oimo
  24904. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24905. scene.enablePhysics(physicsGravity, physicsPlugin);
  24906. }
  24907. //collisions, if defined. otherwise, default is true
  24908. if (parsedData.collisionsEnabled != undefined) {
  24909. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24910. }
  24911. scene.workerCollisions = !!parsedData.workerCollisions;
  24912. var index;
  24913. var cache;
  24914. // Lights
  24915. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24916. var parsedLight = parsedData.lights[index];
  24917. var light = BABYLON.Light.Parse(parsedLight, scene);
  24918. log += (index === 0 ? "\n\tLights:" : "");
  24919. log += "\n\t\t" + light.toString(fullDetails);
  24920. }
  24921. // Animations
  24922. if (parsedData.animations) {
  24923. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24924. var parsedAnimation = parsedData.animations[index];
  24925. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24926. scene.animations.push(animation);
  24927. log += (index === 0 ? "\n\tAnimations:" : "");
  24928. log += "\n\t\t" + animation.toString(fullDetails);
  24929. }
  24930. }
  24931. if (parsedData.autoAnimate) {
  24932. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24933. }
  24934. // Materials
  24935. if (parsedData.materials) {
  24936. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24937. var parsedMaterial = parsedData.materials[index];
  24938. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24939. log += (index === 0 ? "\n\tMaterials:" : "");
  24940. log += "\n\t\t" + mat.toString(fullDetails);
  24941. }
  24942. }
  24943. if (parsedData.multiMaterials) {
  24944. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24945. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24946. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24947. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24948. log += "\n\t\t" + mmat.toString(fullDetails);
  24949. }
  24950. }
  24951. // Skeletons
  24952. if (parsedData.skeletons) {
  24953. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24954. var parsedSkeleton = parsedData.skeletons[index];
  24955. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24956. log += (index === 0 ? "\n\tSkeletons:" : "");
  24957. log += "\n\t\t" + skeleton.toString(fullDetails);
  24958. }
  24959. }
  24960. // Geometries
  24961. var geometries = parsedData.geometries;
  24962. if (geometries) {
  24963. // Boxes
  24964. var boxes = geometries.boxes;
  24965. if (boxes) {
  24966. for (index = 0, cache = boxes.length; index < cache; index++) {
  24967. var parsedBox = boxes[index];
  24968. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24969. }
  24970. }
  24971. // Spheres
  24972. var spheres = geometries.spheres;
  24973. if (spheres) {
  24974. for (index = 0, cache = spheres.length; index < cache; index++) {
  24975. var parsedSphere = spheres[index];
  24976. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24977. }
  24978. }
  24979. // Cylinders
  24980. var cylinders = geometries.cylinders;
  24981. if (cylinders) {
  24982. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24983. var parsedCylinder = cylinders[index];
  24984. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24985. }
  24986. }
  24987. // Toruses
  24988. var toruses = geometries.toruses;
  24989. if (toruses) {
  24990. for (index = 0, cache = toruses.length; index < cache; index++) {
  24991. var parsedTorus = toruses[index];
  24992. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24993. }
  24994. }
  24995. // Grounds
  24996. var grounds = geometries.grounds;
  24997. if (grounds) {
  24998. for (index = 0, cache = grounds.length; index < cache; index++) {
  24999. var parsedGround = grounds[index];
  25000. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25001. }
  25002. }
  25003. // Planes
  25004. var planes = geometries.planes;
  25005. if (planes) {
  25006. for (index = 0, cache = planes.length; index < cache; index++) {
  25007. var parsedPlane = planes[index];
  25008. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25009. }
  25010. }
  25011. // TorusKnots
  25012. var torusKnots = geometries.torusKnots;
  25013. if (torusKnots) {
  25014. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25015. var parsedTorusKnot = torusKnots[index];
  25016. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25017. }
  25018. }
  25019. // VertexData
  25020. var vertexData = geometries.vertexData;
  25021. if (vertexData) {
  25022. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25023. var parsedVertexData = vertexData[index];
  25024. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25025. }
  25026. }
  25027. }
  25028. // Meshes
  25029. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25030. var parsedMesh = parsedData.meshes[index];
  25031. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25032. log += (index === 0 ? "\n\tMeshes:" : "");
  25033. log += "\n\t\t" + mesh.toString(fullDetails);
  25034. }
  25035. // Cameras
  25036. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25037. var parsedCamera = parsedData.cameras[index];
  25038. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25039. log += (index === 0 ? "\n\tCameras:" : "");
  25040. log += "\n\t\t" + camera.toString(fullDetails);
  25041. }
  25042. if (parsedData.activeCameraID) {
  25043. scene.setActiveCameraByID(parsedData.activeCameraID);
  25044. }
  25045. // Browsing all the graph to connect the dots
  25046. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25047. var camera = scene.cameras[index];
  25048. if (camera._waitingParentId) {
  25049. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25050. camera._waitingParentId = undefined;
  25051. }
  25052. }
  25053. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25054. var light = scene.lights[index];
  25055. if (light._waitingParentId) {
  25056. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25057. light._waitingParentId = undefined;
  25058. }
  25059. }
  25060. // Sounds
  25061. var loadedSounds = [];
  25062. var loadedSound;
  25063. if (BABYLON.AudioEngine && parsedData.sounds) {
  25064. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25065. var parsedSound = parsedData.sounds[index];
  25066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25067. if (!parsedSound.url)
  25068. parsedSound.url = parsedSound.name;
  25069. if (!loadedSounds[parsedSound.url]) {
  25070. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25071. loadedSounds[parsedSound.url] = loadedSound;
  25072. }
  25073. else {
  25074. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25075. }
  25076. }
  25077. else {
  25078. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25079. }
  25080. }
  25081. }
  25082. loadedSounds = [];
  25083. // Connect parents & children and parse actions
  25084. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25085. var mesh = scene.meshes[index];
  25086. if (mesh._waitingParentId) {
  25087. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25088. mesh._waitingParentId = undefined;
  25089. }
  25090. if (mesh._waitingActions) {
  25091. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25092. mesh._waitingActions = undefined;
  25093. }
  25094. }
  25095. // freeze world matrix application
  25096. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25097. var currentMesh = scene.meshes[index];
  25098. if (currentMesh._waitingFreezeWorldMatrix) {
  25099. currentMesh.freezeWorldMatrix();
  25100. currentMesh._waitingFreezeWorldMatrix = undefined;
  25101. }
  25102. else {
  25103. currentMesh.computeWorldMatrix(true);
  25104. }
  25105. }
  25106. // Particles Systems
  25107. if (parsedData.particleSystems) {
  25108. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25109. var parsedParticleSystem = parsedData.particleSystems[index];
  25110. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25111. }
  25112. }
  25113. // Lens flares
  25114. if (parsedData.lensFlareSystems) {
  25115. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25116. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25117. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25118. }
  25119. }
  25120. // Shadows
  25121. if (parsedData.shadowGenerators) {
  25122. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25123. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25124. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25125. }
  25126. }
  25127. // Actions (scene)
  25128. if (parsedData.actions) {
  25129. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25130. }
  25131. // Finish
  25132. return true;
  25133. }
  25134. catch (err) {
  25135. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25136. log = null;
  25137. throw err;
  25138. }
  25139. finally {
  25140. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25141. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25142. }
  25143. }
  25144. }
  25145. });
  25146. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25147. })(BABYLON || (BABYLON = {}));
  25148. var BABYLON;
  25149. (function (BABYLON) {
  25150. var SpriteManager = (function () {
  25151. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25153. this.name = name;
  25154. this.cellSize = cellSize;
  25155. this.sprites = new Array();
  25156. this.renderingGroupId = 0;
  25157. this.layerMask = 0x0FFFFFFF;
  25158. this.fogEnabled = true;
  25159. this.isPickable = false;
  25160. /**
  25161. * An event triggered when the manager is disposed.
  25162. * @type {BABYLON.Observable}
  25163. */
  25164. this.onDisposeObservable = new BABYLON.Observable();
  25165. this._vertexBuffers = {};
  25166. this._capacity = capacity;
  25167. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25168. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25169. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25170. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25171. this._scene = scene;
  25172. this._scene.spriteManagers.push(this);
  25173. var indices = [];
  25174. var index = 0;
  25175. for (var count = 0; count < capacity; count++) {
  25176. indices.push(index);
  25177. indices.push(index + 1);
  25178. indices.push(index + 2);
  25179. indices.push(index);
  25180. indices.push(index + 2);
  25181. indices.push(index + 3);
  25182. index += 4;
  25183. }
  25184. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25185. // VBO
  25186. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25187. this._vertexData = new Float32Array(capacity * 16 * 4);
  25188. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25189. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25190. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25191. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25192. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25194. this._vertexBuffers["options"] = options;
  25195. this._vertexBuffers["cellInfo"] = cellInfo;
  25196. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25197. // Effects
  25198. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25199. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25200. }
  25201. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25202. set: function (callback) {
  25203. if (this._onDisposeObserver) {
  25204. this.onDisposeObservable.remove(this._onDisposeObserver);
  25205. }
  25206. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25207. },
  25208. enumerable: true,
  25209. configurable: true
  25210. });
  25211. Object.defineProperty(SpriteManager.prototype, "texture", {
  25212. get: function () {
  25213. return this._spriteTexture;
  25214. },
  25215. set: function (value) {
  25216. this._spriteTexture = value;
  25217. },
  25218. enumerable: true,
  25219. configurable: true
  25220. });
  25221. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25222. var arrayOffset = index * 16;
  25223. if (offsetX === 0)
  25224. offsetX = this._epsilon;
  25225. else if (offsetX === 1)
  25226. offsetX = 1 - this._epsilon;
  25227. if (offsetY === 0)
  25228. offsetY = this._epsilon;
  25229. else if (offsetY === 1)
  25230. offsetY = 1 - this._epsilon;
  25231. this._vertexData[arrayOffset] = sprite.position.x;
  25232. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25233. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25234. this._vertexData[arrayOffset + 3] = sprite.angle;
  25235. this._vertexData[arrayOffset + 4] = sprite.width;
  25236. this._vertexData[arrayOffset + 5] = sprite.height;
  25237. this._vertexData[arrayOffset + 6] = offsetX;
  25238. this._vertexData[arrayOffset + 7] = offsetY;
  25239. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25240. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25241. var offset = (sprite.cellIndex / rowSize) >> 0;
  25242. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25243. this._vertexData[arrayOffset + 11] = offset;
  25244. // Color
  25245. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25246. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25247. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25248. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25249. };
  25250. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25251. var count = Math.min(this._capacity, this.sprites.length);
  25252. var min = BABYLON.Vector3.Zero();
  25253. var max = BABYLON.Vector3.Zero();
  25254. var distance = Number.MAX_VALUE;
  25255. var currentSprite;
  25256. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25257. var cameraView = camera.getViewMatrix();
  25258. for (var index = 0; index < count; index++) {
  25259. var sprite = this.sprites[index];
  25260. if (!sprite) {
  25261. continue;
  25262. }
  25263. if (predicate) {
  25264. if (!predicate(sprite)) {
  25265. continue;
  25266. }
  25267. }
  25268. else if (!sprite.isPickable) {
  25269. continue;
  25270. }
  25271. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25272. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25273. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25274. if (ray.intersectsBoxMinMax(min, max)) {
  25275. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25276. if (distance > currentDistance) {
  25277. distance = currentDistance;
  25278. currentSprite = sprite;
  25279. if (fastCheck) {
  25280. break;
  25281. }
  25282. }
  25283. }
  25284. }
  25285. if (currentSprite) {
  25286. var result = new BABYLON.PickingInfo();
  25287. result.hit = true;
  25288. result.pickedSprite = currentSprite;
  25289. result.distance = distance;
  25290. return result;
  25291. }
  25292. return null;
  25293. };
  25294. SpriteManager.prototype.render = function () {
  25295. // Check
  25296. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25297. return;
  25298. var engine = this._scene.getEngine();
  25299. var baseSize = this._spriteTexture.getBaseSize();
  25300. // Sprites
  25301. var deltaTime = engine.getDeltaTime();
  25302. var max = Math.min(this._capacity, this.sprites.length);
  25303. var rowSize = baseSize.width / this.cellSize;
  25304. var offset = 0;
  25305. for (var index = 0; index < max; index++) {
  25306. var sprite = this.sprites[index];
  25307. if (!sprite) {
  25308. continue;
  25309. }
  25310. sprite._animate(deltaTime);
  25311. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25312. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25313. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25314. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25315. }
  25316. this._buffer.update(this._vertexData);
  25317. // Render
  25318. var effect = this._effectBase;
  25319. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25320. effect = this._effectFog;
  25321. }
  25322. engine.enableEffect(effect);
  25323. var viewMatrix = this._scene.getViewMatrix();
  25324. effect.setTexture("diffuseSampler", this._spriteTexture);
  25325. effect.setMatrix("view", viewMatrix);
  25326. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25327. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25328. // Fog
  25329. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25330. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25331. effect.setColor3("vFogColor", this._scene.fogColor);
  25332. }
  25333. // VBOs
  25334. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25335. // Draw order
  25336. engine.setDepthFunctionToLessOrEqual();
  25337. effect.setBool("alphaTest", true);
  25338. engine.setColorWrite(false);
  25339. engine.draw(true, 0, max * 6);
  25340. engine.setColorWrite(true);
  25341. effect.setBool("alphaTest", false);
  25342. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25343. engine.draw(true, 0, max * 6);
  25344. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25345. };
  25346. SpriteManager.prototype.dispose = function () {
  25347. if (this._buffer) {
  25348. this._buffer.dispose();
  25349. this._buffer = null;
  25350. }
  25351. if (this._indexBuffer) {
  25352. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25353. this._indexBuffer = null;
  25354. }
  25355. if (this._spriteTexture) {
  25356. this._spriteTexture.dispose();
  25357. this._spriteTexture = null;
  25358. }
  25359. // Remove from scene
  25360. var index = this._scene.spriteManagers.indexOf(this);
  25361. this._scene.spriteManagers.splice(index, 1);
  25362. // Callback
  25363. this.onDisposeObservable.notifyObservers(this);
  25364. this.onDisposeObservable.clear();
  25365. };
  25366. return SpriteManager;
  25367. })();
  25368. BABYLON.SpriteManager = SpriteManager;
  25369. })(BABYLON || (BABYLON = {}));
  25370. var BABYLON;
  25371. (function (BABYLON) {
  25372. var Sprite = (function () {
  25373. function Sprite(name, manager) {
  25374. this.name = name;
  25375. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25376. this.width = 1.0;
  25377. this.height = 1.0;
  25378. this.angle = 0;
  25379. this.cellIndex = 0;
  25380. this.invertU = 0;
  25381. this.invertV = 0;
  25382. this.animations = new Array();
  25383. this.isPickable = false;
  25384. this._animationStarted = false;
  25385. this._loopAnimation = false;
  25386. this._fromIndex = 0;
  25387. this._toIndex = 0;
  25388. this._delay = 0;
  25389. this._direction = 1;
  25390. this._frameCount = 0;
  25391. this._time = 0;
  25392. this._manager = manager;
  25393. this._manager.sprites.push(this);
  25394. this.position = BABYLON.Vector3.Zero();
  25395. }
  25396. Object.defineProperty(Sprite.prototype, "size", {
  25397. get: function () {
  25398. return this.width;
  25399. },
  25400. set: function (value) {
  25401. this.width = value;
  25402. this.height = value;
  25403. },
  25404. enumerable: true,
  25405. configurable: true
  25406. });
  25407. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25408. this._fromIndex = from;
  25409. this._toIndex = to;
  25410. this._loopAnimation = loop;
  25411. this._delay = delay;
  25412. this._animationStarted = true;
  25413. this._direction = from < to ? 1 : -1;
  25414. this.cellIndex = from;
  25415. this._time = 0;
  25416. };
  25417. Sprite.prototype.stopAnimation = function () {
  25418. this._animationStarted = false;
  25419. };
  25420. Sprite.prototype._animate = function (deltaTime) {
  25421. if (!this._animationStarted)
  25422. return;
  25423. this._time += deltaTime;
  25424. if (this._time > this._delay) {
  25425. this._time = this._time % this._delay;
  25426. this.cellIndex += this._direction;
  25427. if (this.cellIndex == this._toIndex) {
  25428. if (this._loopAnimation) {
  25429. this.cellIndex = this._fromIndex;
  25430. }
  25431. else {
  25432. this._animationStarted = false;
  25433. if (this.disposeWhenFinishedAnimating) {
  25434. this.dispose();
  25435. }
  25436. }
  25437. }
  25438. }
  25439. };
  25440. Sprite.prototype.dispose = function () {
  25441. for (var i = 0; i < this._manager.sprites.length; i++) {
  25442. if (this._manager.sprites[i] == this) {
  25443. this._manager.sprites.splice(i, 1);
  25444. }
  25445. }
  25446. };
  25447. return Sprite;
  25448. })();
  25449. BABYLON.Sprite = Sprite;
  25450. })(BABYLON || (BABYLON = {}));
  25451. var BABYLON;
  25452. (function (BABYLON) {
  25453. var Layer = (function () {
  25454. function Layer(name, imgUrl, scene, isBackground, color) {
  25455. this.name = name;
  25456. this.scale = new BABYLON.Vector2(1, 1);
  25457. this.offset = new BABYLON.Vector2(0, 0);
  25458. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25459. this._vertexBuffers = {};
  25460. // Events
  25461. /**
  25462. * An event triggered when the layer is disposed.
  25463. * @type {BABYLON.Observable}
  25464. */
  25465. this.onDisposeObservable = new BABYLON.Observable();
  25466. /**
  25467. * An event triggered before rendering the scene
  25468. * @type {BABYLON.Observable}
  25469. */
  25470. this.onBeforeRenderObservable = new BABYLON.Observable();
  25471. /**
  25472. * An event triggered after rendering the scene
  25473. * @type {BABYLON.Observable}
  25474. */
  25475. this.onAfterRenderObservable = new BABYLON.Observable();
  25476. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25477. this.isBackground = isBackground === undefined ? true : isBackground;
  25478. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25479. this._scene = scene;
  25480. this._scene.layers.push(this);
  25481. var engine = scene.getEngine();
  25482. // VBO
  25483. var vertices = [];
  25484. vertices.push(1, 1);
  25485. vertices.push(-1, 1);
  25486. vertices.push(-1, -1);
  25487. vertices.push(1, -1);
  25488. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25489. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  25490. // Indices
  25491. var indices = [];
  25492. indices.push(0);
  25493. indices.push(1);
  25494. indices.push(2);
  25495. indices.push(0);
  25496. indices.push(2);
  25497. indices.push(3);
  25498. this._indexBuffer = engine.createIndexBuffer(indices);
  25499. // Effects
  25500. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25501. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25502. }
  25503. Object.defineProperty(Layer.prototype, "onDispose", {
  25504. set: function (callback) {
  25505. if (this._onDisposeObserver) {
  25506. this.onDisposeObservable.remove(this._onDisposeObserver);
  25507. }
  25508. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25509. },
  25510. enumerable: true,
  25511. configurable: true
  25512. });
  25513. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25514. set: function (callback) {
  25515. if (this._onBeforeRenderObserver) {
  25516. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25517. }
  25518. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25519. },
  25520. enumerable: true,
  25521. configurable: true
  25522. });
  25523. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25524. set: function (callback) {
  25525. if (this._onAfterRenderObserver) {
  25526. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25527. }
  25528. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25529. },
  25530. enumerable: true,
  25531. configurable: true
  25532. });
  25533. Layer.prototype.render = function () {
  25534. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25535. // Check
  25536. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25537. return;
  25538. var engine = this._scene.getEngine();
  25539. this.onBeforeRenderObservable.notifyObservers(this);
  25540. // Render
  25541. engine.enableEffect(currentEffect);
  25542. engine.setState(false);
  25543. // Texture
  25544. currentEffect.setTexture("textureSampler", this.texture);
  25545. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25546. // Color
  25547. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25548. // Scale / offset
  25549. currentEffect.setVector2("offset", this.offset);
  25550. currentEffect.setVector2("scale", this.scale);
  25551. // VBOs
  25552. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  25553. // Draw order
  25554. if (!this._alphaTestEffect) {
  25555. engine.setAlphaMode(this.alphaBlendingMode);
  25556. engine.draw(true, 0, 6);
  25557. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25558. }
  25559. else {
  25560. engine.draw(true, 0, 6);
  25561. }
  25562. this.onAfterRenderObservable.notifyObservers(this);
  25563. };
  25564. Layer.prototype.dispose = function () {
  25565. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25566. if (vertexBuffer) {
  25567. vertexBuffer.dispose();
  25568. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25569. }
  25570. if (this._indexBuffer) {
  25571. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25572. this._indexBuffer = null;
  25573. }
  25574. if (this.texture) {
  25575. this.texture.dispose();
  25576. this.texture = null;
  25577. }
  25578. // Remove from scene
  25579. var index = this._scene.layers.indexOf(this);
  25580. this._scene.layers.splice(index, 1);
  25581. // Callback
  25582. this.onDisposeObservable.notifyObservers(this);
  25583. this.onDisposeObservable.clear();
  25584. this.onAfterRenderObservable.clear();
  25585. this.onBeforeRenderObservable.clear();
  25586. };
  25587. return Layer;
  25588. })();
  25589. BABYLON.Layer = Layer;
  25590. })(BABYLON || (BABYLON = {}));
  25591. var BABYLON;
  25592. (function (BABYLON) {
  25593. var Particle = (function () {
  25594. function Particle() {
  25595. this.position = BABYLON.Vector3.Zero();
  25596. this.direction = BABYLON.Vector3.Zero();
  25597. this.color = new BABYLON.Color4(0, 0, 0, 0);
  25598. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  25599. this.lifeTime = 1.0;
  25600. this.age = 0;
  25601. this.size = 0;
  25602. this.angle = 0;
  25603. this.angularSpeed = 0;
  25604. }
  25605. Particle.prototype.copyTo = function (other) {
  25606. other.position.copyFrom(this.position);
  25607. other.direction.copyFrom(this.direction);
  25608. other.color.copyFrom(this.color);
  25609. other.colorStep.copyFrom(this.colorStep);
  25610. other.lifeTime = this.lifeTime;
  25611. other.age = this.age;
  25612. other.size = this.size;
  25613. other.angle = this.angle;
  25614. other.angularSpeed = this.angularSpeed;
  25615. };
  25616. return Particle;
  25617. })();
  25618. BABYLON.Particle = Particle;
  25619. })(BABYLON || (BABYLON = {}));
  25620. var BABYLON;
  25621. (function (BABYLON) {
  25622. var randomNumber = function (min, max) {
  25623. if (min === max) {
  25624. return (min);
  25625. }
  25626. var random = Math.random();
  25627. return ((random * (max - min)) + min);
  25628. };
  25629. var ParticleSystem = (function () {
  25630. function ParticleSystem(name, capacity, scene, customEffect) {
  25631. var _this = this;
  25632. this.name = name;
  25633. // Members
  25634. this.animations = [];
  25635. this.renderingGroupId = 0;
  25636. this.emitter = null;
  25637. this.emitRate = 10;
  25638. this.manualEmitCount = -1;
  25639. this.updateSpeed = 0.01;
  25640. this.targetStopDuration = 0;
  25641. this.disposeOnStop = false;
  25642. this.minEmitPower = 1;
  25643. this.maxEmitPower = 1;
  25644. this.minLifeTime = 1;
  25645. this.maxLifeTime = 1;
  25646. this.minSize = 1;
  25647. this.maxSize = 1;
  25648. this.minAngularSpeed = 0;
  25649. this.maxAngularSpeed = 0;
  25650. this.layerMask = 0x0FFFFFFF;
  25651. /**
  25652. * An event triggered when the system is disposed.
  25653. * @type {BABYLON.Observable}
  25654. */
  25655. this.onDisposeObservable = new BABYLON.Observable();
  25656. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  25657. this.forceDepthWrite = false;
  25658. this.gravity = BABYLON.Vector3.Zero();
  25659. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  25660. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  25661. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  25662. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  25663. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25664. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25665. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  25666. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25667. this.particles = new Array();
  25668. this._stockParticles = new Array();
  25669. this._newPartsExcess = 0;
  25670. this._vertexBuffers = {};
  25671. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  25672. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  25673. this._scaledDirection = BABYLON.Vector3.Zero();
  25674. this._scaledGravity = BABYLON.Vector3.Zero();
  25675. this._currentRenderId = -1;
  25676. this._started = false;
  25677. this._stopped = false;
  25678. this._actualFrame = 0;
  25679. this.id = name;
  25680. this._capacity = capacity;
  25681. this._scene = scene;
  25682. this._customEffect = customEffect;
  25683. scene.particleSystems.push(this);
  25684. var indices = [];
  25685. var index = 0;
  25686. for (var count = 0; count < capacity; count++) {
  25687. indices.push(index);
  25688. indices.push(index + 1);
  25689. indices.push(index + 2);
  25690. indices.push(index);
  25691. indices.push(index + 2);
  25692. indices.push(index + 3);
  25693. index += 4;
  25694. }
  25695. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25696. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  25697. this._vertexData = new Float32Array(capacity * 11 * 4);
  25698. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  25699. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  25700. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  25701. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  25702. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25703. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25704. this._vertexBuffers["options"] = options;
  25705. // Default behaviors
  25706. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  25707. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  25708. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  25709. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  25710. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  25711. };
  25712. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  25713. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  25714. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  25715. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  25716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  25717. };
  25718. this.updateFunction = function (particles) {
  25719. for (var index = 0; index < particles.length; index++) {
  25720. var particle = particles[index];
  25721. particle.age += _this._scaledUpdateSpeed;
  25722. if (particle.age >= particle.lifeTime) {
  25723. _this.recycleParticle(particle);
  25724. index--;
  25725. continue;
  25726. }
  25727. else {
  25728. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  25729. particle.color.addInPlace(_this._scaledColorStep);
  25730. if (particle.color.a < 0)
  25731. particle.color.a = 0;
  25732. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  25733. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  25734. particle.position.addInPlace(_this._scaledDirection);
  25735. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  25736. particle.direction.addInPlace(_this._scaledGravity);
  25737. }
  25738. }
  25739. };
  25740. }
  25741. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  25742. set: function (callback) {
  25743. if (this._onDisposeObserver) {
  25744. this.onDisposeObservable.remove(this._onDisposeObserver);
  25745. }
  25746. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25747. },
  25748. enumerable: true,
  25749. configurable: true
  25750. });
  25751. ParticleSystem.prototype.recycleParticle = function (particle) {
  25752. var lastParticle = this.particles.pop();
  25753. if (lastParticle !== particle) {
  25754. lastParticle.copyTo(particle);
  25755. this._stockParticles.push(lastParticle);
  25756. }
  25757. };
  25758. ParticleSystem.prototype.getCapacity = function () {
  25759. return this._capacity;
  25760. };
  25761. ParticleSystem.prototype.isAlive = function () {
  25762. return this._alive;
  25763. };
  25764. ParticleSystem.prototype.isStarted = function () {
  25765. return this._started;
  25766. };
  25767. ParticleSystem.prototype.start = function () {
  25768. this._started = true;
  25769. this._stopped = false;
  25770. this._actualFrame = 0;
  25771. };
  25772. ParticleSystem.prototype.stop = function () {
  25773. this._stopped = true;
  25774. };
  25775. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  25776. var offset = index * 11;
  25777. this._vertexData[offset] = particle.position.x;
  25778. this._vertexData[offset + 1] = particle.position.y;
  25779. this._vertexData[offset + 2] = particle.position.z;
  25780. this._vertexData[offset + 3] = particle.color.r;
  25781. this._vertexData[offset + 4] = particle.color.g;
  25782. this._vertexData[offset + 5] = particle.color.b;
  25783. this._vertexData[offset + 6] = particle.color.a;
  25784. this._vertexData[offset + 7] = particle.angle;
  25785. this._vertexData[offset + 8] = particle.size;
  25786. this._vertexData[offset + 9] = offsetX;
  25787. this._vertexData[offset + 10] = offsetY;
  25788. };
  25789. ParticleSystem.prototype._update = function (newParticles) {
  25790. // Update current
  25791. this._alive = this.particles.length > 0;
  25792. this.updateFunction(this.particles);
  25793. // Add new ones
  25794. var worldMatrix;
  25795. if (this.emitter.position) {
  25796. worldMatrix = this.emitter.getWorldMatrix();
  25797. }
  25798. else {
  25799. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  25800. }
  25801. var particle;
  25802. for (var index = 0; index < newParticles; index++) {
  25803. if (this.particles.length === this._capacity) {
  25804. break;
  25805. }
  25806. if (this._stockParticles.length !== 0) {
  25807. particle = this._stockParticles.pop();
  25808. particle.age = 0;
  25809. }
  25810. else {
  25811. particle = new BABYLON.Particle();
  25812. }
  25813. this.particles.push(particle);
  25814. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  25815. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  25816. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  25817. particle.size = randomNumber(this.minSize, this.maxSize);
  25818. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  25819. this.startPositionFunction(worldMatrix, particle.position, particle);
  25820. var step = randomNumber(0, 1.0);
  25821. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  25822. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  25823. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  25824. }
  25825. };
  25826. ParticleSystem.prototype._getEffect = function () {
  25827. if (this._customEffect) {
  25828. return this._customEffect;
  25829. }
  25830. ;
  25831. var defines = [];
  25832. if (this._scene.clipPlane) {
  25833. defines.push("#define CLIPPLANE");
  25834. }
  25835. // Effect
  25836. var join = defines.join("\n");
  25837. if (this._cachedDefines !== join) {
  25838. this._cachedDefines = join;
  25839. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25840. }
  25841. return this._effect;
  25842. };
  25843. ParticleSystem.prototype.animate = function () {
  25844. if (!this._started)
  25845. return;
  25846. var effect = this._getEffect();
  25847. // Check
  25848. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25849. return;
  25850. if (this._currentRenderId === this._scene.getRenderId()) {
  25851. return;
  25852. }
  25853. this._currentRenderId = this._scene.getRenderId();
  25854. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25855. // determine the number of particles we need to create
  25856. var newParticles;
  25857. if (this.manualEmitCount > -1) {
  25858. newParticles = this.manualEmitCount;
  25859. this._newPartsExcess = 0;
  25860. this.manualEmitCount = 0;
  25861. }
  25862. else {
  25863. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25864. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25865. }
  25866. if (this._newPartsExcess > 1.0) {
  25867. newParticles += this._newPartsExcess >> 0;
  25868. this._newPartsExcess -= this._newPartsExcess >> 0;
  25869. }
  25870. this._alive = false;
  25871. if (!this._stopped) {
  25872. this._actualFrame += this._scaledUpdateSpeed;
  25873. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25874. this.stop();
  25875. }
  25876. else {
  25877. newParticles = 0;
  25878. }
  25879. this._update(newParticles);
  25880. // Stopped?
  25881. if (this._stopped) {
  25882. if (!this._alive) {
  25883. this._started = false;
  25884. if (this.disposeOnStop) {
  25885. this._scene._toBeDisposed.push(this);
  25886. }
  25887. }
  25888. }
  25889. // Update VBO
  25890. var offset = 0;
  25891. for (var index = 0; index < this.particles.length; index++) {
  25892. var particle = this.particles[index];
  25893. this._appendParticleVertex(offset++, particle, 0, 0);
  25894. this._appendParticleVertex(offset++, particle, 1, 0);
  25895. this._appendParticleVertex(offset++, particle, 1, 1);
  25896. this._appendParticleVertex(offset++, particle, 0, 1);
  25897. }
  25898. this._vertexBuffer.update(this._vertexData);
  25899. };
  25900. ParticleSystem.prototype.render = function () {
  25901. var effect = this._getEffect();
  25902. // Check
  25903. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25904. return 0;
  25905. var engine = this._scene.getEngine();
  25906. // Render
  25907. engine.enableEffect(effect);
  25908. engine.setState(false);
  25909. var viewMatrix = this._scene.getViewMatrix();
  25910. effect.setTexture("diffuseSampler", this.particleTexture);
  25911. effect.setMatrix("view", viewMatrix);
  25912. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25913. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25914. if (this._scene.clipPlane) {
  25915. var clipPlane = this._scene.clipPlane;
  25916. var invView = viewMatrix.clone();
  25917. invView.invert();
  25918. effect.setMatrix("invView", invView);
  25919. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25920. }
  25921. // VBOs
  25922. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25923. // Draw order
  25924. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25925. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25926. }
  25927. else {
  25928. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25929. }
  25930. if (this.forceDepthWrite) {
  25931. engine.setDepthWrite(true);
  25932. }
  25933. engine.draw(true, 0, this.particles.length * 6);
  25934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25935. return this.particles.length;
  25936. };
  25937. ParticleSystem.prototype.dispose = function () {
  25938. if (this._vertexBuffer) {
  25939. this._vertexBuffer.dispose();
  25940. this._vertexBuffer = null;
  25941. }
  25942. if (this._indexBuffer) {
  25943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25944. this._indexBuffer = null;
  25945. }
  25946. if (this.particleTexture) {
  25947. this.particleTexture.dispose();
  25948. this.particleTexture = null;
  25949. }
  25950. // Remove from scene
  25951. var index = this._scene.particleSystems.indexOf(this);
  25952. this._scene.particleSystems.splice(index, 1);
  25953. // Callback
  25954. this.onDisposeObservable.notifyObservers(this);
  25955. this.onDisposeObservable.clear();
  25956. };
  25957. // Clone
  25958. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25959. var result = new ParticleSystem(name, this._capacity, this._scene);
  25960. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  25961. if (newEmitter === undefined) {
  25962. newEmitter = this.emitter;
  25963. }
  25964. result.emitter = newEmitter;
  25965. if (this.particleTexture) {
  25966. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25967. }
  25968. result.start();
  25969. return result;
  25970. };
  25971. ParticleSystem.prototype.serialize = function () {
  25972. var serializationObject = {};
  25973. serializationObject.name = this.name;
  25974. serializationObject.id = this.id;
  25975. // Emitter
  25976. if (this.emitter.position) {
  25977. serializationObject.emitterId = this.emitter.id;
  25978. }
  25979. else {
  25980. serializationObject.emitter = this.emitter.asArray();
  25981. }
  25982. serializationObject.capacity = this.getCapacity();
  25983. if (this.particleTexture) {
  25984. serializationObject.textureName = this.particleTexture.name;
  25985. }
  25986. // Animations
  25987. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25988. // Particle system
  25989. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25990. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25991. serializationObject.minSize = this.minSize;
  25992. serializationObject.maxSize = this.maxSize;
  25993. serializationObject.minEmitPower = this.minEmitPower;
  25994. serializationObject.maxEmitPower = this.maxEmitPower;
  25995. serializationObject.minLifeTime = this.minLifeTime;
  25996. serializationObject.maxLifeTime = this.maxLifeTime;
  25997. serializationObject.emitRate = this.emitRate;
  25998. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25999. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26000. serializationObject.gravity = this.gravity.asArray();
  26001. serializationObject.direction1 = this.direction1.asArray();
  26002. serializationObject.direction2 = this.direction2.asArray();
  26003. serializationObject.color1 = this.color1.asArray();
  26004. serializationObject.color2 = this.color2.asArray();
  26005. serializationObject.colorDead = this.colorDead.asArray();
  26006. serializationObject.updateSpeed = this.updateSpeed;
  26007. serializationObject.targetStopDuration = this.targetStopDuration;
  26008. serializationObject.textureMask = this.textureMask.asArray();
  26009. serializationObject.blendMode = this.blendMode;
  26010. return serializationObject;
  26011. };
  26012. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26013. var name = parsedParticleSystem.name;
  26014. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26015. if (parsedParticleSystem.id) {
  26016. particleSystem.id = parsedParticleSystem.id;
  26017. }
  26018. // Texture
  26019. if (parsedParticleSystem.textureName) {
  26020. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26021. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26022. }
  26023. // Emitter
  26024. if (parsedParticleSystem.emitterId) {
  26025. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26026. }
  26027. else {
  26028. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26029. }
  26030. // Animations
  26031. if (parsedParticleSystem.animations) {
  26032. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26033. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26034. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26035. }
  26036. }
  26037. if (parsedParticleSystem.autoAnimate) {
  26038. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26039. }
  26040. // Particle system
  26041. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26042. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26043. particleSystem.minSize = parsedParticleSystem.minSize;
  26044. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26045. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26046. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26047. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26048. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26049. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26050. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26051. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26052. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26053. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26054. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26055. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26056. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26057. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26058. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26059. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26060. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26061. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26062. if (!parsedParticleSystem.preventAutoStart) {
  26063. particleSystem.start();
  26064. }
  26065. return particleSystem;
  26066. };
  26067. // Statics
  26068. ParticleSystem.BLENDMODE_ONEONE = 0;
  26069. ParticleSystem.BLENDMODE_STANDARD = 1;
  26070. return ParticleSystem;
  26071. })();
  26072. BABYLON.ParticleSystem = ParticleSystem;
  26073. })(BABYLON || (BABYLON = {}));
  26074. var BABYLON;
  26075. (function (BABYLON) {
  26076. var AnimationRange = (function () {
  26077. function AnimationRange(name, from, to) {
  26078. this.name = name;
  26079. this.from = from;
  26080. this.to = to;
  26081. }
  26082. AnimationRange.prototype.clone = function () {
  26083. return new AnimationRange(this.name, this.from, this.to);
  26084. };
  26085. return AnimationRange;
  26086. })();
  26087. BABYLON.AnimationRange = AnimationRange;
  26088. /**
  26089. * Composed of a frame, and an action function
  26090. */
  26091. var AnimationEvent = (function () {
  26092. function AnimationEvent(frame, action, onlyOnce) {
  26093. this.frame = frame;
  26094. this.action = action;
  26095. this.onlyOnce = onlyOnce;
  26096. this.isDone = false;
  26097. }
  26098. return AnimationEvent;
  26099. })();
  26100. BABYLON.AnimationEvent = AnimationEvent;
  26101. var PathCursor = (function () {
  26102. function PathCursor(path) {
  26103. this.path = path;
  26104. this._onchange = new Array();
  26105. this.value = 0;
  26106. this.animations = new Array();
  26107. }
  26108. PathCursor.prototype.getPoint = function () {
  26109. var point = this.path.getPointAtLengthPosition(this.value);
  26110. return new BABYLON.Vector3(point.x, 0, point.y);
  26111. };
  26112. PathCursor.prototype.moveAhead = function (step) {
  26113. if (step === void 0) { step = 0.002; }
  26114. this.move(step);
  26115. return this;
  26116. };
  26117. PathCursor.prototype.moveBack = function (step) {
  26118. if (step === void 0) { step = 0.002; }
  26119. this.move(-step);
  26120. return this;
  26121. };
  26122. PathCursor.prototype.move = function (step) {
  26123. if (Math.abs(step) > 1) {
  26124. throw "step size should be less than 1.";
  26125. }
  26126. this.value += step;
  26127. this.ensureLimits();
  26128. this.raiseOnChange();
  26129. return this;
  26130. };
  26131. PathCursor.prototype.ensureLimits = function () {
  26132. while (this.value > 1) {
  26133. this.value -= 1;
  26134. }
  26135. while (this.value < 0) {
  26136. this.value += 1;
  26137. }
  26138. return this;
  26139. };
  26140. // used by animation engine
  26141. PathCursor.prototype.markAsDirty = function (propertyName) {
  26142. this.ensureLimits();
  26143. this.raiseOnChange();
  26144. return this;
  26145. };
  26146. PathCursor.prototype.raiseOnChange = function () {
  26147. var _this = this;
  26148. this._onchange.forEach(function (f) { return f(_this); });
  26149. return this;
  26150. };
  26151. PathCursor.prototype.onchange = function (f) {
  26152. this._onchange.push(f);
  26153. return this;
  26154. };
  26155. return PathCursor;
  26156. })();
  26157. BABYLON.PathCursor = PathCursor;
  26158. var Animation = (function () {
  26159. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26160. this.name = name;
  26161. this.targetProperty = targetProperty;
  26162. this.framePerSecond = framePerSecond;
  26163. this.dataType = dataType;
  26164. this.loopMode = loopMode;
  26165. this.enableBlending = enableBlending;
  26166. this._offsetsCache = {};
  26167. this._highLimitsCache = {};
  26168. this._stopped = false;
  26169. this._blendingFactor = 0;
  26170. // The set of event that will be linked to this animation
  26171. this._events = new Array();
  26172. this.allowMatricesInterpolation = false;
  26173. this.blendingSpeed = 0.01;
  26174. this._ranges = {};
  26175. this.targetPropertyPath = targetProperty.split(".");
  26176. this.dataType = dataType;
  26177. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26178. }
  26179. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26180. var dataType = undefined;
  26181. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26182. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26183. }
  26184. else if (from instanceof BABYLON.Quaternion) {
  26185. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26186. }
  26187. else if (from instanceof BABYLON.Vector3) {
  26188. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26189. }
  26190. else if (from instanceof BABYLON.Vector2) {
  26191. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26192. }
  26193. else if (from instanceof BABYLON.Color3) {
  26194. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26195. }
  26196. else if (from instanceof BABYLON.Size) {
  26197. dataType = Animation.ANIMATIONTYPE_SIZE;
  26198. }
  26199. if (dataType == undefined) {
  26200. return null;
  26201. }
  26202. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26203. var keys = [];
  26204. keys.push({ frame: 0, value: from });
  26205. keys.push({ frame: totalFrame, value: to });
  26206. animation.setKeys(keys);
  26207. if (easingFunction !== undefined) {
  26208. animation.setEasingFunction(easingFunction);
  26209. }
  26210. return animation;
  26211. };
  26212. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26213. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26214. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26215. };
  26216. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26217. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26218. node.animations.push(animation);
  26219. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26220. };
  26221. // Methods
  26222. /**
  26223. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26224. */
  26225. Animation.prototype.toString = function (fullDetails) {
  26226. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26227. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26228. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26229. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26230. if (fullDetails) {
  26231. ret += ", Ranges: {";
  26232. var first = true;
  26233. for (var name in this._ranges) {
  26234. if (first) {
  26235. ret += ", ";
  26236. first = false;
  26237. }
  26238. ret += name;
  26239. }
  26240. ret += "}";
  26241. }
  26242. return ret;
  26243. };
  26244. /**
  26245. * Add an event to this animation.
  26246. */
  26247. Animation.prototype.addEvent = function (event) {
  26248. this._events.push(event);
  26249. };
  26250. /**
  26251. * Remove all events found at the given frame
  26252. * @param frame
  26253. */
  26254. Animation.prototype.removeEvents = function (frame) {
  26255. for (var index = 0; index < this._events.length; index++) {
  26256. if (this._events[index].frame === frame) {
  26257. this._events.splice(index, 1);
  26258. index--;
  26259. }
  26260. }
  26261. };
  26262. Animation.prototype.createRange = function (name, from, to) {
  26263. // check name not already in use; could happen for bones after serialized
  26264. if (!this._ranges[name]) {
  26265. this._ranges[name] = new AnimationRange(name, from, to);
  26266. }
  26267. };
  26268. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26269. if (deleteFrames === void 0) { deleteFrames = true; }
  26270. if (this._ranges[name]) {
  26271. if (deleteFrames) {
  26272. var from = this._ranges[name].from;
  26273. var to = this._ranges[name].to;
  26274. // this loop MUST go high to low for multiple splices to work
  26275. for (var key = this._keys.length - 1; key >= 0; key--) {
  26276. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26277. this._keys.splice(key, 1);
  26278. }
  26279. }
  26280. }
  26281. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26282. }
  26283. };
  26284. Animation.prototype.getRange = function (name) {
  26285. return this._ranges[name];
  26286. };
  26287. Animation.prototype.reset = function () {
  26288. this._offsetsCache = {};
  26289. this._highLimitsCache = {};
  26290. this.currentFrame = 0;
  26291. this._blendingFactor = 0;
  26292. this._originalBlendValue = null;
  26293. };
  26294. Animation.prototype.isStopped = function () {
  26295. return this._stopped;
  26296. };
  26297. Animation.prototype.getKeys = function () {
  26298. return this._keys;
  26299. };
  26300. Animation.prototype.getHighestFrame = function () {
  26301. var ret = 0;
  26302. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26303. if (ret < this._keys[key].frame) {
  26304. ret = this._keys[key].frame;
  26305. }
  26306. }
  26307. return ret;
  26308. };
  26309. Animation.prototype.getEasingFunction = function () {
  26310. return this._easingFunction;
  26311. };
  26312. Animation.prototype.setEasingFunction = function (easingFunction) {
  26313. this._easingFunction = easingFunction;
  26314. };
  26315. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26316. return startValue + (endValue - startValue) * gradient;
  26317. };
  26318. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26319. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26320. };
  26321. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26322. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26323. };
  26324. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26325. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26326. };
  26327. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26328. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26329. };
  26330. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26331. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26332. };
  26333. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26334. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26335. };
  26336. Animation.prototype.clone = function () {
  26337. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26338. if (this._keys) {
  26339. clone.setKeys(this._keys);
  26340. }
  26341. if (this._ranges) {
  26342. clone._ranges = {};
  26343. for (var name in this._ranges) {
  26344. clone._ranges[name] = this._ranges[name].clone();
  26345. }
  26346. }
  26347. return clone;
  26348. };
  26349. Animation.prototype.setKeys = function (values) {
  26350. this._keys = values.slice(0);
  26351. this._offsetsCache = {};
  26352. this._highLimitsCache = {};
  26353. };
  26354. Animation.prototype._getKeyValue = function (value) {
  26355. if (typeof value === "function") {
  26356. return value();
  26357. }
  26358. return value;
  26359. };
  26360. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26361. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26362. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26363. }
  26364. this.currentFrame = currentFrame;
  26365. // Try to get a hash to find the right key
  26366. 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));
  26367. if (this._keys[startKey].frame >= currentFrame) {
  26368. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26369. startKey--;
  26370. }
  26371. }
  26372. for (var key = startKey; key < this._keys.length; key++) {
  26373. if (this._keys[key + 1].frame >= currentFrame) {
  26374. var startValue = this._getKeyValue(this._keys[key].value);
  26375. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26376. // gradient : percent of currentFrame between the frame inf and the frame sup
  26377. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26378. // check for easingFunction and correction of gradient
  26379. if (this._easingFunction != null) {
  26380. gradient = this._easingFunction.ease(gradient);
  26381. }
  26382. switch (this.dataType) {
  26383. // Float
  26384. case Animation.ANIMATIONTYPE_FLOAT:
  26385. switch (loopMode) {
  26386. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26387. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26388. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26389. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26390. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26391. }
  26392. break;
  26393. // Quaternion
  26394. case Animation.ANIMATIONTYPE_QUATERNION:
  26395. var quaternion = null;
  26396. switch (loopMode) {
  26397. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26398. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26399. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26400. break;
  26401. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26402. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26403. break;
  26404. }
  26405. return quaternion;
  26406. // Vector3
  26407. case Animation.ANIMATIONTYPE_VECTOR3:
  26408. switch (loopMode) {
  26409. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26410. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26411. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26412. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26413. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26414. }
  26415. // Vector2
  26416. case Animation.ANIMATIONTYPE_VECTOR2:
  26417. switch (loopMode) {
  26418. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26419. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26420. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26421. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26422. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26423. }
  26424. // Size
  26425. case Animation.ANIMATIONTYPE_SIZE:
  26426. switch (loopMode) {
  26427. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26428. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26429. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26430. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26431. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26432. }
  26433. // Color3
  26434. case Animation.ANIMATIONTYPE_COLOR3:
  26435. switch (loopMode) {
  26436. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26437. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26438. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26439. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26440. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26441. }
  26442. // Matrix
  26443. case Animation.ANIMATIONTYPE_MATRIX:
  26444. switch (loopMode) {
  26445. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26446. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26447. if (this.allowMatricesInterpolation) {
  26448. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26449. }
  26450. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26451. return startValue;
  26452. }
  26453. default:
  26454. break;
  26455. }
  26456. break;
  26457. }
  26458. }
  26459. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26460. };
  26461. Animation.prototype.setValue = function (currentValue, blend) {
  26462. if (blend === void 0) { blend = false; }
  26463. // Set value
  26464. var path;
  26465. var destination;
  26466. if (this.targetPropertyPath.length > 1) {
  26467. var property = this._target[this.targetPropertyPath[0]];
  26468. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26469. property = property[this.targetPropertyPath[index]];
  26470. }
  26471. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26472. destination = property;
  26473. }
  26474. else {
  26475. path = this.targetPropertyPath[0];
  26476. destination = this._target;
  26477. }
  26478. // Blending
  26479. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26480. if (!this._originalBlendValue) {
  26481. if (destination[path].clone) {
  26482. this._originalBlendValue = destination[path].clone();
  26483. }
  26484. else {
  26485. this._originalBlendValue = destination[path];
  26486. }
  26487. }
  26488. if (this._originalBlendValue.prototype) {
  26489. if (this._originalBlendValue.prototype.Lerp) {
  26490. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26491. }
  26492. else {
  26493. destination[path] = currentValue;
  26494. }
  26495. }
  26496. else if (this._originalBlendValue.m) {
  26497. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26498. }
  26499. else {
  26500. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26501. }
  26502. this._blendingFactor += this.blendingSpeed;
  26503. }
  26504. else {
  26505. destination[path] = currentValue;
  26506. }
  26507. if (this._target.markAsDirty) {
  26508. this._target.markAsDirty(this.targetProperty);
  26509. }
  26510. };
  26511. Animation.prototype.goToFrame = function (frame) {
  26512. if (frame < this._keys[0].frame) {
  26513. frame = this._keys[0].frame;
  26514. }
  26515. else if (frame > this._keys[this._keys.length - 1].frame) {
  26516. frame = this._keys[this._keys.length - 1].frame;
  26517. }
  26518. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26519. this.setValue(currentValue);
  26520. };
  26521. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26522. if (blend === void 0) { blend = false; }
  26523. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26524. this._stopped = true;
  26525. return false;
  26526. }
  26527. var returnValue = true;
  26528. // Adding a start key at frame 0 if missing
  26529. if (this._keys[0].frame !== 0) {
  26530. var newKey = { frame: 0, value: this._keys[0].value };
  26531. this._keys.splice(0, 0, newKey);
  26532. }
  26533. // Check limits
  26534. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26535. from = this._keys[0].frame;
  26536. }
  26537. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26538. to = this._keys[this._keys.length - 1].frame;
  26539. }
  26540. // Compute ratio
  26541. var range = to - from;
  26542. var offsetValue;
  26543. // ratio represents the frame delta between from and to
  26544. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26545. var highLimitValue = 0;
  26546. if (ratio > range && !loop) {
  26547. returnValue = false;
  26548. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26549. }
  26550. else {
  26551. // Get max value if required
  26552. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26553. var keyOffset = to.toString() + from.toString();
  26554. if (!this._offsetsCache[keyOffset]) {
  26555. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26556. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26557. switch (this.dataType) {
  26558. // Float
  26559. case Animation.ANIMATIONTYPE_FLOAT:
  26560. this._offsetsCache[keyOffset] = toValue - fromValue;
  26561. break;
  26562. // Quaternion
  26563. case Animation.ANIMATIONTYPE_QUATERNION:
  26564. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26565. break;
  26566. // Vector3
  26567. case Animation.ANIMATIONTYPE_VECTOR3:
  26568. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26569. // Vector2
  26570. case Animation.ANIMATIONTYPE_VECTOR2:
  26571. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26572. // Size
  26573. case Animation.ANIMATIONTYPE_SIZE:
  26574. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26575. // Color3
  26576. case Animation.ANIMATIONTYPE_COLOR3:
  26577. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26578. default:
  26579. break;
  26580. }
  26581. this._highLimitsCache[keyOffset] = toValue;
  26582. }
  26583. highLimitValue = this._highLimitsCache[keyOffset];
  26584. offsetValue = this._offsetsCache[keyOffset];
  26585. }
  26586. }
  26587. if (offsetValue === undefined) {
  26588. switch (this.dataType) {
  26589. // Float
  26590. case Animation.ANIMATIONTYPE_FLOAT:
  26591. offsetValue = 0;
  26592. break;
  26593. // Quaternion
  26594. case Animation.ANIMATIONTYPE_QUATERNION:
  26595. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  26596. break;
  26597. // Vector3
  26598. case Animation.ANIMATIONTYPE_VECTOR3:
  26599. offsetValue = BABYLON.Vector3.Zero();
  26600. break;
  26601. // Vector2
  26602. case Animation.ANIMATIONTYPE_VECTOR2:
  26603. offsetValue = BABYLON.Vector2.Zero();
  26604. break;
  26605. // Size
  26606. case Animation.ANIMATIONTYPE_SIZE:
  26607. offsetValue = BABYLON.Size.Zero();
  26608. break;
  26609. // Color3
  26610. case Animation.ANIMATIONTYPE_COLOR3:
  26611. offsetValue = BABYLON.Color3.Black();
  26612. }
  26613. }
  26614. // Compute value
  26615. var repeatCount = (ratio / range) >> 0;
  26616. var currentFrame = returnValue ? from + ratio % range : to;
  26617. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  26618. // Set value
  26619. this.setValue(currentValue);
  26620. // Check events
  26621. for (var index = 0; index < this._events.length; index++) {
  26622. if (currentFrame >= this._events[index].frame) {
  26623. var event = this._events[index];
  26624. if (!event.isDone) {
  26625. // If event should be done only once, remove it.
  26626. if (event.onlyOnce) {
  26627. this._events.splice(index, 1);
  26628. index--;
  26629. }
  26630. event.isDone = true;
  26631. event.action();
  26632. } // Don't do anything if the event has already be done.
  26633. }
  26634. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  26635. // reset event, the animation is looping
  26636. this._events[index].isDone = false;
  26637. }
  26638. }
  26639. if (!returnValue) {
  26640. this._stopped = true;
  26641. }
  26642. return returnValue;
  26643. };
  26644. Animation.prototype.serialize = function () {
  26645. var serializationObject = {};
  26646. serializationObject.name = this.name;
  26647. serializationObject.property = this.targetProperty;
  26648. serializationObject.framePerSecond = this.framePerSecond;
  26649. serializationObject.dataType = this.dataType;
  26650. serializationObject.loopBehavior = this.loopMode;
  26651. var dataType = this.dataType;
  26652. serializationObject.keys = [];
  26653. var keys = this.getKeys();
  26654. for (var index = 0; index < keys.length; index++) {
  26655. var animationKey = keys[index];
  26656. var key = {};
  26657. key.frame = animationKey.frame;
  26658. switch (dataType) {
  26659. case Animation.ANIMATIONTYPE_FLOAT:
  26660. key.values = [animationKey.value];
  26661. break;
  26662. case Animation.ANIMATIONTYPE_QUATERNION:
  26663. case Animation.ANIMATIONTYPE_MATRIX:
  26664. case Animation.ANIMATIONTYPE_VECTOR3:
  26665. case Animation.ANIMATIONTYPE_COLOR3:
  26666. key.values = animationKey.value.asArray();
  26667. break;
  26668. }
  26669. serializationObject.keys.push(key);
  26670. }
  26671. serializationObject.ranges = [];
  26672. for (var name in this._ranges) {
  26673. var range = {};
  26674. range.name = name;
  26675. range.from = this._ranges[name].from;
  26676. range.to = this._ranges[name].to;
  26677. serializationObject.ranges.push(range);
  26678. }
  26679. return serializationObject;
  26680. };
  26681. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  26682. get: function () {
  26683. return Animation._ANIMATIONTYPE_FLOAT;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  26689. get: function () {
  26690. return Animation._ANIMATIONTYPE_VECTOR3;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  26696. get: function () {
  26697. return Animation._ANIMATIONTYPE_VECTOR2;
  26698. },
  26699. enumerable: true,
  26700. configurable: true
  26701. });
  26702. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  26703. get: function () {
  26704. return Animation._ANIMATIONTYPE_SIZE;
  26705. },
  26706. enumerable: true,
  26707. configurable: true
  26708. });
  26709. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  26710. get: function () {
  26711. return Animation._ANIMATIONTYPE_QUATERNION;
  26712. },
  26713. enumerable: true,
  26714. configurable: true
  26715. });
  26716. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  26717. get: function () {
  26718. return Animation._ANIMATIONTYPE_MATRIX;
  26719. },
  26720. enumerable: true,
  26721. configurable: true
  26722. });
  26723. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  26724. get: function () {
  26725. return Animation._ANIMATIONTYPE_COLOR3;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  26731. get: function () {
  26732. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  26733. },
  26734. enumerable: true,
  26735. configurable: true
  26736. });
  26737. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  26738. get: function () {
  26739. return Animation._ANIMATIONLOOPMODE_CYCLE;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  26745. get: function () {
  26746. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  26747. },
  26748. enumerable: true,
  26749. configurable: true
  26750. });
  26751. Animation.Parse = function (parsedAnimation) {
  26752. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  26753. var dataType = parsedAnimation.dataType;
  26754. var keys = [];
  26755. var data;
  26756. var index;
  26757. for (index = 0; index < parsedAnimation.keys.length; index++) {
  26758. var key = parsedAnimation.keys[index];
  26759. switch (dataType) {
  26760. case Animation.ANIMATIONTYPE_FLOAT:
  26761. data = key.values[0];
  26762. break;
  26763. case Animation.ANIMATIONTYPE_QUATERNION:
  26764. data = BABYLON.Quaternion.FromArray(key.values);
  26765. break;
  26766. case Animation.ANIMATIONTYPE_MATRIX:
  26767. data = BABYLON.Matrix.FromArray(key.values);
  26768. break;
  26769. case Animation.ANIMATIONTYPE_COLOR3:
  26770. data = BABYLON.Color3.FromArray(key.values);
  26771. break;
  26772. case Animation.ANIMATIONTYPE_VECTOR3:
  26773. default:
  26774. data = BABYLON.Vector3.FromArray(key.values);
  26775. break;
  26776. }
  26777. keys.push({
  26778. frame: key.frame,
  26779. value: data
  26780. });
  26781. }
  26782. animation.setKeys(keys);
  26783. if (parsedAnimation.ranges) {
  26784. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  26785. data = parsedAnimation.ranges[index];
  26786. animation.createRange(data.name, data.from, data.to);
  26787. }
  26788. }
  26789. return animation;
  26790. };
  26791. Animation.AppendSerializedAnimations = function (source, destination) {
  26792. if (source.animations) {
  26793. destination.animations = [];
  26794. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  26795. var animation = source.animations[animationIndex];
  26796. destination.animations.push(animation.serialize());
  26797. }
  26798. }
  26799. };
  26800. // Statics
  26801. Animation._ANIMATIONTYPE_FLOAT = 0;
  26802. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  26803. Animation._ANIMATIONTYPE_QUATERNION = 2;
  26804. Animation._ANIMATIONTYPE_MATRIX = 3;
  26805. Animation._ANIMATIONTYPE_COLOR3 = 4;
  26806. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  26807. Animation._ANIMATIONTYPE_SIZE = 6;
  26808. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  26809. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  26810. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  26811. return Animation;
  26812. })();
  26813. BABYLON.Animation = Animation;
  26814. })(BABYLON || (BABYLON = {}));
  26815. var BABYLON;
  26816. (function (BABYLON) {
  26817. var Animatable = (function () {
  26818. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  26819. if (fromFrame === void 0) { fromFrame = 0; }
  26820. if (toFrame === void 0) { toFrame = 100; }
  26821. if (loopAnimation === void 0) { loopAnimation = false; }
  26822. if (speedRatio === void 0) { speedRatio = 1.0; }
  26823. this.target = target;
  26824. this.fromFrame = fromFrame;
  26825. this.toFrame = toFrame;
  26826. this.loopAnimation = loopAnimation;
  26827. this.speedRatio = speedRatio;
  26828. this.onAnimationEnd = onAnimationEnd;
  26829. this._animations = new Array();
  26830. this._paused = false;
  26831. this.animationStarted = false;
  26832. if (animations) {
  26833. this.appendAnimations(target, animations);
  26834. }
  26835. this._scene = scene;
  26836. scene._activeAnimatables.push(this);
  26837. }
  26838. // Methods
  26839. Animatable.prototype.getAnimations = function () {
  26840. return this._animations;
  26841. };
  26842. Animatable.prototype.appendAnimations = function (target, animations) {
  26843. for (var index = 0; index < animations.length; index++) {
  26844. var animation = animations[index];
  26845. animation._target = target;
  26846. this._animations.push(animation);
  26847. }
  26848. };
  26849. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  26850. var animations = this._animations;
  26851. for (var index = 0; index < animations.length; index++) {
  26852. if (animations[index].targetProperty === property) {
  26853. return animations[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. Animatable.prototype.reset = function () {
  26859. var animations = this._animations;
  26860. for (var index = 0; index < animations.length; index++) {
  26861. animations[index].reset();
  26862. }
  26863. this._localDelayOffset = null;
  26864. this._pausedDelay = null;
  26865. };
  26866. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26867. var animations = this._animations;
  26868. for (var index = 0; index < animations.length; index++) {
  26869. animations[index].enableBlending = true;
  26870. animations[index].blendingSpeed = blendingSpeed;
  26871. }
  26872. };
  26873. Animatable.prototype.disableBlending = function () {
  26874. var animations = this._animations;
  26875. for (var index = 0; index < animations.length; index++) {
  26876. animations[index].enableBlending = false;
  26877. }
  26878. };
  26879. Animatable.prototype.goToFrame = function (frame) {
  26880. var animations = this._animations;
  26881. for (var index = 0; index < animations.length; index++) {
  26882. animations[index].goToFrame(frame);
  26883. }
  26884. };
  26885. Animatable.prototype.pause = function () {
  26886. if (this._paused) {
  26887. return;
  26888. }
  26889. this._paused = true;
  26890. };
  26891. Animatable.prototype.restart = function () {
  26892. this._paused = false;
  26893. };
  26894. Animatable.prototype.stop = function () {
  26895. var index = this._scene._activeAnimatables.indexOf(this);
  26896. if (index > -1) {
  26897. this._scene._activeAnimatables.splice(index, 1);
  26898. var animations = this._animations;
  26899. for (var index = 0; index < animations.length; index++) {
  26900. animations[index].reset();
  26901. }
  26902. if (this.onAnimationEnd) {
  26903. this.onAnimationEnd();
  26904. }
  26905. }
  26906. };
  26907. Animatable.prototype._animate = function (delay) {
  26908. if (this._paused) {
  26909. this.animationStarted = false;
  26910. if (!this._pausedDelay) {
  26911. this._pausedDelay = delay;
  26912. }
  26913. return true;
  26914. }
  26915. if (!this._localDelayOffset) {
  26916. this._localDelayOffset = delay;
  26917. }
  26918. else if (this._pausedDelay) {
  26919. this._localDelayOffset += delay - this._pausedDelay;
  26920. this._pausedDelay = null;
  26921. }
  26922. // Animating
  26923. var running = false;
  26924. var animations = this._animations;
  26925. var index;
  26926. for (index = 0; index < animations.length; index++) {
  26927. var animation = animations[index];
  26928. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26929. running = running || isRunning;
  26930. }
  26931. this.animationStarted = running;
  26932. if (!running) {
  26933. // Remove from active animatables
  26934. index = this._scene._activeAnimatables.indexOf(this);
  26935. this._scene._activeAnimatables.splice(index, 1);
  26936. }
  26937. if (!running && this.onAnimationEnd) {
  26938. this.onAnimationEnd();
  26939. this.onAnimationEnd = null;
  26940. }
  26941. return running;
  26942. };
  26943. return Animatable;
  26944. })();
  26945. BABYLON.Animatable = Animatable;
  26946. })(BABYLON || (BABYLON = {}));
  26947. var BABYLON;
  26948. (function (BABYLON) {
  26949. var EasingFunction = (function () {
  26950. function EasingFunction() {
  26951. // Properties
  26952. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26953. }
  26954. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26955. get: function () {
  26956. return EasingFunction._EASINGMODE_EASEIN;
  26957. },
  26958. enumerable: true,
  26959. configurable: true
  26960. });
  26961. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26962. get: function () {
  26963. return EasingFunction._EASINGMODE_EASEOUT;
  26964. },
  26965. enumerable: true,
  26966. configurable: true
  26967. });
  26968. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26969. get: function () {
  26970. return EasingFunction._EASINGMODE_EASEINOUT;
  26971. },
  26972. enumerable: true,
  26973. configurable: true
  26974. });
  26975. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26976. var n = Math.min(Math.max(easingMode, 0), 2);
  26977. this._easingMode = n;
  26978. };
  26979. EasingFunction.prototype.getEasingMode = function () {
  26980. return this._easingMode;
  26981. };
  26982. EasingFunction.prototype.easeInCore = function (gradient) {
  26983. throw new Error('You must implement this method');
  26984. };
  26985. EasingFunction.prototype.ease = function (gradient) {
  26986. switch (this._easingMode) {
  26987. case EasingFunction.EASINGMODE_EASEIN:
  26988. return this.easeInCore(gradient);
  26989. case EasingFunction.EASINGMODE_EASEOUT:
  26990. return (1 - this.easeInCore(1 - gradient));
  26991. }
  26992. if (gradient >= 0.5) {
  26993. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26994. }
  26995. return (this.easeInCore(gradient * 2) * 0.5);
  26996. };
  26997. //Statics
  26998. EasingFunction._EASINGMODE_EASEIN = 0;
  26999. EasingFunction._EASINGMODE_EASEOUT = 1;
  27000. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27001. return EasingFunction;
  27002. })();
  27003. BABYLON.EasingFunction = EasingFunction;
  27004. var CircleEase = (function (_super) {
  27005. __extends(CircleEase, _super);
  27006. function CircleEase() {
  27007. _super.apply(this, arguments);
  27008. }
  27009. CircleEase.prototype.easeInCore = function (gradient) {
  27010. gradient = Math.max(0, Math.min(1, gradient));
  27011. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27012. };
  27013. return CircleEase;
  27014. })(EasingFunction);
  27015. BABYLON.CircleEase = CircleEase;
  27016. var BackEase = (function (_super) {
  27017. __extends(BackEase, _super);
  27018. function BackEase(amplitude) {
  27019. if (amplitude === void 0) { amplitude = 1; }
  27020. _super.call(this);
  27021. this.amplitude = amplitude;
  27022. }
  27023. BackEase.prototype.easeInCore = function (gradient) {
  27024. var num = Math.max(0, this.amplitude);
  27025. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27026. };
  27027. return BackEase;
  27028. })(EasingFunction);
  27029. BABYLON.BackEase = BackEase;
  27030. var BounceEase = (function (_super) {
  27031. __extends(BounceEase, _super);
  27032. function BounceEase(bounces, bounciness) {
  27033. if (bounces === void 0) { bounces = 3; }
  27034. if (bounciness === void 0) { bounciness = 2; }
  27035. _super.call(this);
  27036. this.bounces = bounces;
  27037. this.bounciness = bounciness;
  27038. }
  27039. BounceEase.prototype.easeInCore = function (gradient) {
  27040. var y = Math.max(0.0, this.bounces);
  27041. var bounciness = this.bounciness;
  27042. if (bounciness <= 1.0) {
  27043. bounciness = 1.001;
  27044. }
  27045. var num9 = Math.pow(bounciness, y);
  27046. var num5 = 1.0 - bounciness;
  27047. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27048. var num15 = gradient * num4;
  27049. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27050. var num3 = Math.floor(num65);
  27051. var num13 = num3 + 1.0;
  27052. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27053. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27054. var num7 = (num8 + num12) * 0.5;
  27055. var num6 = gradient - num7;
  27056. var num2 = num7 - num8;
  27057. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27058. };
  27059. return BounceEase;
  27060. })(EasingFunction);
  27061. BABYLON.BounceEase = BounceEase;
  27062. var CubicEase = (function (_super) {
  27063. __extends(CubicEase, _super);
  27064. function CubicEase() {
  27065. _super.apply(this, arguments);
  27066. }
  27067. CubicEase.prototype.easeInCore = function (gradient) {
  27068. return (gradient * gradient * gradient);
  27069. };
  27070. return CubicEase;
  27071. })(EasingFunction);
  27072. BABYLON.CubicEase = CubicEase;
  27073. var ElasticEase = (function (_super) {
  27074. __extends(ElasticEase, _super);
  27075. function ElasticEase(oscillations, springiness) {
  27076. if (oscillations === void 0) { oscillations = 3; }
  27077. if (springiness === void 0) { springiness = 3; }
  27078. _super.call(this);
  27079. this.oscillations = oscillations;
  27080. this.springiness = springiness;
  27081. }
  27082. ElasticEase.prototype.easeInCore = function (gradient) {
  27083. var num2;
  27084. var num3 = Math.max(0.0, this.oscillations);
  27085. var num = Math.max(0.0, this.springiness);
  27086. if (num == 0) {
  27087. num2 = gradient;
  27088. }
  27089. else {
  27090. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27091. }
  27092. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27093. };
  27094. return ElasticEase;
  27095. })(EasingFunction);
  27096. BABYLON.ElasticEase = ElasticEase;
  27097. var ExponentialEase = (function (_super) {
  27098. __extends(ExponentialEase, _super);
  27099. function ExponentialEase(exponent) {
  27100. if (exponent === void 0) { exponent = 2; }
  27101. _super.call(this);
  27102. this.exponent = exponent;
  27103. }
  27104. ExponentialEase.prototype.easeInCore = function (gradient) {
  27105. if (this.exponent <= 0) {
  27106. return gradient;
  27107. }
  27108. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27109. };
  27110. return ExponentialEase;
  27111. })(EasingFunction);
  27112. BABYLON.ExponentialEase = ExponentialEase;
  27113. var PowerEase = (function (_super) {
  27114. __extends(PowerEase, _super);
  27115. function PowerEase(power) {
  27116. if (power === void 0) { power = 2; }
  27117. _super.call(this);
  27118. this.power = power;
  27119. }
  27120. PowerEase.prototype.easeInCore = function (gradient) {
  27121. var y = Math.max(0.0, this.power);
  27122. return Math.pow(gradient, y);
  27123. };
  27124. return PowerEase;
  27125. })(EasingFunction);
  27126. BABYLON.PowerEase = PowerEase;
  27127. var QuadraticEase = (function (_super) {
  27128. __extends(QuadraticEase, _super);
  27129. function QuadraticEase() {
  27130. _super.apply(this, arguments);
  27131. }
  27132. QuadraticEase.prototype.easeInCore = function (gradient) {
  27133. return (gradient * gradient);
  27134. };
  27135. return QuadraticEase;
  27136. })(EasingFunction);
  27137. BABYLON.QuadraticEase = QuadraticEase;
  27138. var QuarticEase = (function (_super) {
  27139. __extends(QuarticEase, _super);
  27140. function QuarticEase() {
  27141. _super.apply(this, arguments);
  27142. }
  27143. QuarticEase.prototype.easeInCore = function (gradient) {
  27144. return (gradient * gradient * gradient * gradient);
  27145. };
  27146. return QuarticEase;
  27147. })(EasingFunction);
  27148. BABYLON.QuarticEase = QuarticEase;
  27149. var QuinticEase = (function (_super) {
  27150. __extends(QuinticEase, _super);
  27151. function QuinticEase() {
  27152. _super.apply(this, arguments);
  27153. }
  27154. QuinticEase.prototype.easeInCore = function (gradient) {
  27155. return (gradient * gradient * gradient * gradient * gradient);
  27156. };
  27157. return QuinticEase;
  27158. })(EasingFunction);
  27159. BABYLON.QuinticEase = QuinticEase;
  27160. var SineEase = (function (_super) {
  27161. __extends(SineEase, _super);
  27162. function SineEase() {
  27163. _super.apply(this, arguments);
  27164. }
  27165. SineEase.prototype.easeInCore = function (gradient) {
  27166. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27167. };
  27168. return SineEase;
  27169. })(EasingFunction);
  27170. BABYLON.SineEase = SineEase;
  27171. var BezierCurveEase = (function (_super) {
  27172. __extends(BezierCurveEase, _super);
  27173. function BezierCurveEase(x1, y1, x2, y2) {
  27174. if (x1 === void 0) { x1 = 0; }
  27175. if (y1 === void 0) { y1 = 0; }
  27176. if (x2 === void 0) { x2 = 1; }
  27177. if (y2 === void 0) { y2 = 1; }
  27178. _super.call(this);
  27179. this.x1 = x1;
  27180. this.y1 = y1;
  27181. this.x2 = x2;
  27182. this.y2 = y2;
  27183. }
  27184. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27185. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27186. };
  27187. return BezierCurveEase;
  27188. })(EasingFunction);
  27189. BABYLON.BezierCurveEase = BezierCurveEase;
  27190. })(BABYLON || (BABYLON = {}));
  27191. var BABYLON;
  27192. (function (BABYLON) {
  27193. var Bone = (function (_super) {
  27194. __extends(Bone, _super);
  27195. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27196. _super.call(this, name, skeleton.getScene());
  27197. this.name = name;
  27198. this.children = new Array();
  27199. this.animations = new Array();
  27200. this._worldTransform = new BABYLON.Matrix();
  27201. this._absoluteTransform = new BABYLON.Matrix();
  27202. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27203. this._skeleton = skeleton;
  27204. this._matrix = matrix;
  27205. this._baseMatrix = matrix;
  27206. this._restPose = restPose ? restPose : matrix.clone();
  27207. skeleton.bones.push(this);
  27208. if (parentBone) {
  27209. this._parent = parentBone;
  27210. parentBone.children.push(this);
  27211. }
  27212. else {
  27213. this._parent = null;
  27214. }
  27215. this._updateDifferenceMatrix();
  27216. }
  27217. // Members
  27218. Bone.prototype.getParent = function () {
  27219. return this._parent;
  27220. };
  27221. Bone.prototype.getLocalMatrix = function () {
  27222. return this._matrix;
  27223. };
  27224. Bone.prototype.getBaseMatrix = function () {
  27225. return this._baseMatrix;
  27226. };
  27227. Bone.prototype.getRestPose = function () {
  27228. return this._restPose;
  27229. };
  27230. Bone.prototype.returnToRest = function () {
  27231. this.updateMatrix(this._restPose.clone());
  27232. };
  27233. Bone.prototype.getWorldMatrix = function () {
  27234. return this._worldTransform;
  27235. };
  27236. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27237. return this._invertedAbsoluteTransform;
  27238. };
  27239. Bone.prototype.getAbsoluteTransform = function () {
  27240. return this._absoluteTransform;
  27241. };
  27242. // Methods
  27243. Bone.prototype.updateMatrix = function (matrix) {
  27244. this._baseMatrix = matrix.clone();
  27245. this._matrix = matrix.clone();
  27246. this._skeleton._markAsDirty();
  27247. this._updateDifferenceMatrix();
  27248. };
  27249. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27250. if (!rootMatrix) {
  27251. rootMatrix = this._baseMatrix;
  27252. }
  27253. if (this._parent) {
  27254. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27255. }
  27256. else {
  27257. this._absoluteTransform.copyFrom(rootMatrix);
  27258. }
  27259. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27260. for (var index = 0; index < this.children.length; index++) {
  27261. this.children[index]._updateDifferenceMatrix();
  27262. }
  27263. };
  27264. Bone.prototype.markAsDirty = function () {
  27265. this._currentRenderId++;
  27266. this._skeleton._markAsDirty();
  27267. };
  27268. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27269. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27270. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27271. // all animation may be coming from a library skeleton, so may need to create animation
  27272. if (this.animations.length === 0) {
  27273. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27274. this.animations[0].setKeys([]);
  27275. }
  27276. // get animation info / verify there is such a range from the source bone
  27277. var sourceRange = source.animations[0].getRange(rangeName);
  27278. if (!sourceRange) {
  27279. return false;
  27280. }
  27281. var from = sourceRange.from;
  27282. var to = sourceRange.to;
  27283. var sourceKeys = source.animations[0].getKeys();
  27284. // rescaling prep
  27285. var sourceBoneLength = source.length;
  27286. var sourceParent = source.getParent();
  27287. var parent = this.getParent();
  27288. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27289. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27290. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27291. var destKeys = this.animations[0].getKeys();
  27292. // loop vars declaration
  27293. var orig;
  27294. var origTranslation;
  27295. var mat;
  27296. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27297. orig = sourceKeys[key];
  27298. if (orig.frame >= from && orig.frame <= to) {
  27299. if (rescaleAsRequired) {
  27300. mat = orig.value.clone();
  27301. // scale based on parent ratio, when bone has parent
  27302. if (parentScalingReqd) {
  27303. origTranslation = mat.getTranslation();
  27304. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27305. }
  27306. else if (dimensionsScalingReqd) {
  27307. origTranslation = mat.getTranslation();
  27308. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27309. }
  27310. else {
  27311. mat = orig.value;
  27312. }
  27313. }
  27314. else {
  27315. mat = orig.value;
  27316. }
  27317. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27318. }
  27319. }
  27320. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27321. return true;
  27322. };
  27323. return Bone;
  27324. })(BABYLON.Node);
  27325. BABYLON.Bone = Bone;
  27326. })(BABYLON || (BABYLON = {}));
  27327. var BABYLON;
  27328. (function (BABYLON) {
  27329. var Skeleton = (function () {
  27330. function Skeleton(name, id, scene) {
  27331. this.name = name;
  27332. this.id = id;
  27333. this.bones = new Array();
  27334. this.needInitialSkinMatrix = false;
  27335. this._isDirty = true;
  27336. this._meshesWithPoseMatrix = new Array();
  27337. this._identity = BABYLON.Matrix.Identity();
  27338. this._ranges = {};
  27339. this.bones = [];
  27340. this._scene = scene;
  27341. scene.skeletons.push(this);
  27342. //make sure it will recalculate the matrix next time prepare is called.
  27343. this._isDirty = true;
  27344. }
  27345. // Members
  27346. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27347. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27348. return mesh._bonesTransformMatrices;
  27349. }
  27350. return this._transformMatrices;
  27351. };
  27352. Skeleton.prototype.getScene = function () {
  27353. return this._scene;
  27354. };
  27355. // Methods
  27356. /**
  27357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27358. */
  27359. Skeleton.prototype.toString = function (fullDetails) {
  27360. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27361. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27362. if (fullDetails) {
  27363. ret += ", Ranges: {";
  27364. var first = true;
  27365. for (var name_1 in this._ranges) {
  27366. if (first) {
  27367. ret += ", ";
  27368. first = false;
  27369. }
  27370. ret += name_1;
  27371. }
  27372. ret += "}";
  27373. }
  27374. return ret;
  27375. };
  27376. /**
  27377. * Get bone's index searching by name
  27378. * @param {string} name is bone's name to search for
  27379. * @return {number} Indice of the bone. Returns -1 if not found
  27380. */
  27381. Skeleton.prototype.getBoneIndexByName = function (name) {
  27382. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27383. if (this.bones[boneIndex].name === name) {
  27384. return boneIndex;
  27385. }
  27386. }
  27387. return -1;
  27388. };
  27389. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27390. // check name not already in use
  27391. if (!this._ranges[name]) {
  27392. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27393. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27394. if (this.bones[i].animations[0]) {
  27395. this.bones[i].animations[0].createRange(name, from, to);
  27396. }
  27397. }
  27398. }
  27399. };
  27400. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27401. if (deleteFrames === void 0) { deleteFrames = true; }
  27402. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27403. if (this.bones[i].animations[0]) {
  27404. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27405. }
  27406. }
  27407. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27408. };
  27409. Skeleton.prototype.getAnimationRange = function (name) {
  27410. return this._ranges[name];
  27411. };
  27412. /**
  27413. * Returns as an Array, all AnimationRanges defined on this skeleton
  27414. */
  27415. Skeleton.prototype.getAnimationRanges = function () {
  27416. var animationRanges = [];
  27417. var name;
  27418. var i = 0;
  27419. for (name in this._ranges) {
  27420. animationRanges[i] = this._ranges[name];
  27421. i++;
  27422. }
  27423. return animationRanges;
  27424. };
  27425. /**
  27426. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27427. */
  27428. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27429. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27430. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27431. return false;
  27432. }
  27433. var ret = true;
  27434. var frameOffset = this._getHighestAnimationFrame() + 1;
  27435. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27436. var boneDict = {};
  27437. var sourceBones = source.bones;
  27438. var nBones;
  27439. var i;
  27440. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27441. boneDict[sourceBones[i].name] = sourceBones[i];
  27442. }
  27443. if (this.bones.length !== sourceBones.length) {
  27444. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27445. ret = false;
  27446. }
  27447. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  27448. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27449. var boneName = this.bones[i].name;
  27450. var sourceBone = boneDict[boneName];
  27451. if (sourceBone) {
  27452. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  27453. }
  27454. else {
  27455. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27456. ret = false;
  27457. }
  27458. }
  27459. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27460. var range = source.getAnimationRange(name);
  27461. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27462. return ret;
  27463. };
  27464. Skeleton.prototype.returnToRest = function () {
  27465. for (var index = 0; index < this.bones.length; index++) {
  27466. this.bones[index].returnToRest();
  27467. }
  27468. };
  27469. Skeleton.prototype._getHighestAnimationFrame = function () {
  27470. var ret = 0;
  27471. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27472. if (this.bones[i].animations[0]) {
  27473. var highest = this.bones[i].animations[0].getHighestFrame();
  27474. if (ret < highest) {
  27475. ret = highest;
  27476. }
  27477. }
  27478. }
  27479. return ret;
  27480. };
  27481. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27482. var range = this.getAnimationRange(name);
  27483. if (!range) {
  27484. return null;
  27485. }
  27486. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27487. };
  27488. Skeleton.prototype._markAsDirty = function () {
  27489. this._isDirty = true;
  27490. };
  27491. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27492. this._meshesWithPoseMatrix.push(mesh);
  27493. };
  27494. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27495. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27496. if (index > -1) {
  27497. this._meshesWithPoseMatrix.splice(index, 1);
  27498. }
  27499. };
  27500. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27501. for (var index = 0; index < this.bones.length; index++) {
  27502. var bone = this.bones[index];
  27503. var parentBone = bone.getParent();
  27504. if (parentBone) {
  27505. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27506. }
  27507. else {
  27508. if (initialSkinMatrix) {
  27509. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  27510. }
  27511. else {
  27512. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  27513. }
  27514. }
  27515. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  27516. }
  27517. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  27518. };
  27519. Skeleton.prototype.prepare = function () {
  27520. if (!this._isDirty) {
  27521. return;
  27522. }
  27523. if (this.needInitialSkinMatrix) {
  27524. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  27525. var mesh = this._meshesWithPoseMatrix[index];
  27526. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  27527. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27528. }
  27529. var poseMatrix = mesh.getPoseMatrix();
  27530. // Prepare bones
  27531. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27532. var bone = this.bones[boneIndex];
  27533. if (!bone.getParent()) {
  27534. var matrix = bone.getBaseMatrix();
  27535. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27536. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27537. }
  27538. }
  27539. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27540. }
  27541. }
  27542. else {
  27543. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27544. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27545. }
  27546. this._computeTransformMatrices(this._transformMatrices, null);
  27547. }
  27548. this._isDirty = false;
  27549. this._scene._activeBones += this.bones.length;
  27550. };
  27551. Skeleton.prototype.getAnimatables = function () {
  27552. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27553. this._animatables = [];
  27554. for (var index = 0; index < this.bones.length; index++) {
  27555. this._animatables.push(this.bones[index]);
  27556. }
  27557. }
  27558. return this._animatables;
  27559. };
  27560. Skeleton.prototype.clone = function (name, id) {
  27561. var result = new Skeleton(name, id || name, this._scene);
  27562. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27563. for (var index = 0; index < this.bones.length; index++) {
  27564. var source = this.bones[index];
  27565. var parentBone = null;
  27566. if (source.getParent()) {
  27567. var parentIndex = this.bones.indexOf(source.getParent());
  27568. parentBone = result.bones[parentIndex];
  27569. }
  27570. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  27571. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  27572. }
  27573. if (this._ranges) {
  27574. result._ranges = {};
  27575. for (var rangeName in this._ranges) {
  27576. result._ranges[rangeName] = this._ranges[rangeName].clone();
  27577. }
  27578. }
  27579. this._isDirty = true;
  27580. return result;
  27581. };
  27582. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  27583. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  27584. this.bones.forEach(function (bone) {
  27585. bone.animations.forEach(function (animation) {
  27586. animation.enableBlending = true;
  27587. animation.blendingSpeed = blendingSpeed;
  27588. });
  27589. });
  27590. };
  27591. Skeleton.prototype.dispose = function () {
  27592. this._meshesWithPoseMatrix = [];
  27593. // Animations
  27594. this.getScene().stopAnimation(this);
  27595. // Remove from scene
  27596. this.getScene().removeSkeleton(this);
  27597. };
  27598. Skeleton.prototype.serialize = function () {
  27599. var serializationObject = {};
  27600. serializationObject.name = this.name;
  27601. serializationObject.id = this.id;
  27602. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  27603. serializationObject.bones = [];
  27604. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27605. for (var index = 0; index < this.bones.length; index++) {
  27606. var bone = this.bones[index];
  27607. var serializedBone = {
  27608. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  27609. name: bone.name,
  27610. matrix: bone.getLocalMatrix().toArray(),
  27611. rest: bone.getRestPose().toArray()
  27612. };
  27613. serializationObject.bones.push(serializedBone);
  27614. if (bone.length) {
  27615. serializedBone.length = bone.length;
  27616. }
  27617. if (bone.animations && bone.animations.length > 0) {
  27618. serializedBone.animation = bone.animations[0].serialize();
  27619. }
  27620. serializationObject.ranges = [];
  27621. for (var name in this._ranges) {
  27622. var range = {};
  27623. range.name = name;
  27624. range.from = this._ranges[name].from;
  27625. range.to = this._ranges[name].to;
  27626. serializationObject.ranges.push(range);
  27627. }
  27628. }
  27629. return serializationObject;
  27630. };
  27631. Skeleton.Parse = function (parsedSkeleton, scene) {
  27632. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  27633. if (parsedSkeleton.dimensionsAtRest) {
  27634. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  27635. }
  27636. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  27637. var index;
  27638. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  27639. var parsedBone = parsedSkeleton.bones[index];
  27640. var parentBone = null;
  27641. if (parsedBone.parentBoneIndex > -1) {
  27642. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  27643. }
  27644. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  27645. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  27646. if (parsedBone.length) {
  27647. bone.length = parsedBone.length;
  27648. }
  27649. if (parsedBone.animation) {
  27650. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  27651. }
  27652. }
  27653. // placed after bones, so createAnimationRange can cascade down
  27654. if (parsedSkeleton.ranges) {
  27655. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  27656. var data = parsedSkeleton.ranges[index];
  27657. skeleton.createAnimationRange(data.name, data.from, data.to);
  27658. }
  27659. }
  27660. return skeleton;
  27661. };
  27662. return Skeleton;
  27663. })();
  27664. BABYLON.Skeleton = Skeleton;
  27665. })(BABYLON || (BABYLON = {}));
  27666. var BABYLON;
  27667. (function (BABYLON) {
  27668. var PostProcess = (function () {
  27669. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  27670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  27671. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27672. this.name = name;
  27673. this.width = -1;
  27674. this.height = -1;
  27675. /*
  27676. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  27677. Can only be used on a single postprocess or on the last one of a chain.
  27678. */
  27679. this.enablePixelPerfectMode = false;
  27680. this._reusable = false;
  27681. this._textures = new BABYLON.SmartArray(2);
  27682. this._currentRenderTextureInd = 0;
  27683. this._scaleRatio = new BABYLON.Vector2(1, 1);
  27684. // Events
  27685. /**
  27686. * An event triggered when the postprocess is activated.
  27687. * @type {BABYLON.Observable}
  27688. */
  27689. this.onActivateObservable = new BABYLON.Observable();
  27690. /**
  27691. * An event triggered when the postprocess changes its size.
  27692. * @type {BABYLON.Observable}
  27693. */
  27694. this.onSizeChangedObservable = new BABYLON.Observable();
  27695. /**
  27696. * An event triggered when the postprocess applies its effect.
  27697. * @type {BABYLON.Observable}
  27698. */
  27699. this.onApplyObservable = new BABYLON.Observable();
  27700. /**
  27701. * An event triggered before rendering the postprocess
  27702. * @type {BABYLON.Observable}
  27703. */
  27704. this.onBeforeRenderObservable = new BABYLON.Observable();
  27705. /**
  27706. * An event triggered after rendering the postprocess
  27707. * @type {BABYLON.Observable}
  27708. */
  27709. this.onAfterRenderObservable = new BABYLON.Observable();
  27710. if (camera != null) {
  27711. this._camera = camera;
  27712. this._scene = camera.getScene();
  27713. camera.attachPostProcess(this);
  27714. this._engine = this._scene.getEngine();
  27715. }
  27716. else {
  27717. this._engine = engine;
  27718. }
  27719. this._options = options;
  27720. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  27721. this._reusable = reusable || false;
  27722. this._textureType = textureType;
  27723. this._samplers = samplers || [];
  27724. this._samplers.push("textureSampler");
  27725. this._fragmentUrl = fragmentUrl;
  27726. this._parameters = parameters || [];
  27727. this._parameters.push("scale");
  27728. this.updateEffect(defines);
  27729. }
  27730. Object.defineProperty(PostProcess.prototype, "onActivate", {
  27731. set: function (callback) {
  27732. if (this._onActivateObserver) {
  27733. this.onActivateObservable.remove(this._onActivateObserver);
  27734. }
  27735. this._onActivateObserver = this.onActivateObservable.add(callback);
  27736. },
  27737. enumerable: true,
  27738. configurable: true
  27739. });
  27740. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  27741. set: function (callback) {
  27742. if (this._onSizeChangedObserver) {
  27743. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  27744. }
  27745. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  27746. },
  27747. enumerable: true,
  27748. configurable: true
  27749. });
  27750. Object.defineProperty(PostProcess.prototype, "onApply", {
  27751. set: function (callback) {
  27752. if (this._onApplyObserver) {
  27753. this.onApplyObservable.remove(this._onApplyObserver);
  27754. }
  27755. this._onApplyObserver = this.onApplyObservable.add(callback);
  27756. },
  27757. enumerable: true,
  27758. configurable: true
  27759. });
  27760. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  27761. set: function (callback) {
  27762. if (this._onBeforeRenderObserver) {
  27763. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27764. }
  27765. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27766. },
  27767. enumerable: true,
  27768. configurable: true
  27769. });
  27770. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  27771. set: function (callback) {
  27772. if (this._onAfterRenderObserver) {
  27773. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27774. }
  27775. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27776. },
  27777. enumerable: true,
  27778. configurable: true
  27779. });
  27780. PostProcess.prototype.updateEffect = function (defines) {
  27781. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  27782. };
  27783. PostProcess.prototype.isReusable = function () {
  27784. return this._reusable;
  27785. };
  27786. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  27787. PostProcess.prototype.markTextureDirty = function () {
  27788. this.width = -1;
  27789. };
  27790. PostProcess.prototype.activate = function (camera, sourceTexture) {
  27791. camera = camera || this._camera;
  27792. var scene = camera.getScene();
  27793. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  27794. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  27795. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  27796. var desiredWidth = this._options.width || requiredWidth;
  27797. var desiredHeight = this._options.height || requiredHeight;
  27798. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27799. if (!this._options.width) {
  27800. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  27801. }
  27802. if (!this._options.height) {
  27803. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  27804. }
  27805. }
  27806. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  27807. if (this._textures.length > 0) {
  27808. for (var i = 0; i < this._textures.length; i++) {
  27809. this._engine._releaseTexture(this._textures.data[i]);
  27810. }
  27811. this._textures.reset();
  27812. }
  27813. this.width = desiredWidth;
  27814. this.height = desiredHeight;
  27815. 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 }));
  27816. if (this._reusable) {
  27817. 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 }));
  27818. }
  27819. this.onSizeChangedObservable.notifyObservers(this);
  27820. }
  27821. if (this.enablePixelPerfectMode) {
  27822. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  27823. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  27824. }
  27825. else {
  27826. this._scaleRatio.copyFromFloats(1, 1);
  27827. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  27828. }
  27829. this.onActivateObservable.notifyObservers(camera);
  27830. // Clear
  27831. if (this.clearColor) {
  27832. this._engine.clear(this.clearColor, true, true);
  27833. }
  27834. else {
  27835. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  27836. }
  27837. if (this._reusable) {
  27838. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  27839. }
  27840. };
  27841. Object.defineProperty(PostProcess.prototype, "isSupported", {
  27842. get: function () {
  27843. return this._effect.isSupported;
  27844. },
  27845. enumerable: true,
  27846. configurable: true
  27847. });
  27848. PostProcess.prototype.apply = function () {
  27849. // Check
  27850. if (!this._effect.isReady())
  27851. return null;
  27852. // States
  27853. this._engine.enableEffect(this._effect);
  27854. this._engine.setState(false);
  27855. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27856. this._engine.setDepthBuffer(false);
  27857. this._engine.setDepthWrite(false);
  27858. // Texture
  27859. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  27860. // Parameters
  27861. this._effect.setVector2("scale", this._scaleRatio);
  27862. this.onApplyObservable.notifyObservers(this._effect);
  27863. return this._effect;
  27864. };
  27865. PostProcess.prototype.dispose = function (camera) {
  27866. camera = camera || this._camera;
  27867. if (this._textures.length > 0) {
  27868. for (var i = 0; i < this._textures.length; i++) {
  27869. this._engine._releaseTexture(this._textures.data[i]);
  27870. }
  27871. this._textures.reset();
  27872. }
  27873. if (!camera) {
  27874. return;
  27875. }
  27876. camera.detachPostProcess(this);
  27877. var index = camera._postProcesses.indexOf(this);
  27878. if (index === 0 && camera._postProcesses.length > 0) {
  27879. this._camera._postProcesses[0].markTextureDirty();
  27880. }
  27881. this.onActivateObservable.clear();
  27882. this.onAfterRenderObservable.clear();
  27883. this.onApplyObservable.clear();
  27884. this.onBeforeRenderObservable.clear();
  27885. this.onSizeChangedObservable.clear();
  27886. };
  27887. return PostProcess;
  27888. })();
  27889. BABYLON.PostProcess = PostProcess;
  27890. })(BABYLON || (BABYLON = {}));
  27891. var BABYLON;
  27892. (function (BABYLON) {
  27893. var PostProcessManager = (function () {
  27894. function PostProcessManager(scene) {
  27895. this._vertexBuffers = {};
  27896. this._scene = scene;
  27897. }
  27898. PostProcessManager.prototype._prepareBuffers = function () {
  27899. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27900. return;
  27901. }
  27902. // VBO
  27903. var vertices = [];
  27904. vertices.push(1, 1);
  27905. vertices.push(-1, 1);
  27906. vertices.push(-1, -1);
  27907. vertices.push(1, -1);
  27908. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27909. // Indices
  27910. var indices = [];
  27911. indices.push(0);
  27912. indices.push(1);
  27913. indices.push(2);
  27914. indices.push(0);
  27915. indices.push(2);
  27916. indices.push(3);
  27917. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27918. };
  27919. // Methods
  27920. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27921. var postProcesses = this._scene.activeCamera._postProcesses;
  27922. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27923. return false;
  27924. }
  27925. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27926. return true;
  27927. };
  27928. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27929. var engine = this._scene.getEngine();
  27930. for (var index = 0; index < postProcesses.length; index++) {
  27931. if (index < postProcesses.length - 1) {
  27932. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27933. }
  27934. else {
  27935. if (targetTexture) {
  27936. engine.bindFramebuffer(targetTexture);
  27937. }
  27938. else {
  27939. engine.restoreDefaultFramebuffer();
  27940. }
  27941. }
  27942. var pp = postProcesses[index];
  27943. var effect = pp.apply();
  27944. if (effect) {
  27945. pp.onBeforeRenderObservable.notifyObservers(effect);
  27946. // VBOs
  27947. this._prepareBuffers();
  27948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27949. // Draw order
  27950. engine.draw(true, 0, 6);
  27951. pp.onAfterRenderObservable.notifyObservers(effect);
  27952. }
  27953. }
  27954. // Restore depth buffer
  27955. engine.setDepthBuffer(true);
  27956. engine.setDepthWrite(true);
  27957. };
  27958. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27959. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27960. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27961. return;
  27962. }
  27963. var engine = this._scene.getEngine();
  27964. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27965. if (index < len - 1) {
  27966. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27967. }
  27968. else {
  27969. if (targetTexture) {
  27970. engine.bindFramebuffer(targetTexture, faceIndex);
  27971. }
  27972. else {
  27973. engine.restoreDefaultFramebuffer();
  27974. }
  27975. }
  27976. if (doNotPresent) {
  27977. break;
  27978. }
  27979. var pp = postProcesses[index];
  27980. var effect = pp.apply();
  27981. if (effect) {
  27982. pp.onBeforeRenderObservable.notifyObservers(effect);
  27983. // VBOs
  27984. this._prepareBuffers();
  27985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27986. // Draw order
  27987. engine.draw(true, 0, 6);
  27988. pp.onAfterRenderObservable.notifyObservers(effect);
  27989. }
  27990. }
  27991. // Restore depth buffer
  27992. engine.setDepthBuffer(true);
  27993. engine.setDepthWrite(true);
  27994. };
  27995. PostProcessManager.prototype.dispose = function () {
  27996. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27997. if (buffer) {
  27998. buffer.dispose();
  27999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28000. }
  28001. if (this._indexBuffer) {
  28002. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28003. this._indexBuffer = null;
  28004. }
  28005. };
  28006. return PostProcessManager;
  28007. })();
  28008. BABYLON.PostProcessManager = PostProcessManager;
  28009. })(BABYLON || (BABYLON = {}));
  28010. var BABYLON;
  28011. (function (BABYLON) {
  28012. var PassPostProcess = (function (_super) {
  28013. __extends(PassPostProcess, _super);
  28014. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28015. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28016. }
  28017. return PassPostProcess;
  28018. })(BABYLON.PostProcess);
  28019. BABYLON.PassPostProcess = PassPostProcess;
  28020. })(BABYLON || (BABYLON = {}));
  28021. var BABYLON;
  28022. (function (BABYLON) {
  28023. /**
  28024. * This is a holder class for the physics joint created by the physics plugin.
  28025. * It holds a set of functions to control the underlying joint.
  28026. */
  28027. var PhysicsJoint = (function () {
  28028. function PhysicsJoint(type, jointData) {
  28029. this.type = type;
  28030. this.jointData = jointData;
  28031. jointData.nativeParams = jointData.nativeParams || {};
  28032. }
  28033. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28034. get: function () {
  28035. return this._physicsJoint;
  28036. },
  28037. set: function (newJoint) {
  28038. if (this._physicsJoint) {
  28039. }
  28040. this._physicsJoint = newJoint;
  28041. },
  28042. enumerable: true,
  28043. configurable: true
  28044. });
  28045. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28046. set: function (physicsPlugin) {
  28047. this._physicsPlugin = physicsPlugin;
  28048. },
  28049. enumerable: true,
  28050. configurable: true
  28051. });
  28052. /**
  28053. * Execute a function that is physics-plugin specific.
  28054. * @param {Function} func the function that will be executed.
  28055. * It accepts two parameters: the physics world and the physics joint.
  28056. */
  28057. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28058. func(this._physicsPlugin.world, this._physicsJoint);
  28059. };
  28060. //TODO check if the native joints are the same
  28061. //Joint Types
  28062. PhysicsJoint.DistanceJoint = 0;
  28063. PhysicsJoint.HingeJoint = 1;
  28064. PhysicsJoint.BallAndSocketJoint = 2;
  28065. PhysicsJoint.WheelJoint = 3;
  28066. PhysicsJoint.SliderJoint = 4;
  28067. //OIMO
  28068. PhysicsJoint.PrismaticJoint = 5;
  28069. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28070. PhysicsJoint.UniversalJoint = 6;
  28071. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28072. //Cannon
  28073. //Similar to a Ball-Joint. Different in params
  28074. PhysicsJoint.PointToPointJoint = 8;
  28075. //Cannon only at the moment
  28076. PhysicsJoint.SpringJoint = 9;
  28077. PhysicsJoint.LockJoint = 10;
  28078. return PhysicsJoint;
  28079. })();
  28080. BABYLON.PhysicsJoint = PhysicsJoint;
  28081. /**
  28082. * A class representing a physics distance joint.
  28083. */
  28084. var DistanceJoint = (function (_super) {
  28085. __extends(DistanceJoint, _super);
  28086. function DistanceJoint(jointData) {
  28087. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28088. }
  28089. /**
  28090. * Update the predefined distance.
  28091. */
  28092. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28093. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28094. };
  28095. return DistanceJoint;
  28096. })(PhysicsJoint);
  28097. BABYLON.DistanceJoint = DistanceJoint;
  28098. var MotorEnabledJoint = (function (_super) {
  28099. __extends(MotorEnabledJoint, _super);
  28100. function MotorEnabledJoint(type, jointData) {
  28101. _super.call(this, type, jointData);
  28102. }
  28103. /**
  28104. * Set the motor values.
  28105. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28106. * @param {number} force the force to apply
  28107. * @param {number} maxForce max force for this motor.
  28108. */
  28109. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28110. this._physicsPlugin.setMotor(this, force, maxForce);
  28111. };
  28112. /**
  28113. * Set the motor's limits.
  28114. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28115. */
  28116. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28117. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28118. };
  28119. return MotorEnabledJoint;
  28120. })(PhysicsJoint);
  28121. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28122. /**
  28123. * This class represents a single hinge physics joint
  28124. */
  28125. var HingeJoint = (function (_super) {
  28126. __extends(HingeJoint, _super);
  28127. function HingeJoint(jointData) {
  28128. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28129. }
  28130. /**
  28131. * Set the motor values.
  28132. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28133. * @param {number} force the force to apply
  28134. * @param {number} maxForce max force for this motor.
  28135. */
  28136. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28137. this._physicsPlugin.setMotor(this, force, maxForce);
  28138. };
  28139. /**
  28140. * Set the motor's limits.
  28141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28142. */
  28143. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28144. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28145. };
  28146. return HingeJoint;
  28147. })(MotorEnabledJoint);
  28148. BABYLON.HingeJoint = HingeJoint;
  28149. /**
  28150. * This class represents a dual hinge physics joint (same as wheel joint)
  28151. */
  28152. var Hinge2Joint = (function (_super) {
  28153. __extends(Hinge2Joint, _super);
  28154. function Hinge2Joint(jointData) {
  28155. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28156. }
  28157. /**
  28158. * Set the motor values.
  28159. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28160. * @param {number} force the force to apply
  28161. * @param {number} maxForce max force for this motor.
  28162. * @param {motorIndex} the motor's index, 0 or 1.
  28163. */
  28164. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28165. if (motorIndex === void 0) { motorIndex = 0; }
  28166. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28167. };
  28168. /**
  28169. * Set the motor limits.
  28170. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28171. * @param {number} upperLimit the upper limit
  28172. * @param {number} lowerLimit lower limit
  28173. * @param {motorIndex} the motor's index, 0 or 1.
  28174. */
  28175. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28176. if (motorIndex === void 0) { motorIndex = 0; }
  28177. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28178. };
  28179. return Hinge2Joint;
  28180. })(MotorEnabledJoint);
  28181. BABYLON.Hinge2Joint = Hinge2Joint;
  28182. })(BABYLON || (BABYLON = {}));
  28183. var BABYLON;
  28184. (function (BABYLON) {
  28185. var PhysicsImpostor = (function () {
  28186. function PhysicsImpostor(object, type, _options, _scene) {
  28187. var _this = this;
  28188. if (_options === void 0) { _options = { mass: 0 }; }
  28189. this.object = object;
  28190. this.type = type;
  28191. this._options = _options;
  28192. this._scene = _scene;
  28193. this._bodyUpdateRequired = false;
  28194. this._onBeforePhysicsStepCallbacks = new Array();
  28195. this._onAfterPhysicsStepCallbacks = new Array();
  28196. this._onPhysicsCollideCallbacks = [];
  28197. this._deltaPosition = BABYLON.Vector3.Zero();
  28198. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28199. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28200. /**
  28201. * this function is executed by the physics engine.
  28202. */
  28203. this.beforeStep = function () {
  28204. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28205. //conjugate deltaRotation
  28206. if (_this._deltaRotationConjugated) {
  28207. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28208. }
  28209. else {
  28210. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28211. }
  28212. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28213. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28214. func(_this);
  28215. });
  28216. };
  28217. /**
  28218. * this function is executed by the physics engine.
  28219. */
  28220. this.afterStep = function () {
  28221. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28222. func(_this);
  28223. });
  28224. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28225. _this.object.position.addInPlace(_this._deltaPosition);
  28226. if (_this._deltaRotation) {
  28227. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28228. }
  28229. };
  28230. //event and body object due to cannon's event-based architecture.
  28231. this.onCollide = function (e) {
  28232. if (!_this._onPhysicsCollideCallbacks.length)
  28233. return;
  28234. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28235. if (otherImpostor) {
  28236. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28237. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28238. }).forEach(function (obj) {
  28239. obj.callback(_this, otherImpostor);
  28240. });
  28241. }
  28242. };
  28243. //sanity check!
  28244. if (!this.object) {
  28245. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28246. return;
  28247. }
  28248. //legacy support for old syntax.
  28249. if (!this._scene && object.getScene) {
  28250. this._scene = object.getScene();
  28251. }
  28252. this._physicsEngine = this._scene.getPhysicsEngine();
  28253. if (!this._physicsEngine) {
  28254. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28255. }
  28256. else {
  28257. //set the object's quaternion, if not set
  28258. if (!this.object.rotationQuaternion) {
  28259. if (this.object.rotation) {
  28260. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28261. }
  28262. else {
  28263. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28264. }
  28265. }
  28266. //default options params
  28267. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28268. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28269. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28270. this._joints = [];
  28271. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28272. if (!this.object.parent) {
  28273. this._init();
  28274. }
  28275. }
  28276. }
  28277. /**
  28278. * This function will completly initialize this impostor.
  28279. * It will create a new body - but only if this mesh has no parent.
  28280. * If it has, this impostor will not be used other than to define the impostor
  28281. * of the child mesh.
  28282. */
  28283. PhysicsImpostor.prototype._init = function () {
  28284. this._physicsEngine.removeImpostor(this);
  28285. this.physicsBody = null;
  28286. this._parent = this._parent || this._getPhysicsParent();
  28287. if (!this.parent) {
  28288. this._physicsEngine.addImpostor(this);
  28289. }
  28290. };
  28291. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28292. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28293. var parentMesh = this.object.parent;
  28294. return parentMesh.physicsImpostor;
  28295. }
  28296. return;
  28297. };
  28298. /**
  28299. * Should a new body be generated.
  28300. */
  28301. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28302. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28303. };
  28304. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28305. this.forceUpdate();
  28306. };
  28307. /**
  28308. * Force a regeneration of this or the parent's impostor's body.
  28309. * Use under cautious - This will remove all joints already implemented.
  28310. */
  28311. PhysicsImpostor.prototype.forceUpdate = function () {
  28312. this._init();
  28313. if (this.parent) {
  28314. this.parent.forceUpdate();
  28315. }
  28316. };
  28317. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28318. /*public get mesh(): AbstractMesh {
  28319. return this._mesh;
  28320. }*/
  28321. /**
  28322. * Gets the body that holds this impostor. Either its own, or its parent.
  28323. */
  28324. get: function () {
  28325. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28326. },
  28327. /**
  28328. * Set the physics body. Used mainly by the physics engine/plugin
  28329. */
  28330. set: function (physicsBody) {
  28331. if (this._physicsBody) {
  28332. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28333. }
  28334. this._physicsBody = physicsBody;
  28335. this.resetUpdateFlags();
  28336. },
  28337. enumerable: true,
  28338. configurable: true
  28339. });
  28340. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28341. get: function () {
  28342. return this._parent;
  28343. },
  28344. enumerable: true,
  28345. configurable: true
  28346. });
  28347. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28348. this._bodyUpdateRequired = false;
  28349. };
  28350. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28351. if (this.object.getBoundingInfo) {
  28352. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28353. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28354. }
  28355. else {
  28356. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28357. }
  28358. };
  28359. PhysicsImpostor.prototype.getObjectCenter = function () {
  28360. if (this.object.getBoundingInfo) {
  28361. return this.object.getBoundingInfo().boundingBox.center;
  28362. }
  28363. else {
  28364. return this.object.position;
  28365. }
  28366. };
  28367. /**
  28368. * Get a specific parametes from the options parameter.
  28369. */
  28370. PhysicsImpostor.prototype.getParam = function (paramName) {
  28371. return this._options[paramName];
  28372. };
  28373. /**
  28374. * Sets a specific parameter in the options given to the physics plugin
  28375. */
  28376. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28377. this._options[paramName] = value;
  28378. this._bodyUpdateRequired = true;
  28379. };
  28380. /**
  28381. * Specifically change the body's mass option. Won't recreate the physics body object
  28382. */
  28383. PhysicsImpostor.prototype.setMass = function (mass) {
  28384. if (this.getParam("mass") !== mass) {
  28385. this.setParam("mass", mass);
  28386. }
  28387. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28388. };
  28389. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28390. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28391. };
  28392. /**
  28393. * Set the body's linear velocity.
  28394. */
  28395. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28396. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28397. };
  28398. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28399. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28400. };
  28401. /**
  28402. * Set the body's linear velocity.
  28403. */
  28404. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28405. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28406. };
  28407. /**
  28408. * Execute a function with the physics plugin native code.
  28409. * Provide a function the will have two variables - the world object and the physics body object.
  28410. */
  28411. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28412. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28413. };
  28414. /**
  28415. * Register a function that will be executed before the physics world is stepping forward.
  28416. */
  28417. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28418. this._onBeforePhysicsStepCallbacks.push(func);
  28419. };
  28420. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28421. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28422. if (index > -1) {
  28423. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28424. }
  28425. else {
  28426. BABYLON.Tools.Warn("Function to remove was not found");
  28427. }
  28428. };
  28429. /**
  28430. * Register a function that will be executed after the physics step
  28431. */
  28432. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28433. this._onAfterPhysicsStepCallbacks.push(func);
  28434. };
  28435. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28436. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28437. if (index > -1) {
  28438. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28439. }
  28440. else {
  28441. BABYLON.Tools.Warn("Function to remove was not found");
  28442. }
  28443. };
  28444. /**
  28445. * register a function that will be executed when this impostor collides against a different body.
  28446. */
  28447. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28448. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28449. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28450. };
  28451. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28452. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28453. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28454. if (index > -1) {
  28455. this._onPhysicsCollideCallbacks.splice(index, 1);
  28456. }
  28457. else {
  28458. BABYLON.Tools.Warn("Function to remove was not found");
  28459. }
  28460. };
  28461. /**
  28462. * Apply a force
  28463. */
  28464. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28465. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28466. };
  28467. /**
  28468. * Apply an impulse
  28469. */
  28470. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28471. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28472. };
  28473. /**
  28474. * A help function to create a joint.
  28475. */
  28476. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28477. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28478. this.addJoint(otherImpostor, joint);
  28479. };
  28480. /**
  28481. * Add a joint to this impostor with a different impostor.
  28482. */
  28483. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28484. this._joints.push({
  28485. otherImpostor: otherImpostor,
  28486. joint: joint
  28487. });
  28488. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28489. };
  28490. /**
  28491. * Will keep this body still, in a sleep mode.
  28492. */
  28493. PhysicsImpostor.prototype.sleep = function () {
  28494. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28495. };
  28496. /**
  28497. * Wake the body up.
  28498. */
  28499. PhysicsImpostor.prototype.wakeUp = function () {
  28500. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28501. };
  28502. PhysicsImpostor.prototype.clone = function (newObject) {
  28503. if (!newObject)
  28504. return null;
  28505. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28506. };
  28507. PhysicsImpostor.prototype.dispose = function () {
  28508. var _this = this;
  28509. //no dispose if no physics engine is available.
  28510. if (!this._physicsEngine) {
  28511. return;
  28512. }
  28513. this._joints.forEach(function (j) {
  28514. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  28515. });
  28516. //dispose the physics body
  28517. this._physicsEngine.removeImpostor(this);
  28518. if (this.parent) {
  28519. this.parent.forceUpdate();
  28520. }
  28521. else {
  28522. }
  28523. };
  28524. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  28525. this._deltaPosition.copyFrom(position);
  28526. };
  28527. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  28528. if (!this._deltaRotation) {
  28529. this._deltaRotation = new BABYLON.Quaternion();
  28530. }
  28531. this._deltaRotation.copyFrom(rotation);
  28532. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  28533. };
  28534. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  28535. //Impostor types
  28536. PhysicsImpostor.NoImpostor = 0;
  28537. PhysicsImpostor.SphereImpostor = 1;
  28538. PhysicsImpostor.BoxImpostor = 2;
  28539. PhysicsImpostor.PlaneImpostor = 3;
  28540. PhysicsImpostor.MeshImpostor = 4;
  28541. PhysicsImpostor.CylinderImpostor = 7;
  28542. PhysicsImpostor.ParticleImpostor = 8;
  28543. PhysicsImpostor.HeightmapImpostor = 9;
  28544. return PhysicsImpostor;
  28545. })();
  28546. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28547. })(BABYLON || (BABYLON = {}));
  28548. var BABYLON;
  28549. (function (BABYLON) {
  28550. var PhysicsEngine = (function () {
  28551. function PhysicsEngine(gravity, _physicsPlugin) {
  28552. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28553. this._physicsPlugin = _physicsPlugin;
  28554. //new methods and parameters
  28555. this._impostors = [];
  28556. this._joints = [];
  28557. if (!this._physicsPlugin.isSupported()) {
  28558. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28559. + "Please make sure it is included.");
  28560. }
  28561. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28562. this.setGravity(gravity);
  28563. this.setTimeStep();
  28564. }
  28565. PhysicsEngine.prototype.setGravity = function (gravity) {
  28566. this.gravity = gravity;
  28567. this._physicsPlugin.setGravity(this.gravity);
  28568. };
  28569. /**
  28570. * Set the time step of the physics engine.
  28571. * default is 1/60.
  28572. * To slow it down, enter 1/600 for example.
  28573. * To speed it up, 1/30
  28574. * @param {number} newTimeStep the new timestep to apply to this world.
  28575. */
  28576. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  28577. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  28578. this._physicsPlugin.setTimeStep(newTimeStep);
  28579. };
  28580. PhysicsEngine.prototype.dispose = function () {
  28581. this._impostors.forEach(function (impostor) {
  28582. impostor.dispose();
  28583. });
  28584. this._physicsPlugin.dispose();
  28585. };
  28586. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  28587. return this._physicsPlugin.name;
  28588. };
  28589. /**
  28590. * Adding a new impostor for the impostor tracking.
  28591. * This will be done by the impostor itself.
  28592. * @param {PhysicsImpostor} impostor the impostor to add
  28593. */
  28594. PhysicsEngine.prototype.addImpostor = function (impostor) {
  28595. impostor.uniqueId = this._impostors.push(impostor);
  28596. //if no parent, generate the body
  28597. if (!impostor.parent) {
  28598. this._physicsPlugin.generatePhysicsBody(impostor);
  28599. }
  28600. };
  28601. /**
  28602. * Remove an impostor from the engine.
  28603. * This impostor and its mesh will not longer be updated by the physics engine.
  28604. * @param {PhysicsImpostor} impostor the impostor to remove
  28605. */
  28606. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  28607. var index = this._impostors.indexOf(impostor);
  28608. if (index > -1) {
  28609. var removed = this._impostors.splice(index, 1);
  28610. //Is it needed?
  28611. if (removed.length) {
  28612. //this will also remove it from the world.
  28613. removed[0].physicsBody = null;
  28614. }
  28615. }
  28616. };
  28617. /**
  28618. * Add a joint to the physics engine
  28619. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  28620. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  28621. * @param {PhysicsJoint} the joint that will connect both impostors.
  28622. */
  28623. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  28624. var impostorJoint = {
  28625. mainImpostor: mainImpostor,
  28626. connectedImpostor: connectedImpostor,
  28627. joint: joint
  28628. };
  28629. joint.physicsPlugin = this._physicsPlugin;
  28630. this._joints.push(impostorJoint);
  28631. this._physicsPlugin.generateJoint(impostorJoint);
  28632. };
  28633. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  28634. var matchingJoints = this._joints.filter(function (impostorJoint) {
  28635. return (impostorJoint.connectedImpostor === connectedImpostor
  28636. && impostorJoint.joint === joint
  28637. && impostorJoint.mainImpostor === mainImpostor);
  28638. });
  28639. if (matchingJoints.length) {
  28640. this._physicsPlugin.removeJoint(matchingJoints[0]);
  28641. }
  28642. };
  28643. /**
  28644. * Called by the scene. no need to call it.
  28645. */
  28646. PhysicsEngine.prototype._step = function (delta) {
  28647. var _this = this;
  28648. //check if any mesh has no body / requires an update
  28649. this._impostors.forEach(function (impostor) {
  28650. if (impostor.isBodyInitRequired()) {
  28651. _this._physicsPlugin.generatePhysicsBody(impostor);
  28652. }
  28653. });
  28654. if (delta > 0.1) {
  28655. delta = 0.1;
  28656. }
  28657. else if (delta <= 0) {
  28658. delta = 1.0 / 60.0;
  28659. }
  28660. this._physicsPlugin.executeStep(delta, this._impostors);
  28661. };
  28662. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  28663. return this._physicsPlugin;
  28664. };
  28665. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  28666. for (var i = 0; i < this._impostors.length; ++i) {
  28667. if (this._impostors[i].object === object) {
  28668. return this._impostors[i];
  28669. }
  28670. }
  28671. };
  28672. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  28673. for (var i = 0; i < this._impostors.length; ++i) {
  28674. if (this._impostors[i].physicsBody === body) {
  28675. return this._impostors[i];
  28676. }
  28677. }
  28678. };
  28679. // Statics, Legacy support.
  28680. /**
  28681. * @Deprecated
  28682. *
  28683. */
  28684. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  28685. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  28686. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  28687. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  28688. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  28689. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  28690. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  28691. PhysicsEngine.CapsuleImpostor = -1;
  28692. PhysicsEngine.ConeImpostor = -1;
  28693. PhysicsEngine.ConvexHullImpostor = -1;
  28694. PhysicsEngine.Epsilon = 0.001;
  28695. return PhysicsEngine;
  28696. })();
  28697. BABYLON.PhysicsEngine = PhysicsEngine;
  28698. })(BABYLON || (BABYLON = {}));
  28699. var BABYLON;
  28700. (function (BABYLON) {
  28701. var VertexData = (function () {
  28702. function VertexData() {
  28703. }
  28704. VertexData.prototype.set = function (data, kind) {
  28705. switch (kind) {
  28706. case BABYLON.VertexBuffer.PositionKind:
  28707. this.positions = data;
  28708. break;
  28709. case BABYLON.VertexBuffer.NormalKind:
  28710. this.normals = data;
  28711. break;
  28712. case BABYLON.VertexBuffer.UVKind:
  28713. this.uvs = data;
  28714. break;
  28715. case BABYLON.VertexBuffer.UV2Kind:
  28716. this.uvs2 = data;
  28717. break;
  28718. case BABYLON.VertexBuffer.UV3Kind:
  28719. this.uvs3 = data;
  28720. break;
  28721. case BABYLON.VertexBuffer.UV4Kind:
  28722. this.uvs4 = data;
  28723. break;
  28724. case BABYLON.VertexBuffer.UV5Kind:
  28725. this.uvs5 = data;
  28726. break;
  28727. case BABYLON.VertexBuffer.UV6Kind:
  28728. this.uvs6 = data;
  28729. break;
  28730. case BABYLON.VertexBuffer.ColorKind:
  28731. this.colors = data;
  28732. break;
  28733. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28734. this.matricesIndices = data;
  28735. break;
  28736. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28737. this.matricesWeights = data;
  28738. break;
  28739. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28740. this.matricesIndicesExtra = data;
  28741. break;
  28742. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28743. this.matricesWeightsExtra = data;
  28744. break;
  28745. }
  28746. };
  28747. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28748. this._applyTo(mesh, updatable);
  28749. };
  28750. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28751. this._applyTo(geometry, updatable);
  28752. };
  28753. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28754. this._update(mesh);
  28755. };
  28756. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28757. this._update(geometry);
  28758. };
  28759. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28760. if (this.positions) {
  28761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28762. }
  28763. if (this.normals) {
  28764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28765. }
  28766. if (this.uvs) {
  28767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28768. }
  28769. if (this.uvs2) {
  28770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28771. }
  28772. if (this.uvs3) {
  28773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28774. }
  28775. if (this.uvs4) {
  28776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28777. }
  28778. if (this.uvs5) {
  28779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28780. }
  28781. if (this.uvs6) {
  28782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28783. }
  28784. if (this.colors) {
  28785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28786. }
  28787. if (this.matricesIndices) {
  28788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28789. }
  28790. if (this.matricesWeights) {
  28791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28792. }
  28793. if (this.matricesIndicesExtra) {
  28794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28795. }
  28796. if (this.matricesWeightsExtra) {
  28797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28798. }
  28799. if (this.indices) {
  28800. meshOrGeometry.setIndices(this.indices);
  28801. }
  28802. };
  28803. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28804. if (this.positions) {
  28805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28806. }
  28807. if (this.normals) {
  28808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28809. }
  28810. if (this.uvs) {
  28811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28812. }
  28813. if (this.uvs2) {
  28814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28815. }
  28816. if (this.uvs3) {
  28817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28818. }
  28819. if (this.uvs4) {
  28820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28821. }
  28822. if (this.uvs5) {
  28823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28824. }
  28825. if (this.uvs6) {
  28826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28827. }
  28828. if (this.colors) {
  28829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28830. }
  28831. if (this.matricesIndices) {
  28832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28833. }
  28834. if (this.matricesWeights) {
  28835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28836. }
  28837. if (this.matricesIndicesExtra) {
  28838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28839. }
  28840. if (this.matricesWeightsExtra) {
  28841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28842. }
  28843. if (this.indices) {
  28844. meshOrGeometry.setIndices(this.indices);
  28845. }
  28846. };
  28847. VertexData.prototype.transform = function (matrix) {
  28848. var transformed = BABYLON.Vector3.Zero();
  28849. var index;
  28850. if (this.positions) {
  28851. var position = BABYLON.Vector3.Zero();
  28852. for (index = 0; index < this.positions.length; index += 3) {
  28853. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28854. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28855. this.positions[index] = transformed.x;
  28856. this.positions[index + 1] = transformed.y;
  28857. this.positions[index + 2] = transformed.z;
  28858. }
  28859. }
  28860. if (this.normals) {
  28861. var normal = BABYLON.Vector3.Zero();
  28862. for (index = 0; index < this.normals.length; index += 3) {
  28863. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28864. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28865. this.normals[index] = transformed.x;
  28866. this.normals[index + 1] = transformed.y;
  28867. this.normals[index + 2] = transformed.z;
  28868. }
  28869. }
  28870. };
  28871. VertexData.prototype.merge = function (other) {
  28872. if (other.indices) {
  28873. if (!this.indices) {
  28874. this.indices = [];
  28875. }
  28876. var offset = this.positions ? this.positions.length / 3 : 0;
  28877. for (var index = 0; index < other.indices.length; index++) {
  28878. //TODO check type - if Int32Array!
  28879. this.indices.push(other.indices[index] + offset);
  28880. }
  28881. }
  28882. this.positions = this._mergeElement(this.positions, other.positions);
  28883. this.normals = this._mergeElement(this.normals, other.normals);
  28884. this.uvs = this._mergeElement(this.uvs, other.uvs);
  28885. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  28886. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  28887. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  28888. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  28889. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  28890. this.colors = this._mergeElement(this.colors, other.colors);
  28891. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  28892. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  28893. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  28894. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  28895. };
  28896. VertexData.prototype._mergeElement = function (source, other) {
  28897. if (!other)
  28898. return source;
  28899. if (!source)
  28900. return other;
  28901. var len = other.length + source.length;
  28902. var isSrcTypedArray = source instanceof Float32Array;
  28903. var isOthTypedArray = other instanceof Float32Array;
  28904. // use non-loop method when the source is Float32Array
  28905. if (isSrcTypedArray) {
  28906. var ret32 = new Float32Array(len);
  28907. ret32.set(source);
  28908. ret32.set(other, source.length);
  28909. return ret32;
  28910. }
  28911. else if (!isOthTypedArray) {
  28912. return source.concat(other);
  28913. }
  28914. else {
  28915. var ret = source.slice(0); // copy source to a separate array
  28916. for (var i = 0, len = other.length; i < len; i++) {
  28917. ret.push(other[i]);
  28918. }
  28919. return ret;
  28920. }
  28921. };
  28922. VertexData.prototype.serialize = function () {
  28923. var serializationObject = this.serialize();
  28924. if (this.positions) {
  28925. serializationObject.positions = this.positions;
  28926. }
  28927. if (this.normals) {
  28928. serializationObject.normals = this.normals;
  28929. }
  28930. if (this.uvs) {
  28931. serializationObject.uvs = this.uvs;
  28932. }
  28933. if (this.uvs2) {
  28934. serializationObject.uvs2 = this.uvs2;
  28935. }
  28936. if (this.uvs3) {
  28937. serializationObject.uvs3 = this.uvs3;
  28938. }
  28939. if (this.uvs4) {
  28940. serializationObject.uvs4 = this.uvs4;
  28941. }
  28942. if (this.uvs5) {
  28943. serializationObject.uvs5 = this.uvs5;
  28944. }
  28945. if (this.uvs6) {
  28946. serializationObject.uvs6 = this.uvs6;
  28947. }
  28948. if (this.colors) {
  28949. serializationObject.colors = this.colors;
  28950. }
  28951. if (this.matricesIndices) {
  28952. serializationObject.matricesIndices = this.matricesIndices;
  28953. serializationObject.matricesIndices._isExpanded = true;
  28954. }
  28955. if (this.matricesWeights) {
  28956. serializationObject.matricesWeights = this.matricesWeights;
  28957. }
  28958. if (this.matricesIndicesExtra) {
  28959. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28960. serializationObject.matricesIndicesExtra._isExpanded = true;
  28961. }
  28962. if (this.matricesWeightsExtra) {
  28963. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28964. }
  28965. serializationObject.indices = this.indices;
  28966. return serializationObject;
  28967. };
  28968. // Statics
  28969. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28970. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28971. };
  28972. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28973. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28974. };
  28975. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28976. var result = new VertexData();
  28977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28978. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28979. }
  28980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28981. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28982. }
  28983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28984. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28985. }
  28986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28987. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28988. }
  28989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28990. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28991. }
  28992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28993. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28994. }
  28995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28996. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28997. }
  28998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28999. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29000. }
  29001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29002. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29003. }
  29004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29005. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29006. }
  29007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29008. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29009. }
  29010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29011. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29012. }
  29013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29014. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29015. }
  29016. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29017. return result;
  29018. };
  29019. VertexData.CreateRibbon = function (options) {
  29020. var pathArray = options.pathArray;
  29021. var closeArray = options.closeArray || false;
  29022. var closePath = options.closePath || false;
  29023. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29024. var offset = options.offset || defaultOffset;
  29025. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29026. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29027. var positions = [];
  29028. var indices = [];
  29029. var normals = [];
  29030. var uvs = [];
  29031. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29032. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29033. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29034. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29035. var minlg; // minimal length among all paths from pathArray
  29036. var lg = []; // array of path lengths : nb of vertex per path
  29037. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29038. var p; // path iterator
  29039. var i; // point iterator
  29040. var j; // point iterator
  29041. // if single path in pathArray
  29042. if (pathArray.length < 2) {
  29043. var ar1 = [];
  29044. var ar2 = [];
  29045. for (i = 0; i < pathArray[0].length - offset; i++) {
  29046. ar1.push(pathArray[0][i]);
  29047. ar2.push(pathArray[0][i + offset]);
  29048. }
  29049. pathArray = [ar1, ar2];
  29050. }
  29051. // positions and horizontal distances (u)
  29052. var idc = 0;
  29053. var closePathCorr = (closePath) ? 1 : 0;
  29054. var path;
  29055. var l;
  29056. minlg = pathArray[0].length;
  29057. var vectlg;
  29058. var dist;
  29059. for (p = 0; p < pathArray.length; p++) {
  29060. uTotalDistance[p] = 0;
  29061. us[p] = [0];
  29062. path = pathArray[p];
  29063. l = path.length;
  29064. minlg = (minlg < l) ? minlg : l;
  29065. j = 0;
  29066. while (j < l) {
  29067. positions.push(path[j].x, path[j].y, path[j].z);
  29068. if (j > 0) {
  29069. vectlg = path[j].subtract(path[j - 1]).length();
  29070. dist = vectlg + uTotalDistance[p];
  29071. us[p].push(dist);
  29072. uTotalDistance[p] = dist;
  29073. }
  29074. j++;
  29075. }
  29076. if (closePath) {
  29077. j--;
  29078. positions.push(path[0].x, path[0].y, path[0].z);
  29079. vectlg = path[j].subtract(path[0]).length();
  29080. dist = vectlg + uTotalDistance[p];
  29081. us[p].push(dist);
  29082. uTotalDistance[p] = dist;
  29083. }
  29084. lg[p] = l + closePathCorr;
  29085. idx[p] = idc;
  29086. idc += (l + closePathCorr);
  29087. }
  29088. // vertical distances (v)
  29089. var path1;
  29090. var path2;
  29091. var vertex1;
  29092. var vertex2;
  29093. for (i = 0; i < minlg + closePathCorr; i++) {
  29094. vTotalDistance[i] = 0;
  29095. vs[i] = [0];
  29096. for (p = 0; p < pathArray.length - 1; p++) {
  29097. path1 = pathArray[p];
  29098. path2 = pathArray[p + 1];
  29099. if (i === minlg) {
  29100. vertex1 = path1[0];
  29101. vertex2 = path2[0];
  29102. }
  29103. else {
  29104. vertex1 = path1[i];
  29105. vertex2 = path2[i];
  29106. }
  29107. vectlg = vertex2.subtract(vertex1).length();
  29108. dist = vectlg + vTotalDistance[i];
  29109. vs[i].push(dist);
  29110. vTotalDistance[i] = dist;
  29111. }
  29112. if (closeArray) {
  29113. path1 = pathArray[p];
  29114. path2 = pathArray[0];
  29115. if (i === minlg) {
  29116. vertex2 = path2[0];
  29117. }
  29118. vectlg = vertex2.subtract(vertex1).length();
  29119. dist = vectlg + vTotalDistance[i];
  29120. vTotalDistance[i] = dist;
  29121. }
  29122. }
  29123. // uvs
  29124. var u;
  29125. var v;
  29126. for (p = 0; p < pathArray.length; p++) {
  29127. for (i = 0; i < minlg + closePathCorr; i++) {
  29128. u = us[p][i] / uTotalDistance[p];
  29129. v = vs[i][p] / vTotalDistance[i];
  29130. uvs.push(u, v);
  29131. }
  29132. }
  29133. // indices
  29134. p = 0; // path index
  29135. var pi = 0; // positions array index
  29136. var l1 = lg[p] - 1; // path1 length
  29137. var l2 = lg[p + 1] - 1; // path2 length
  29138. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29139. var shft = idx[1] - idx[0]; // shift
  29140. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29141. while (pi <= min && p < path1nb) {
  29142. // 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
  29143. indices.push(pi, pi + shft, pi + 1);
  29144. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29145. pi += 1;
  29146. if (pi === min) {
  29147. p++;
  29148. if (p === lg.length - 1) {
  29149. shft = idx[0] - idx[p];
  29150. l1 = lg[p] - 1;
  29151. l2 = lg[0] - 1;
  29152. }
  29153. else {
  29154. shft = idx[p + 1] - idx[p];
  29155. l1 = lg[p] - 1;
  29156. l2 = lg[p + 1] - 1;
  29157. }
  29158. pi = idx[p];
  29159. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29160. }
  29161. }
  29162. // normals
  29163. VertexData.ComputeNormals(positions, indices, normals);
  29164. if (closePath) {
  29165. var indexFirst = 0;
  29166. var indexLast = 0;
  29167. for (p = 0; p < pathArray.length; p++) {
  29168. indexFirst = idx[p] * 3;
  29169. if (p + 1 < pathArray.length) {
  29170. indexLast = (idx[p + 1] - 1) * 3;
  29171. }
  29172. else {
  29173. indexLast = normals.length - 3;
  29174. }
  29175. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29176. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29177. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29178. normals[indexLast] = normals[indexFirst];
  29179. normals[indexLast + 1] = normals[indexFirst + 1];
  29180. normals[indexLast + 2] = normals[indexFirst + 2];
  29181. }
  29182. }
  29183. // sides
  29184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29185. // Result
  29186. var vertexData = new VertexData();
  29187. vertexData.indices = indices;
  29188. vertexData.positions = positions;
  29189. vertexData.normals = normals;
  29190. vertexData.uvs = uvs;
  29191. if (closePath) {
  29192. vertexData._idx = idx;
  29193. }
  29194. return vertexData;
  29195. };
  29196. VertexData.CreateBox = function (options) {
  29197. var normalsSource = [
  29198. new BABYLON.Vector3(0, 0, 1),
  29199. new BABYLON.Vector3(0, 0, -1),
  29200. new BABYLON.Vector3(1, 0, 0),
  29201. new BABYLON.Vector3(-1, 0, 0),
  29202. new BABYLON.Vector3(0, 1, 0),
  29203. new BABYLON.Vector3(0, -1, 0)
  29204. ];
  29205. var indices = [];
  29206. var positions = [];
  29207. var normals = [];
  29208. var uvs = [];
  29209. var width = options.width || options.size || 1;
  29210. var height = options.height || options.size || 1;
  29211. var depth = options.depth || options.size || 1;
  29212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29213. var faceUV = options.faceUV || new Array(6);
  29214. var faceColors = options.faceColors;
  29215. var colors = [];
  29216. // default face colors and UV if undefined
  29217. for (var f = 0; f < 6; f++) {
  29218. if (faceUV[f] === undefined) {
  29219. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29220. }
  29221. if (faceColors && faceColors[f] === undefined) {
  29222. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29223. }
  29224. }
  29225. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29226. // Create each face in turn.
  29227. for (var index = 0; index < normalsSource.length; index++) {
  29228. var normal = normalsSource[index];
  29229. // Get two vectors perpendicular to the face normal and to each other.
  29230. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29231. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29232. // Six indices (two triangles) per face.
  29233. var verticesLength = positions.length / 3;
  29234. indices.push(verticesLength);
  29235. indices.push(verticesLength + 1);
  29236. indices.push(verticesLength + 2);
  29237. indices.push(verticesLength);
  29238. indices.push(verticesLength + 2);
  29239. indices.push(verticesLength + 3);
  29240. // Four vertices per face.
  29241. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29242. positions.push(vertex.x, vertex.y, vertex.z);
  29243. normals.push(normal.x, normal.y, normal.z);
  29244. uvs.push(faceUV[index].z, faceUV[index].w);
  29245. if (faceColors) {
  29246. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29247. }
  29248. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29249. positions.push(vertex.x, vertex.y, vertex.z);
  29250. normals.push(normal.x, normal.y, normal.z);
  29251. uvs.push(faceUV[index].x, faceUV[index].w);
  29252. if (faceColors) {
  29253. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29254. }
  29255. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29256. positions.push(vertex.x, vertex.y, vertex.z);
  29257. normals.push(normal.x, normal.y, normal.z);
  29258. uvs.push(faceUV[index].x, faceUV[index].y);
  29259. if (faceColors) {
  29260. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29261. }
  29262. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29263. positions.push(vertex.x, vertex.y, vertex.z);
  29264. normals.push(normal.x, normal.y, normal.z);
  29265. uvs.push(faceUV[index].z, faceUV[index].y);
  29266. if (faceColors) {
  29267. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29268. }
  29269. }
  29270. // sides
  29271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29272. // Result
  29273. var vertexData = new VertexData();
  29274. vertexData.indices = indices;
  29275. vertexData.positions = positions;
  29276. vertexData.normals = normals;
  29277. vertexData.uvs = uvs;
  29278. if (faceColors) {
  29279. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29280. vertexData.colors = totalColors;
  29281. }
  29282. return vertexData;
  29283. };
  29284. VertexData.CreateSphere = function (options) {
  29285. var segments = options.segments || 32;
  29286. var diameterX = options.diameterX || options.diameter || 1;
  29287. var diameterY = options.diameterY || options.diameter || 1;
  29288. var diameterZ = options.diameterZ || options.diameter || 1;
  29289. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29290. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29291. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29292. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29293. var totalZRotationSteps = 2 + segments;
  29294. var totalYRotationSteps = 2 * totalZRotationSteps;
  29295. var indices = [];
  29296. var positions = [];
  29297. var normals = [];
  29298. var uvs = [];
  29299. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29300. var normalizedZ = zRotationStep / totalZRotationSteps;
  29301. var angleZ = normalizedZ * Math.PI * slice;
  29302. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29303. var normalizedY = yRotationStep / totalYRotationSteps;
  29304. var angleY = normalizedY * Math.PI * 2 * arc;
  29305. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29306. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29307. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29308. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29309. var vertex = complete.multiply(radius);
  29310. var normal = complete.divide(radius).normalize();
  29311. positions.push(vertex.x, vertex.y, vertex.z);
  29312. normals.push(normal.x, normal.y, normal.z);
  29313. uvs.push(normalizedY, normalizedZ);
  29314. }
  29315. if (zRotationStep > 0) {
  29316. var verticesCount = positions.length / 3;
  29317. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29318. indices.push((firstIndex));
  29319. indices.push((firstIndex + 1));
  29320. indices.push(firstIndex + totalYRotationSteps + 1);
  29321. indices.push((firstIndex + totalYRotationSteps + 1));
  29322. indices.push((firstIndex + 1));
  29323. indices.push((firstIndex + totalYRotationSteps + 2));
  29324. }
  29325. }
  29326. }
  29327. // Sides
  29328. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29329. // Result
  29330. var vertexData = new VertexData();
  29331. vertexData.indices = indices;
  29332. vertexData.positions = positions;
  29333. vertexData.normals = normals;
  29334. vertexData.uvs = uvs;
  29335. return vertexData;
  29336. };
  29337. // Cylinder and cone
  29338. VertexData.CreateCylinder = function (options) {
  29339. var height = options.height || 2;
  29340. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29341. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29342. var tessellation = options.tessellation || 24;
  29343. var subdivisions = options.subdivisions || 1;
  29344. var hasRings = options.hasRings;
  29345. var enclose = options.enclose;
  29346. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29348. var faceUV = options.faceUV || new Array(3);
  29349. var faceColors = options.faceColors;
  29350. // default face colors and UV if undefined
  29351. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29352. var ringNb = (hasRings) ? subdivisions : 1;
  29353. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29354. var f;
  29355. for (f = 0; f < surfaceNb; f++) {
  29356. if (faceColors && faceColors[f] === undefined) {
  29357. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29358. }
  29359. }
  29360. for (f = 0; f < surfaceNb; f++) {
  29361. if (faceUV && faceUV[f] === undefined) {
  29362. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29363. }
  29364. }
  29365. var indices = [];
  29366. var positions = [];
  29367. var normals = [];
  29368. var uvs = [];
  29369. var colors = [];
  29370. var angle_step = Math.PI * 2 * arc / tessellation;
  29371. var angle;
  29372. var h;
  29373. var radius;
  29374. var tan = (diameterBottom - diameterTop) / 2 / height;
  29375. var ringVertex = BABYLON.Vector3.Zero();
  29376. var ringNormal = BABYLON.Vector3.Zero();
  29377. var ringFirstVertex = BABYLON.Vector3.Zero();
  29378. var ringFirstNormal = BABYLON.Vector3.Zero();
  29379. var quadNormal = BABYLON.Vector3.Zero();
  29380. var Y = BABYLON.Axis.Y;
  29381. // positions, normals, uvs
  29382. var i;
  29383. var j;
  29384. var r;
  29385. var ringIdx = 1;
  29386. var s = 1; // surface index
  29387. var cs = 0;
  29388. var v = 0;
  29389. for (i = 0; i <= subdivisions; i++) {
  29390. h = i / subdivisions;
  29391. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29392. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29393. for (r = 0; r < ringIdx; r++) {
  29394. if (hasRings) {
  29395. s += r;
  29396. }
  29397. if (enclose) {
  29398. s += 2 * r;
  29399. }
  29400. for (j = 0; j <= tessellation; j++) {
  29401. angle = j * angle_step;
  29402. // position
  29403. ringVertex.x = Math.cos(-angle) * radius;
  29404. ringVertex.y = -height / 2 + h * height;
  29405. ringVertex.z = Math.sin(-angle) * radius;
  29406. // normal
  29407. if (diameterTop === 0 && i === subdivisions) {
  29408. // if no top cap, reuse former normals
  29409. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29410. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29411. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29412. }
  29413. else {
  29414. ringNormal.x = ringVertex.x;
  29415. ringNormal.z = ringVertex.z;
  29416. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29417. ringNormal.normalize();
  29418. }
  29419. // keep first ring vertex values for enclose
  29420. if (j === 0) {
  29421. ringFirstVertex.copyFrom(ringVertex);
  29422. ringFirstNormal.copyFrom(ringNormal);
  29423. }
  29424. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29425. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29426. if (hasRings) {
  29427. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29428. }
  29429. else {
  29430. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29431. }
  29432. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29433. if (faceColors) {
  29434. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29435. }
  29436. }
  29437. // if enclose, add four vertices and their dedicated normals
  29438. if (arc !== 1 && enclose) {
  29439. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29440. positions.push(0, ringVertex.y, 0);
  29441. positions.push(0, ringVertex.y, 0);
  29442. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29443. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29444. quadNormal.normalize();
  29445. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29446. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29447. quadNormal.normalize();
  29448. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29449. if (hasRings) {
  29450. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29451. }
  29452. else {
  29453. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29454. }
  29455. uvs.push(faceUV[s + 1].x, v);
  29456. uvs.push(faceUV[s + 1].z, v);
  29457. if (hasRings) {
  29458. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29459. }
  29460. else {
  29461. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29462. }
  29463. uvs.push(faceUV[s + 2].x, v);
  29464. uvs.push(faceUV[s + 2].z, v);
  29465. if (faceColors) {
  29466. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29467. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29468. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29469. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29470. }
  29471. }
  29472. if (cs !== s) {
  29473. cs = s;
  29474. }
  29475. }
  29476. }
  29477. // indices
  29478. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29479. var s;
  29480. i = 0;
  29481. for (s = 0; s < subdivisions; s++) {
  29482. for (j = 0; j < tessellation; j++) {
  29483. var i0 = i * (e + 1) + j;
  29484. var i1 = (i + 1) * (e + 1) + j;
  29485. var i2 = i * (e + 1) + (j + 1);
  29486. var i3 = (i + 1) * (e + 1) + (j + 1);
  29487. indices.push(i0, i1, i2);
  29488. indices.push(i3, i2, i1);
  29489. }
  29490. if (arc !== 1 && enclose) {
  29491. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29492. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29493. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29494. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29495. }
  29496. i = (hasRings) ? (i + 2) : (i + 1);
  29497. }
  29498. // Caps
  29499. var createCylinderCap = function (isTop) {
  29500. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29501. if (radius === 0) {
  29502. return;
  29503. }
  29504. // Cap positions, normals & uvs
  29505. var angle;
  29506. var circleVector;
  29507. var i;
  29508. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29509. var c;
  29510. if (faceColors) {
  29511. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29512. }
  29513. // cap center
  29514. var vbase = positions.length / 3;
  29515. var offset = isTop ? height / 2 : -height / 2;
  29516. var center = new BABYLON.Vector3(0, offset, 0);
  29517. positions.push(center.x, center.y, center.z);
  29518. normals.push(0, isTop ? 1 : -1, 0);
  29519. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29520. if (faceColors) {
  29521. colors.push(c.r, c.g, c.b, c.a);
  29522. }
  29523. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29524. for (i = 0; i <= tessellation; i++) {
  29525. angle = Math.PI * 2 * i * arc / tessellation;
  29526. var cos = Math.cos(-angle);
  29527. var sin = Math.sin(-angle);
  29528. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29529. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29530. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29531. normals.push(0, isTop ? 1 : -1, 0);
  29532. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29533. if (faceColors) {
  29534. colors.push(c.r, c.g, c.b, c.a);
  29535. }
  29536. }
  29537. // Cap indices
  29538. for (i = 0; i < tessellation; i++) {
  29539. if (!isTop) {
  29540. indices.push(vbase);
  29541. indices.push(vbase + (i + 1));
  29542. indices.push(vbase + (i + 2));
  29543. }
  29544. else {
  29545. indices.push(vbase);
  29546. indices.push(vbase + (i + 2));
  29547. indices.push(vbase + (i + 1));
  29548. }
  29549. }
  29550. };
  29551. // add caps to geometry
  29552. createCylinderCap(false);
  29553. createCylinderCap(true);
  29554. // Sides
  29555. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29556. var vertexData = new VertexData();
  29557. vertexData.indices = indices;
  29558. vertexData.positions = positions;
  29559. vertexData.normals = normals;
  29560. vertexData.uvs = uvs;
  29561. if (faceColors) {
  29562. vertexData.colors = colors;
  29563. }
  29564. return vertexData;
  29565. };
  29566. VertexData.CreateTorus = function (options) {
  29567. var indices = [];
  29568. var positions = [];
  29569. var normals = [];
  29570. var uvs = [];
  29571. var diameter = options.diameter || 1;
  29572. var thickness = options.thickness || 0.5;
  29573. var tessellation = options.tessellation || 16;
  29574. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29575. var stride = tessellation + 1;
  29576. for (var i = 0; i <= tessellation; i++) {
  29577. var u = i / tessellation;
  29578. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29579. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29580. for (var j = 0; j <= tessellation; j++) {
  29581. var v = 1 - j / tessellation;
  29582. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29583. var dx = Math.cos(innerAngle);
  29584. var dy = Math.sin(innerAngle);
  29585. // Create a vertex.
  29586. var normal = new BABYLON.Vector3(dx, dy, 0);
  29587. var position = normal.scale(thickness / 2);
  29588. var textureCoordinate = new BABYLON.Vector2(u, v);
  29589. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29590. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29591. positions.push(position.x, position.y, position.z);
  29592. normals.push(normal.x, normal.y, normal.z);
  29593. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29594. // And create indices for two triangles.
  29595. var nextI = (i + 1) % stride;
  29596. var nextJ = (j + 1) % stride;
  29597. indices.push(i * stride + j);
  29598. indices.push(i * stride + nextJ);
  29599. indices.push(nextI * stride + j);
  29600. indices.push(i * stride + nextJ);
  29601. indices.push(nextI * stride + nextJ);
  29602. indices.push(nextI * stride + j);
  29603. }
  29604. }
  29605. // Sides
  29606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29607. // Result
  29608. var vertexData = new VertexData();
  29609. vertexData.indices = indices;
  29610. vertexData.positions = positions;
  29611. vertexData.normals = normals;
  29612. vertexData.uvs = uvs;
  29613. return vertexData;
  29614. };
  29615. VertexData.CreateLineSystem = function (options) {
  29616. var indices = [];
  29617. var positions = [];
  29618. var lines = options.lines;
  29619. var idx = 0;
  29620. for (var l = 0; l < lines.length; l++) {
  29621. var points = lines[l];
  29622. for (var index = 0; index < points.length; index++) {
  29623. positions.push(points[index].x, points[index].y, points[index].z);
  29624. if (index > 0) {
  29625. indices.push(idx - 1);
  29626. indices.push(idx);
  29627. }
  29628. idx++;
  29629. }
  29630. }
  29631. var vertexData = new VertexData();
  29632. vertexData.indices = indices;
  29633. vertexData.positions = positions;
  29634. return vertexData;
  29635. };
  29636. VertexData.CreateDashedLines = function (options) {
  29637. var dashSize = options.dashSize || 3;
  29638. var gapSize = options.gapSize || 1;
  29639. var dashNb = options.dashNb || 200;
  29640. var points = options.points;
  29641. var positions = new Array();
  29642. var indices = new Array();
  29643. var curvect = BABYLON.Vector3.Zero();
  29644. var lg = 0;
  29645. var nb = 0;
  29646. var shft = 0;
  29647. var dashshft = 0;
  29648. var curshft = 0;
  29649. var idx = 0;
  29650. var i = 0;
  29651. for (i = 0; i < points.length - 1; i++) {
  29652. points[i + 1].subtractToRef(points[i], curvect);
  29653. lg += curvect.length();
  29654. }
  29655. shft = lg / dashNb;
  29656. dashshft = dashSize * shft / (dashSize + gapSize);
  29657. for (i = 0; i < points.length - 1; i++) {
  29658. points[i + 1].subtractToRef(points[i], curvect);
  29659. nb = Math.floor(curvect.length() / shft);
  29660. curvect.normalize();
  29661. for (var j = 0; j < nb; j++) {
  29662. curshft = shft * j;
  29663. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29664. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29665. indices.push(idx, idx + 1);
  29666. idx += 2;
  29667. }
  29668. }
  29669. // Result
  29670. var vertexData = new VertexData();
  29671. vertexData.positions = positions;
  29672. vertexData.indices = indices;
  29673. return vertexData;
  29674. };
  29675. VertexData.CreateGround = function (options) {
  29676. var indices = [];
  29677. var positions = [];
  29678. var normals = [];
  29679. var uvs = [];
  29680. var row, col;
  29681. var width = options.width || 1;
  29682. var height = options.height || 1;
  29683. var subdivisions = options.subdivisions || 1;
  29684. for (row = 0; row <= subdivisions; row++) {
  29685. for (col = 0; col <= subdivisions; col++) {
  29686. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  29687. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29688. positions.push(position.x, position.y, position.z);
  29689. normals.push(normal.x, normal.y, normal.z);
  29690. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  29691. }
  29692. }
  29693. for (row = 0; row < subdivisions; row++) {
  29694. for (col = 0; col < subdivisions; col++) {
  29695. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29696. indices.push(col + 1 + row * (subdivisions + 1));
  29697. indices.push(col + row * (subdivisions + 1));
  29698. indices.push(col + (row + 1) * (subdivisions + 1));
  29699. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29700. indices.push(col + row * (subdivisions + 1));
  29701. }
  29702. }
  29703. // Result
  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.CreateTiledGround = function (options) {
  29712. var xmin = options.xmin;
  29713. var zmin = options.zmin;
  29714. var xmax = options.xmax;
  29715. var zmax = options.zmax;
  29716. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29717. var precision = options.precision || { w: 1, h: 1 };
  29718. var indices = [];
  29719. var positions = [];
  29720. var normals = [];
  29721. var uvs = [];
  29722. var row, col, tileRow, tileCol;
  29723. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  29724. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29725. precision.w = (precision.w < 1) ? 1 : precision.w;
  29726. precision.h = (precision.h < 1) ? 1 : precision.h;
  29727. var tileSize = {
  29728. 'w': (xmax - xmin) / subdivisions.w,
  29729. 'h': (zmax - zmin) / subdivisions.h
  29730. };
  29731. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29732. // Indices
  29733. var base = positions.length / 3;
  29734. var rowLength = precision.w + 1;
  29735. for (row = 0; row < precision.h; row++) {
  29736. for (col = 0; col < precision.w; col++) {
  29737. var square = [
  29738. base + col + row * rowLength,
  29739. base + (col + 1) + row * rowLength,
  29740. base + (col + 1) + (row + 1) * rowLength,
  29741. base + col + (row + 1) * rowLength
  29742. ];
  29743. indices.push(square[1]);
  29744. indices.push(square[2]);
  29745. indices.push(square[3]);
  29746. indices.push(square[0]);
  29747. indices.push(square[1]);
  29748. indices.push(square[3]);
  29749. }
  29750. }
  29751. // Position, normals and uvs
  29752. var position = BABYLON.Vector3.Zero();
  29753. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29754. for (row = 0; row <= precision.h; row++) {
  29755. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29756. for (col = 0; col <= precision.w; col++) {
  29757. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29758. position.y = 0;
  29759. positions.push(position.x, position.y, position.z);
  29760. normals.push(normal.x, normal.y, normal.z);
  29761. uvs.push(col / precision.w, row / precision.h);
  29762. }
  29763. }
  29764. }
  29765. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29766. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29767. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29768. }
  29769. }
  29770. // Result
  29771. var vertexData = new VertexData();
  29772. vertexData.indices = indices;
  29773. vertexData.positions = positions;
  29774. vertexData.normals = normals;
  29775. vertexData.uvs = uvs;
  29776. return vertexData;
  29777. };
  29778. VertexData.CreateGroundFromHeightMap = function (options) {
  29779. var indices = [];
  29780. var positions = [];
  29781. var normals = [];
  29782. var uvs = [];
  29783. var row, col;
  29784. // Vertices
  29785. for (row = 0; row <= options.subdivisions; row++) {
  29786. for (col = 0; col <= options.subdivisions; col++) {
  29787. 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));
  29788. // Compute height
  29789. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29790. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29791. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29792. var r = options.buffer[pos] / 255.0;
  29793. var g = options.buffer[pos + 1] / 255.0;
  29794. var b = options.buffer[pos + 2] / 255.0;
  29795. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29796. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29797. // Add vertex
  29798. positions.push(position.x, position.y, position.z);
  29799. normals.push(0, 0, 0);
  29800. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29801. }
  29802. }
  29803. // Indices
  29804. for (row = 0; row < options.subdivisions; row++) {
  29805. for (col = 0; col < options.subdivisions; col++) {
  29806. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29807. indices.push(col + 1 + row * (options.subdivisions + 1));
  29808. indices.push(col + row * (options.subdivisions + 1));
  29809. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29810. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29811. indices.push(col + row * (options.subdivisions + 1));
  29812. }
  29813. }
  29814. // Normals
  29815. VertexData.ComputeNormals(positions, indices, normals);
  29816. // Result
  29817. var vertexData = new VertexData();
  29818. vertexData.indices = indices;
  29819. vertexData.positions = positions;
  29820. vertexData.normals = normals;
  29821. vertexData.uvs = uvs;
  29822. return vertexData;
  29823. };
  29824. VertexData.CreatePlane = function (options) {
  29825. var indices = [];
  29826. var positions = [];
  29827. var normals = [];
  29828. var uvs = [];
  29829. var width = options.width || options.size || 1;
  29830. var height = options.height || options.size || 1;
  29831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29832. // Vertices
  29833. var halfWidth = width / 2.0;
  29834. var halfHeight = height / 2.0;
  29835. positions.push(-halfWidth, -halfHeight, 0);
  29836. normals.push(0, 0, -1.0);
  29837. uvs.push(0.0, 0.0);
  29838. positions.push(halfWidth, -halfHeight, 0);
  29839. normals.push(0, 0, -1.0);
  29840. uvs.push(1.0, 0.0);
  29841. positions.push(halfWidth, halfHeight, 0);
  29842. normals.push(0, 0, -1.0);
  29843. uvs.push(1.0, 1.0);
  29844. positions.push(-halfWidth, halfHeight, 0);
  29845. normals.push(0, 0, -1.0);
  29846. uvs.push(0.0, 1.0);
  29847. // Indices
  29848. indices.push(0);
  29849. indices.push(1);
  29850. indices.push(2);
  29851. indices.push(0);
  29852. indices.push(2);
  29853. indices.push(3);
  29854. // Sides
  29855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29856. // Result
  29857. var vertexData = new VertexData();
  29858. vertexData.indices = indices;
  29859. vertexData.positions = positions;
  29860. vertexData.normals = normals;
  29861. vertexData.uvs = uvs;
  29862. return vertexData;
  29863. };
  29864. VertexData.CreateDisc = function (options) {
  29865. var positions = [];
  29866. var indices = [];
  29867. var normals = [];
  29868. var uvs = [];
  29869. var radius = options.radius || 0.5;
  29870. var tessellation = options.tessellation || 64;
  29871. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29872. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29873. // positions and uvs
  29874. positions.push(0, 0, 0); // disc center first
  29875. uvs.push(0.5, 0.5);
  29876. var theta = Math.PI * 2 * arc;
  29877. var step = theta / tessellation;
  29878. for (var a = 0; a < theta; a += step) {
  29879. var x = Math.cos(a);
  29880. var y = Math.sin(a);
  29881. var u = (x + 1) / 2;
  29882. var v = (1 - y) / 2;
  29883. positions.push(radius * x, radius * y, 0);
  29884. uvs.push(u, v);
  29885. }
  29886. if (arc === 1) {
  29887. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29888. uvs.push(uvs[2], uvs[3]);
  29889. }
  29890. //indices
  29891. var vertexNb = positions.length / 3;
  29892. for (var i = 1; i < vertexNb - 1; i++) {
  29893. indices.push(i + 1, 0, i);
  29894. }
  29895. // result
  29896. VertexData.ComputeNormals(positions, indices, normals);
  29897. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29898. var vertexData = new VertexData();
  29899. vertexData.indices = indices;
  29900. vertexData.positions = positions;
  29901. vertexData.normals = normals;
  29902. vertexData.uvs = uvs;
  29903. return vertexData;
  29904. };
  29905. VertexData.CreateIcoSphere = function (options) {
  29906. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29907. var radius = options.radius || 1;
  29908. var flat = (options.flat === undefined) ? true : options.flat;
  29909. var subdivisions = options.subdivisions || 4;
  29910. var radiusX = options.radiusX || radius;
  29911. var radiusY = options.radiusY || radius;
  29912. var radiusZ = options.radiusZ || radius;
  29913. var t = (1 + Math.sqrt(5)) / 2;
  29914. // 12 vertex x,y,z
  29915. var ico_vertices = [
  29916. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29917. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29918. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29919. ];
  29920. // index of 3 vertex makes a face of icopshere
  29921. var ico_indices = [
  29922. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29923. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29924. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29925. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29926. ];
  29927. // vertex for uv have aliased position, not for UV
  29928. var vertices_unalias_id = [
  29929. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29930. // vertex alias
  29931. 0,
  29932. 2,
  29933. 3,
  29934. 3,
  29935. 3,
  29936. 4,
  29937. 7,
  29938. 8,
  29939. 9,
  29940. 9,
  29941. 10,
  29942. 11 // 23: B + 12
  29943. ];
  29944. // uv as integer step (not pixels !)
  29945. var ico_vertexuv = [
  29946. 5, 1, 3, 1, 6, 4, 0, 0,
  29947. 5, 3, 4, 2, 2, 2, 4, 0,
  29948. 2, 0, 1, 1, 6, 0, 6, 2,
  29949. // vertex alias (for same vertex on different faces)
  29950. 0, 4,
  29951. 3, 3,
  29952. 4, 4,
  29953. 3, 1,
  29954. 4, 2,
  29955. 4, 4,
  29956. 0, 2,
  29957. 1, 1,
  29958. 2, 2,
  29959. 3, 3,
  29960. 1, 3,
  29961. 2, 4 // 23: B + 12
  29962. ];
  29963. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29964. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29965. // First island of uv mapping
  29966. // v = 4h 3+ 2
  29967. // v = 3h 9+ 4
  29968. // v = 2h 9+ 5 B
  29969. // v = 1h 9 1 0
  29970. // v = 0h 3 8 7 A
  29971. // u = 0 1 2 3 4 5 6 *a
  29972. // Second island of uv mapping
  29973. // v = 4h 0+ B+ 4+
  29974. // v = 3h A+ 2+
  29975. // v = 2h 7+ 6 3+
  29976. // v = 1h 8+ 3+
  29977. // v = 0h
  29978. // u = 0 1 2 3 4 5 6 *a
  29979. // Face layout on texture UV mapping
  29980. // ============
  29981. // \ 4 /\ 16 / ======
  29982. // \ / \ / /\ 11 /
  29983. // \/ 7 \/ / \ /
  29984. // ======= / 10 \/
  29985. // /\ 17 /\ =======
  29986. // / \ / \ \ 15 /\
  29987. // / 8 \/ 12 \ \ / \
  29988. // ============ \/ 6 \
  29989. // \ 18 /\ ============
  29990. // \ / \ \ 5 /\ 0 /
  29991. // \/ 13 \ \ / \ /
  29992. // ======= \/ 1 \/
  29993. // =============
  29994. // /\ 19 /\ 2 /\
  29995. // / \ / \ / \
  29996. // / 14 \/ 9 \/ 3 \
  29997. // ===================
  29998. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29999. var ustep = 138 / 1024;
  30000. var vstep = 239 / 1024;
  30001. var uoffset = 60 / 1024;
  30002. var voffset = 26 / 1024;
  30003. // Second island should have margin, not to touch the first island
  30004. // avoid any borderline artefact in pixel rounding
  30005. var island_u_offset = -40 / 1024;
  30006. var island_v_offset = +20 / 1024;
  30007. // face is either island 0 or 1 :
  30008. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30009. var island = [
  30010. 0, 0, 0, 0, 1,
  30011. 0, 0, 1, 1, 0,
  30012. 0, 0, 1, 1, 0,
  30013. 0, 1, 1, 1, 0 // 15 - 19
  30014. ];
  30015. var indices = [];
  30016. var positions = [];
  30017. var normals = [];
  30018. var uvs = [];
  30019. var current_indice = 0;
  30020. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30021. var face_vertex_pos = new Array(3);
  30022. var face_vertex_uv = new Array(3);
  30023. var v012;
  30024. for (v012 = 0; v012 < 3; v012++) {
  30025. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30026. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30027. }
  30028. // create all with normals
  30029. for (var face = 0; face < 20; face++) {
  30030. // 3 vertex per face
  30031. for (v012 = 0; v012 < 3; v012++) {
  30032. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30033. var v_id = ico_indices[3 * face + v012];
  30034. // vertex have 3D position (x,y,z)
  30035. 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]);
  30036. // Normalize to get normal, then scale to radius
  30037. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30038. // uv Coordinates from vertex ID
  30039. 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);
  30040. }
  30041. // Subdivide the face (interpolate pos, norm, uv)
  30042. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30043. // - norm is linear interpolation of vertex corner normal
  30044. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30045. // - uv is linear interpolation
  30046. //
  30047. // Topology is as below for sub-divide by 2
  30048. // vertex shown as v0,v1,v2
  30049. // interp index is i1 to progress in range [v0,v1[
  30050. // interp index is i2 to progress in range [v0,v2[
  30051. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30052. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30053. //
  30054. //
  30055. // i2 v2
  30056. // ^ ^
  30057. // / / \
  30058. // / / \
  30059. // / / \
  30060. // / / (0,1) \
  30061. // / #---------\
  30062. // / / \ (0,0)'/ \
  30063. // / / \ / \
  30064. // / / \ / \
  30065. // / / (0,0) \ / (1,0) \
  30066. // / #---------#---------\
  30067. // v0 v1
  30068. //
  30069. // --------------------> i1
  30070. //
  30071. // interp of (i1,i2):
  30072. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30073. // along i1 : lerp(x0,x1, i1/(S-i2))
  30074. //
  30075. // centroid of triangle is needed to get help normal computation
  30076. // (c1,c2) are used for centroid location
  30077. var interp_vertex = function (i1, i2, c1, c2) {
  30078. // vertex is interpolated from
  30079. // - face_vertex_pos[0..2]
  30080. // - face_vertex_uv[0..2]
  30081. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30082. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30083. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30084. pos_interp.normalize();
  30085. var vertex_normal;
  30086. if (flat) {
  30087. // in flat mode, recalculate normal as face centroid normal
  30088. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30089. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30090. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30091. }
  30092. else {
  30093. // in smooth mode, recalculate normal from each single vertex position
  30094. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30095. }
  30096. // Vertex normal need correction due to X,Y,Z radius scaling
  30097. vertex_normal.x /= radiusX;
  30098. vertex_normal.y /= radiusY;
  30099. vertex_normal.z /= radiusZ;
  30100. vertex_normal.normalize();
  30101. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30102. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30103. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30104. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30105. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30106. uvs.push(uv_interp.x, uv_interp.y);
  30107. // push each vertex has member of a face
  30108. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30109. indices.push(current_indice);
  30110. current_indice++;
  30111. };
  30112. for (var i2 = 0; i2 < subdivisions; i2++) {
  30113. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30114. // face : (i1,i2) for /\ :
  30115. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30116. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30117. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30118. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30119. if (i1 + i2 + 1 < subdivisions) {
  30120. // face : (i1,i2)' for \/ :
  30121. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30122. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30123. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30124. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30125. }
  30126. }
  30127. }
  30128. }
  30129. // Sides
  30130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30131. // Result
  30132. var vertexData = new VertexData();
  30133. vertexData.indices = indices;
  30134. vertexData.positions = positions;
  30135. vertexData.normals = normals;
  30136. vertexData.uvs = uvs;
  30137. return vertexData;
  30138. };
  30139. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30140. VertexData.CreatePolyhedron = function (options) {
  30141. // provided polyhedron types :
  30142. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30143. // 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)
  30144. var polyhedra = [];
  30145. 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]] };
  30146. 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]] };
  30147. polyhedra[2] = {
  30148. 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]],
  30149. 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]]
  30150. };
  30151. polyhedra[3] = {
  30152. 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]],
  30153. 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]]
  30154. };
  30155. polyhedra[4] = {
  30156. 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]],
  30157. 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]]
  30158. };
  30159. 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]] };
  30160. 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]] };
  30161. 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]] };
  30162. 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]] };
  30163. 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]] };
  30164. 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]] };
  30165. 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]] };
  30166. 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]] };
  30167. 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]] };
  30168. polyhedra[14] = {
  30169. 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]],
  30170. 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]]
  30171. };
  30172. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30173. var size = options.size;
  30174. var sizeX = options.sizeX || size || 1;
  30175. var sizeY = options.sizeY || size || 1;
  30176. var sizeZ = options.sizeZ || size || 1;
  30177. var data = options.custom || polyhedra[type];
  30178. var nbfaces = data.face.length;
  30179. var faceUV = options.faceUV || new Array(nbfaces);
  30180. var faceColors = options.faceColors;
  30181. var flat = (options.flat === undefined) ? true : options.flat;
  30182. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30183. var positions = [];
  30184. var indices = [];
  30185. var normals = [];
  30186. var uvs = [];
  30187. var colors = [];
  30188. var index = 0;
  30189. var faceIdx = 0; // face cursor in the array "indexes"
  30190. var indexes = [];
  30191. var i = 0;
  30192. var f = 0;
  30193. var u, v, ang, x, y, tmp;
  30194. // default face colors and UV if undefined
  30195. if (flat) {
  30196. for (f = 0; f < nbfaces; f++) {
  30197. if (faceColors && faceColors[f] === undefined) {
  30198. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30199. }
  30200. if (faceUV && faceUV[f] === undefined) {
  30201. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30202. }
  30203. }
  30204. }
  30205. if (!flat) {
  30206. for (i = 0; i < data.vertex.length; i++) {
  30207. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30208. uvs.push(0, 0);
  30209. }
  30210. for (f = 0; f < nbfaces; f++) {
  30211. for (i = 0; i < data.face[f].length - 2; i++) {
  30212. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30213. }
  30214. }
  30215. }
  30216. else {
  30217. for (f = 0; f < nbfaces; f++) {
  30218. var fl = data.face[f].length; // number of vertices of the current face
  30219. ang = 2 * Math.PI / fl;
  30220. x = 0.5 * Math.tan(ang / 2);
  30221. y = 0.5;
  30222. // positions, uvs, colors
  30223. for (i = 0; i < fl; i++) {
  30224. // positions
  30225. 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);
  30226. indexes.push(index);
  30227. index++;
  30228. // uvs
  30229. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30230. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30231. uvs.push(u, v);
  30232. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30233. y = x * Math.sin(ang) + y * Math.cos(ang);
  30234. x = tmp;
  30235. // colors
  30236. if (faceColors) {
  30237. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30238. }
  30239. }
  30240. // indices from indexes
  30241. for (i = 0; i < fl - 2; i++) {
  30242. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30243. }
  30244. faceIdx += fl;
  30245. }
  30246. }
  30247. VertexData.ComputeNormals(positions, indices, normals);
  30248. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30249. var vertexData = new VertexData();
  30250. vertexData.positions = positions;
  30251. vertexData.indices = indices;
  30252. vertexData.normals = normals;
  30253. vertexData.uvs = uvs;
  30254. if (faceColors && flat) {
  30255. vertexData.colors = colors;
  30256. }
  30257. return vertexData;
  30258. };
  30259. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30260. VertexData.CreateTorusKnot = function (options) {
  30261. var indices = [];
  30262. var positions = [];
  30263. var normals = [];
  30264. var uvs = [];
  30265. var radius = options.radius || 2;
  30266. var tube = options.tube || 0.5;
  30267. var radialSegments = options.radialSegments || 32;
  30268. var tubularSegments = options.tubularSegments || 32;
  30269. var p = options.p || 2;
  30270. var q = options.q || 3;
  30271. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30272. // Helper
  30273. var getPos = function (angle) {
  30274. var cu = Math.cos(angle);
  30275. var su = Math.sin(angle);
  30276. var quOverP = q / p * angle;
  30277. var cs = Math.cos(quOverP);
  30278. var tx = radius * (2 + cs) * 0.5 * cu;
  30279. var ty = radius * (2 + cs) * su * 0.5;
  30280. var tz = radius * Math.sin(quOverP) * 0.5;
  30281. return new BABYLON.Vector3(tx, ty, tz);
  30282. };
  30283. // Vertices
  30284. var i;
  30285. var j;
  30286. for (i = 0; i <= radialSegments; i++) {
  30287. var modI = i % radialSegments;
  30288. var u = modI / radialSegments * 2 * p * Math.PI;
  30289. var p1 = getPos(u);
  30290. var p2 = getPos(u + 0.01);
  30291. var tang = p2.subtract(p1);
  30292. var n = p2.add(p1);
  30293. var bitan = BABYLON.Vector3.Cross(tang, n);
  30294. n = BABYLON.Vector3.Cross(bitan, tang);
  30295. bitan.normalize();
  30296. n.normalize();
  30297. for (j = 0; j < tubularSegments; j++) {
  30298. var modJ = j % tubularSegments;
  30299. var v = modJ / tubularSegments * 2 * Math.PI;
  30300. var cx = -tube * Math.cos(v);
  30301. var cy = tube * Math.sin(v);
  30302. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30303. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30304. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30305. uvs.push(i / radialSegments);
  30306. uvs.push(j / tubularSegments);
  30307. }
  30308. }
  30309. for (i = 0; i < radialSegments; i++) {
  30310. for (j = 0; j < tubularSegments; j++) {
  30311. var jNext = (j + 1) % tubularSegments;
  30312. var a = i * tubularSegments + j;
  30313. var b = (i + 1) * tubularSegments + j;
  30314. var c = (i + 1) * tubularSegments + jNext;
  30315. var d = i * tubularSegments + jNext;
  30316. indices.push(d);
  30317. indices.push(b);
  30318. indices.push(a);
  30319. indices.push(d);
  30320. indices.push(c);
  30321. indices.push(b);
  30322. }
  30323. }
  30324. // Normals
  30325. VertexData.ComputeNormals(positions, indices, normals);
  30326. // Sides
  30327. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30328. // Result
  30329. var vertexData = new VertexData();
  30330. vertexData.indices = indices;
  30331. vertexData.positions = positions;
  30332. vertexData.normals = normals;
  30333. vertexData.uvs = uvs;
  30334. return vertexData;
  30335. };
  30336. // Tools
  30337. /**
  30338. * @param {any} - positions (number[] or Float32Array)
  30339. * @param {any} - indices (number[] or Uint16Array)
  30340. * @param {any} - normals (number[] or Float32Array)
  30341. */
  30342. VertexData.ComputeNormals = function (positions, indices, normals) {
  30343. var index = 0;
  30344. var p1p2x = 0.0;
  30345. var p1p2y = 0.0;
  30346. var p1p2z = 0.0;
  30347. var p3p2x = 0.0;
  30348. var p3p2y = 0.0;
  30349. var p3p2z = 0.0;
  30350. var faceNormalx = 0.0;
  30351. var faceNormaly = 0.0;
  30352. var faceNormalz = 0.0;
  30353. var length = 0.0;
  30354. var i1 = 0;
  30355. var i2 = 0;
  30356. var i3 = 0;
  30357. for (index = 0; index < positions.length; index++) {
  30358. normals[index] = 0.0;
  30359. }
  30360. // indice triplet = 1 face
  30361. var nbFaces = indices.length / 3;
  30362. for (index = 0; index < nbFaces; index++) {
  30363. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30364. i2 = indices[index * 3 + 1];
  30365. i3 = indices[index * 3 + 2];
  30366. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30367. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30368. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30369. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30370. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30371. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30372. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30373. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30374. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30375. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30376. length = (length === 0) ? 1.0 : length;
  30377. faceNormalx /= length; // normalize this normal
  30378. faceNormaly /= length;
  30379. faceNormalz /= length;
  30380. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30381. normals[i1 * 3 + 1] += faceNormaly;
  30382. normals[i1 * 3 + 2] += faceNormalz;
  30383. normals[i2 * 3] += faceNormalx;
  30384. normals[i2 * 3 + 1] += faceNormaly;
  30385. normals[i2 * 3 + 2] += faceNormalz;
  30386. normals[i3 * 3] += faceNormalx;
  30387. normals[i3 * 3 + 1] += faceNormaly;
  30388. normals[i3 * 3 + 2] += faceNormalz;
  30389. }
  30390. // last normalization of each normal
  30391. for (index = 0; index < normals.length / 3; index++) {
  30392. faceNormalx = normals[index * 3];
  30393. faceNormaly = normals[index * 3 + 1];
  30394. faceNormalz = normals[index * 3 + 2];
  30395. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30396. length = (length === 0) ? 1.0 : length;
  30397. faceNormalx /= length;
  30398. faceNormaly /= length;
  30399. faceNormalz /= length;
  30400. normals[index * 3] = faceNormalx;
  30401. normals[index * 3 + 1] = faceNormaly;
  30402. normals[index * 3 + 2] = faceNormalz;
  30403. }
  30404. };
  30405. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30406. var li = indices.length;
  30407. var ln = normals.length;
  30408. var i;
  30409. var n;
  30410. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30411. switch (sideOrientation) {
  30412. case BABYLON.Mesh.FRONTSIDE:
  30413. // nothing changed
  30414. break;
  30415. case BABYLON.Mesh.BACKSIDE:
  30416. var tmp;
  30417. // indices
  30418. for (i = 0; i < li; i += 3) {
  30419. tmp = indices[i];
  30420. indices[i] = indices[i + 2];
  30421. indices[i + 2] = tmp;
  30422. }
  30423. // normals
  30424. for (n = 0; n < ln; n++) {
  30425. normals[n] = -normals[n];
  30426. }
  30427. break;
  30428. case BABYLON.Mesh.DOUBLESIDE:
  30429. // positions
  30430. var lp = positions.length;
  30431. var l = lp / 3;
  30432. for (var p = 0; p < lp; p++) {
  30433. positions[lp + p] = positions[p];
  30434. }
  30435. // indices
  30436. for (i = 0; i < li; i += 3) {
  30437. indices[i + li] = indices[i + 2] + l;
  30438. indices[i + 1 + li] = indices[i + 1] + l;
  30439. indices[i + 2 + li] = indices[i] + l;
  30440. }
  30441. // normals
  30442. for (n = 0; n < ln; n++) {
  30443. normals[ln + n] = -normals[n];
  30444. }
  30445. // uvs
  30446. var lu = uvs.length;
  30447. for (var u = 0; u < lu; u++) {
  30448. uvs[u + lu] = uvs[u];
  30449. }
  30450. break;
  30451. }
  30452. };
  30453. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30454. var vertexData = new VertexData();
  30455. // positions
  30456. var positions = parsedVertexData.positions;
  30457. if (positions) {
  30458. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30459. }
  30460. // normals
  30461. var normals = parsedVertexData.normals;
  30462. if (normals) {
  30463. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30464. }
  30465. // uvs
  30466. var uvs = parsedVertexData.uvs;
  30467. if (uvs) {
  30468. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30469. }
  30470. // uv2s
  30471. var uv2s = parsedVertexData.uv2s;
  30472. if (uv2s) {
  30473. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30474. }
  30475. // uv3s
  30476. var uv3s = parsedVertexData.uv3s;
  30477. if (uv3s) {
  30478. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30479. }
  30480. // uv4s
  30481. var uv4s = parsedVertexData.uv4s;
  30482. if (uv4s) {
  30483. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30484. }
  30485. // uv5s
  30486. var uv5s = parsedVertexData.uv5s;
  30487. if (uv5s) {
  30488. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30489. }
  30490. // uv6s
  30491. var uv6s = parsedVertexData.uv6s;
  30492. if (uv6s) {
  30493. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30494. }
  30495. // colors
  30496. var colors = parsedVertexData.colors;
  30497. if (colors) {
  30498. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30499. }
  30500. // matricesIndices
  30501. var matricesIndices = parsedVertexData.matricesIndices;
  30502. if (matricesIndices) {
  30503. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30504. }
  30505. // matricesWeights
  30506. var matricesWeights = parsedVertexData.matricesWeights;
  30507. if (matricesWeights) {
  30508. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30509. }
  30510. // indices
  30511. var indices = parsedVertexData.indices;
  30512. if (indices) {
  30513. vertexData.indices = indices;
  30514. }
  30515. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30516. };
  30517. return VertexData;
  30518. })();
  30519. BABYLON.VertexData = VertexData;
  30520. })(BABYLON || (BABYLON = {}));
  30521. var BABYLON;
  30522. (function (BABYLON) {
  30523. var Tags = (function () {
  30524. function Tags() {
  30525. }
  30526. Tags.EnableFor = function (obj) {
  30527. obj._tags = obj._tags || {};
  30528. obj.hasTags = function () {
  30529. return Tags.HasTags(obj);
  30530. };
  30531. obj.addTags = function (tagsString) {
  30532. return Tags.AddTagsTo(obj, tagsString);
  30533. };
  30534. obj.removeTags = function (tagsString) {
  30535. return Tags.RemoveTagsFrom(obj, tagsString);
  30536. };
  30537. obj.matchesTagsQuery = function (tagsQuery) {
  30538. return Tags.MatchesQuery(obj, tagsQuery);
  30539. };
  30540. };
  30541. Tags.DisableFor = function (obj) {
  30542. delete obj._tags;
  30543. delete obj.hasTags;
  30544. delete obj.addTags;
  30545. delete obj.removeTags;
  30546. delete obj.matchesTagsQuery;
  30547. };
  30548. Tags.HasTags = function (obj) {
  30549. if (!obj._tags) {
  30550. return false;
  30551. }
  30552. return !BABYLON.Tools.IsEmpty(obj._tags);
  30553. };
  30554. Tags.GetTags = function (obj, asString) {
  30555. if (asString === void 0) { asString = true; }
  30556. if (!obj._tags) {
  30557. return null;
  30558. }
  30559. if (asString) {
  30560. var tagsArray = [];
  30561. for (var tag in obj._tags) {
  30562. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  30563. tagsArray.push(tag);
  30564. }
  30565. }
  30566. return tagsArray.join(" ");
  30567. }
  30568. else {
  30569. return obj._tags;
  30570. }
  30571. };
  30572. // the tags 'true' and 'false' are reserved and cannot be used as tags
  30573. // a tag cannot start with '||', '&&', and '!'
  30574. // it cannot contain whitespaces
  30575. Tags.AddTagsTo = function (obj, tagsString) {
  30576. if (!tagsString) {
  30577. return;
  30578. }
  30579. if (typeof tagsString !== "string") {
  30580. return;
  30581. }
  30582. var tags = tagsString.split(" ");
  30583. for (var t in tags) {
  30584. Tags._AddTagTo(obj, tags[t]);
  30585. }
  30586. };
  30587. Tags._AddTagTo = function (obj, tag) {
  30588. tag = tag.trim();
  30589. if (tag === "" || tag === "true" || tag === "false") {
  30590. return;
  30591. }
  30592. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  30593. return;
  30594. }
  30595. Tags.EnableFor(obj);
  30596. obj._tags[tag] = true;
  30597. };
  30598. Tags.RemoveTagsFrom = function (obj, tagsString) {
  30599. if (!Tags.HasTags(obj)) {
  30600. return;
  30601. }
  30602. var tags = tagsString.split(" ");
  30603. for (var t in tags) {
  30604. Tags._RemoveTagFrom(obj, tags[t]);
  30605. }
  30606. };
  30607. Tags._RemoveTagFrom = function (obj, tag) {
  30608. delete obj._tags[tag];
  30609. };
  30610. Tags.MatchesQuery = function (obj, tagsQuery) {
  30611. if (tagsQuery === undefined) {
  30612. return true;
  30613. }
  30614. if (tagsQuery === "") {
  30615. return Tags.HasTags(obj);
  30616. }
  30617. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  30618. };
  30619. return Tags;
  30620. })();
  30621. BABYLON.Tags = Tags;
  30622. })(BABYLON || (BABYLON = {}));
  30623. var BABYLON;
  30624. (function (BABYLON) {
  30625. var Internals;
  30626. (function (Internals) {
  30627. var AndOrNotEvaluator = (function () {
  30628. function AndOrNotEvaluator() {
  30629. }
  30630. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  30631. if (!query.match(/\([^\(\)]*\)/g)) {
  30632. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  30633. }
  30634. else {
  30635. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  30636. // remove parenthesis
  30637. r = r.slice(1, r.length - 1);
  30638. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  30639. });
  30640. }
  30641. if (query === "true") {
  30642. return true;
  30643. }
  30644. if (query === "false") {
  30645. return false;
  30646. }
  30647. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  30648. };
  30649. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  30650. evaluateCallback = evaluateCallback || (function (r) {
  30651. return r === "true" ? true : false;
  30652. });
  30653. var result;
  30654. var or = parenthesisContent.split("||");
  30655. for (var i in or) {
  30656. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  30657. var and = ori.split("&&");
  30658. if (and.length > 1) {
  30659. for (var j = 0; j < and.length; ++j) {
  30660. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  30661. if (andj !== "true" && andj !== "false") {
  30662. if (andj[0] === "!") {
  30663. result = !evaluateCallback(andj.substring(1));
  30664. }
  30665. else {
  30666. result = evaluateCallback(andj);
  30667. }
  30668. }
  30669. else {
  30670. result = andj === "true" ? true : false;
  30671. }
  30672. if (!result) {
  30673. ori = "false";
  30674. break;
  30675. }
  30676. }
  30677. }
  30678. if (result || ori === "true") {
  30679. result = true;
  30680. break;
  30681. }
  30682. // result equals false (or undefined)
  30683. if (ori !== "true" && ori !== "false") {
  30684. if (ori[0] === "!") {
  30685. result = !evaluateCallback(ori.substring(1));
  30686. }
  30687. else {
  30688. result = evaluateCallback(ori);
  30689. }
  30690. }
  30691. else {
  30692. result = ori === "true" ? true : false;
  30693. }
  30694. }
  30695. // the whole parenthesis scope is replaced by 'true' or 'false'
  30696. return result ? "true" : "false";
  30697. };
  30698. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  30699. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  30700. // remove whitespaces
  30701. r = r.replace(/[\s]/g, function () { return ""; });
  30702. return r.length % 2 ? "!" : "";
  30703. });
  30704. booleanString = booleanString.trim();
  30705. if (booleanString === "!true") {
  30706. booleanString = "false";
  30707. }
  30708. else if (booleanString === "!false") {
  30709. booleanString = "true";
  30710. }
  30711. return booleanString;
  30712. };
  30713. return AndOrNotEvaluator;
  30714. })();
  30715. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  30716. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30717. })(BABYLON || (BABYLON = {}));
  30718. var BABYLON;
  30719. (function (BABYLON) {
  30720. var PostProcessRenderPass = (function () {
  30721. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  30722. this._enabled = true;
  30723. this._refCount = 0;
  30724. this._name = name;
  30725. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  30726. this.setRenderList(renderList);
  30727. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  30728. this._renderTexture.onAfterRenderObservable.add(afterRender);
  30729. this._scene = scene;
  30730. this._renderList = renderList;
  30731. }
  30732. // private
  30733. PostProcessRenderPass.prototype._incRefCount = function () {
  30734. if (this._refCount === 0) {
  30735. this._scene.customRenderTargets.push(this._renderTexture);
  30736. }
  30737. return ++this._refCount;
  30738. };
  30739. PostProcessRenderPass.prototype._decRefCount = function () {
  30740. this._refCount--;
  30741. if (this._refCount <= 0) {
  30742. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  30743. }
  30744. return this._refCount;
  30745. };
  30746. PostProcessRenderPass.prototype._update = function () {
  30747. this.setRenderList(this._renderList);
  30748. };
  30749. // public
  30750. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  30751. this._renderTexture.renderList = renderList;
  30752. };
  30753. PostProcessRenderPass.prototype.getRenderTexture = function () {
  30754. return this._renderTexture;
  30755. };
  30756. return PostProcessRenderPass;
  30757. })();
  30758. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  30759. })(BABYLON || (BABYLON = {}));
  30760. var BABYLON;
  30761. (function (BABYLON) {
  30762. var PostProcessRenderEffect = (function () {
  30763. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  30764. this._engine = engine;
  30765. this._name = name;
  30766. this._singleInstance = singleInstance || true;
  30767. this._getPostProcess = getPostProcess;
  30768. this._cameras = [];
  30769. this._indicesForCamera = [];
  30770. this._postProcesses = {};
  30771. this._renderPasses = {};
  30772. this._renderEffectAsPasses = {};
  30773. }
  30774. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  30775. get: function () {
  30776. for (var index in this._postProcesses) {
  30777. if (!this._postProcesses[index].isSupported) {
  30778. return false;
  30779. }
  30780. }
  30781. return true;
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. PostProcessRenderEffect.prototype._update = function () {
  30787. for (var renderPassName in this._renderPasses) {
  30788. this._renderPasses[renderPassName]._update();
  30789. }
  30790. };
  30791. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  30792. this._renderPasses[renderPass._name] = renderPass;
  30793. this._linkParameters();
  30794. };
  30795. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  30796. delete this._renderPasses[renderPass._name];
  30797. this._linkParameters();
  30798. };
  30799. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  30800. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  30801. this._linkParameters();
  30802. };
  30803. PostProcessRenderEffect.prototype.getPass = function (passName) {
  30804. for (var renderPassName in this._renderPasses) {
  30805. if (renderPassName === passName) {
  30806. return this._renderPasses[passName];
  30807. }
  30808. }
  30809. };
  30810. PostProcessRenderEffect.prototype.emptyPasses = function () {
  30811. this._renderPasses = {};
  30812. this._linkParameters();
  30813. };
  30814. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  30815. var cameraKey;
  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. if (this._singleInstance) {
  30821. cameraKey = 0;
  30822. }
  30823. else {
  30824. cameraKey = cameraName;
  30825. }
  30826. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  30827. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  30828. if (!this._indicesForCamera[cameraName]) {
  30829. this._indicesForCamera[cameraName] = [];
  30830. }
  30831. this._indicesForCamera[cameraName].push(index);
  30832. if (this._cameras.indexOf(camera) === -1) {
  30833. this._cameras[cameraName] = camera;
  30834. }
  30835. for (var passName in this._renderPasses) {
  30836. this._renderPasses[passName]._incRefCount();
  30837. }
  30838. }
  30839. this._linkParameters();
  30840. };
  30841. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  30842. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30843. for (var i = 0; i < _cam.length; i++) {
  30844. var camera = _cam[i];
  30845. var cameraName = camera.name;
  30846. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30847. var index = this._cameras.indexOf(cameraName);
  30848. this._indicesForCamera.splice(index, 1);
  30849. this._cameras.splice(index, 1);
  30850. for (var passName in this._renderPasses) {
  30851. this._renderPasses[passName]._decRefCount();
  30852. }
  30853. }
  30854. };
  30855. PostProcessRenderEffect.prototype._enable = function (cameras) {
  30856. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30857. for (var i = 0; i < _cam.length; i++) {
  30858. var camera = _cam[i];
  30859. var cameraName = camera.name;
  30860. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  30861. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  30862. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  30863. }
  30864. }
  30865. for (var passName in this._renderPasses) {
  30866. this._renderPasses[passName]._incRefCount();
  30867. }
  30868. }
  30869. };
  30870. PostProcessRenderEffect.prototype._disable = function (cameras) {
  30871. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30872. for (var i = 0; i < _cam.length; i++) {
  30873. var camera = _cam[i];
  30874. var cameraName = camera.Name;
  30875. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30876. for (var passName in this._renderPasses) {
  30877. this._renderPasses[passName]._decRefCount();
  30878. }
  30879. }
  30880. };
  30881. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  30882. if (this._singleInstance) {
  30883. return this._postProcesses[0];
  30884. }
  30885. else {
  30886. return this._postProcesses[camera.name];
  30887. }
  30888. };
  30889. PostProcessRenderEffect.prototype._linkParameters = function () {
  30890. var _this = this;
  30891. for (var index in this._postProcesses) {
  30892. if (this.applyParameters) {
  30893. this.applyParameters(this._postProcesses[index]);
  30894. }
  30895. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  30896. _this._linkTextures(effect);
  30897. });
  30898. }
  30899. };
  30900. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  30901. for (var renderPassName in this._renderPasses) {
  30902. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  30903. }
  30904. for (var renderEffectName in this._renderEffectAsPasses) {
  30905. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  30906. }
  30907. };
  30908. return PostProcessRenderEffect;
  30909. })();
  30910. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  30911. })(BABYLON || (BABYLON = {}));
  30912. var BABYLON;
  30913. (function (BABYLON) {
  30914. var PostProcessRenderPipeline = (function () {
  30915. function PostProcessRenderPipeline(engine, name) {
  30916. this._engine = engine;
  30917. this._name = name;
  30918. this._renderEffects = {};
  30919. this._renderEffectsForIsolatedPass = {};
  30920. this._cameras = [];
  30921. }
  30922. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  30923. get: function () {
  30924. for (var renderEffectName in this._renderEffects) {
  30925. if (!this._renderEffects[renderEffectName].isSupported) {
  30926. return false;
  30927. }
  30928. }
  30929. return true;
  30930. },
  30931. enumerable: true,
  30932. configurable: true
  30933. });
  30934. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  30935. this._renderEffects[renderEffect._name] = renderEffect;
  30936. };
  30937. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  30938. var renderEffects = this._renderEffects[renderEffectName];
  30939. if (!renderEffects) {
  30940. return;
  30941. }
  30942. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30943. };
  30944. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30945. var renderEffects = this._renderEffects[renderEffectName];
  30946. if (!renderEffects) {
  30947. return;
  30948. }
  30949. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30950. };
  30951. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30952. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30953. var indicesToDelete = [];
  30954. var i;
  30955. for (i = 0; i < _cam.length; i++) {
  30956. var camera = _cam[i];
  30957. var cameraName = camera.name;
  30958. if (this._cameras.indexOf(camera) === -1) {
  30959. this._cameras[cameraName] = camera;
  30960. }
  30961. else if (unique) {
  30962. indicesToDelete.push(i);
  30963. }
  30964. }
  30965. for (i = 0; i < indicesToDelete.length; i++) {
  30966. cameras.splice(indicesToDelete[i], 1);
  30967. }
  30968. for (var renderEffectName in this._renderEffects) {
  30969. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30970. }
  30971. };
  30972. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30973. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30974. for (var renderEffectName in this._renderEffects) {
  30975. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30976. }
  30977. for (var i = 0; i < _cam.length; i++) {
  30978. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30979. }
  30980. };
  30981. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30982. var _this = this;
  30983. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30984. var pass = null;
  30985. var renderEffectName;
  30986. for (renderEffectName in this._renderEffects) {
  30987. pass = this._renderEffects[renderEffectName].getPass(passName);
  30988. if (pass != null) {
  30989. break;
  30990. }
  30991. }
  30992. if (pass === null) {
  30993. return;
  30994. }
  30995. for (renderEffectName in this._renderEffects) {
  30996. this._renderEffects[renderEffectName]._disable(_cam);
  30997. }
  30998. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30999. for (var i = 0; i < _cam.length; i++) {
  31000. var camera = _cam[i];
  31001. var cameraName = camera.name;
  31002. 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); });
  31003. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31004. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31005. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31006. }
  31007. };
  31008. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31009. var _this = this;
  31010. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31011. for (var i = 0; i < _cam.length; i++) {
  31012. var camera = _cam[i];
  31013. var cameraName = camera.name;
  31014. 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); });
  31015. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31016. }
  31017. for (var renderEffectName in this._renderEffects) {
  31018. this._renderEffects[renderEffectName]._enable(_cam);
  31019. }
  31020. };
  31021. PostProcessRenderPipeline.prototype._update = function () {
  31022. for (var renderEffectName in this._renderEffects) {
  31023. this._renderEffects[renderEffectName]._update();
  31024. }
  31025. for (var i = 0; i < this._cameras.length; i++) {
  31026. var cameraName = this._cameras[i].name;
  31027. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31028. this._renderEffectsForIsolatedPass[cameraName]._update();
  31029. }
  31030. }
  31031. };
  31032. PostProcessRenderPipeline.prototype.dispose = function () {
  31033. // Must be implemented by children
  31034. };
  31035. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31036. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31037. return PostProcessRenderPipeline;
  31038. })();
  31039. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31040. })(BABYLON || (BABYLON = {}));
  31041. var BABYLON;
  31042. (function (BABYLON) {
  31043. var PostProcessRenderPipelineManager = (function () {
  31044. function PostProcessRenderPipelineManager() {
  31045. this._renderPipelines = {};
  31046. }
  31047. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31048. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31049. };
  31050. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31051. var renderPipeline = this._renderPipelines[renderPipelineName];
  31052. if (!renderPipeline) {
  31053. return;
  31054. }
  31055. renderPipeline._attachCameras(cameras, unique);
  31056. };
  31057. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31058. var renderPipeline = this._renderPipelines[renderPipelineName];
  31059. if (!renderPipeline) {
  31060. return;
  31061. }
  31062. renderPipeline._detachCameras(cameras);
  31063. };
  31064. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31065. var renderPipeline = this._renderPipelines[renderPipelineName];
  31066. if (!renderPipeline) {
  31067. return;
  31068. }
  31069. renderPipeline._enableEffect(renderEffectName, cameras);
  31070. };
  31071. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31072. var renderPipeline = this._renderPipelines[renderPipelineName];
  31073. if (!renderPipeline) {
  31074. return;
  31075. }
  31076. renderPipeline._disableEffect(renderEffectName, cameras);
  31077. };
  31078. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31079. var renderPipeline = this._renderPipelines[renderPipelineName];
  31080. if (!renderPipeline) {
  31081. return;
  31082. }
  31083. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31084. };
  31085. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31086. var renderPipeline = this._renderPipelines[renderPipelineName];
  31087. if (!renderPipeline) {
  31088. return;
  31089. }
  31090. renderPipeline._disableDisplayOnlyPass(cameras);
  31091. };
  31092. PostProcessRenderPipelineManager.prototype.update = function () {
  31093. for (var renderPipelineName in this._renderPipelines) {
  31094. var pipeline = this._renderPipelines[renderPipelineName];
  31095. if (!pipeline.isSupported) {
  31096. pipeline.dispose();
  31097. delete this._renderPipelines[renderPipelineName];
  31098. }
  31099. else {
  31100. pipeline._update();
  31101. }
  31102. }
  31103. };
  31104. return PostProcessRenderPipelineManager;
  31105. })();
  31106. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31107. })(BABYLON || (BABYLON = {}));
  31108. var BABYLON;
  31109. (function (BABYLON) {
  31110. var BoundingBoxRenderer = (function () {
  31111. function BoundingBoxRenderer(scene) {
  31112. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31113. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31114. this.showBackLines = true;
  31115. this.renderList = new BABYLON.SmartArray(32);
  31116. this._vertexBuffers = {};
  31117. this._scene = scene;
  31118. }
  31119. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31120. if (this._colorShader) {
  31121. return;
  31122. }
  31123. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31124. attributes: [BABYLON.VertexBuffer.PositionKind],
  31125. uniforms: ["worldViewProjection", "color"]
  31126. });
  31127. var engine = this._scene.getEngine();
  31128. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31130. this._indexBuffer = 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]);
  31131. };
  31132. BoundingBoxRenderer.prototype.reset = function () {
  31133. this.renderList.reset();
  31134. };
  31135. BoundingBoxRenderer.prototype.render = function () {
  31136. if (this.renderList.length === 0) {
  31137. return;
  31138. }
  31139. this._prepareRessources();
  31140. if (!this._colorShader.isReady()) {
  31141. return;
  31142. }
  31143. var engine = this._scene.getEngine();
  31144. engine.setDepthWrite(false);
  31145. this._colorShader._preBind();
  31146. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31147. var boundingBox = this.renderList.data[boundingBoxIndex];
  31148. var min = boundingBox.minimum;
  31149. var max = boundingBox.maximum;
  31150. var diff = max.subtract(min);
  31151. var median = min.add(diff.scale(0.5));
  31152. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31153. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31154. .multiply(boundingBox.getWorldMatrix());
  31155. // VBOs
  31156. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31157. if (this.showBackLines) {
  31158. // Back
  31159. engine.setDepthFunctionToGreaterOrEqual();
  31160. this._scene.resetCachedMaterial();
  31161. this._colorShader.setColor4("color", this.backColor.toColor4());
  31162. this._colorShader.bind(worldMatrix);
  31163. // Draw order
  31164. engine.draw(false, 0, 24);
  31165. }
  31166. // Front
  31167. engine.setDepthFunctionToLess();
  31168. this._scene.resetCachedMaterial();
  31169. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31170. this._colorShader.bind(worldMatrix);
  31171. // Draw order
  31172. engine.draw(false, 0, 24);
  31173. }
  31174. this._colorShader.unbind();
  31175. engine.setDepthFunctionToLessOrEqual();
  31176. engine.setDepthWrite(true);
  31177. };
  31178. BoundingBoxRenderer.prototype.dispose = function () {
  31179. if (!this._colorShader) {
  31180. return;
  31181. }
  31182. this._colorShader.dispose();
  31183. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31184. if (buffer) {
  31185. buffer.dispose();
  31186. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31187. }
  31188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31189. };
  31190. return BoundingBoxRenderer;
  31191. })();
  31192. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31193. })(BABYLON || (BABYLON = {}));
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. var Condition = (function () {
  31197. function Condition(actionManager) {
  31198. this._actionManager = actionManager;
  31199. }
  31200. Condition.prototype.isValid = function () {
  31201. return true;
  31202. };
  31203. Condition.prototype._getProperty = function (propertyPath) {
  31204. return this._actionManager._getProperty(propertyPath);
  31205. };
  31206. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31207. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31208. };
  31209. Condition.prototype.serialize = function () {
  31210. };
  31211. Condition.prototype._serialize = function (serializedCondition) {
  31212. return {
  31213. type: 2,
  31214. children: [],
  31215. name: serializedCondition.name,
  31216. properties: serializedCondition.properties
  31217. };
  31218. };
  31219. return Condition;
  31220. })();
  31221. BABYLON.Condition = Condition;
  31222. var ValueCondition = (function (_super) {
  31223. __extends(ValueCondition, _super);
  31224. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31225. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31226. _super.call(this, actionManager);
  31227. this.propertyPath = propertyPath;
  31228. this.value = value;
  31229. this.operator = operator;
  31230. this._target = target;
  31231. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31232. this._property = this._getProperty(this.propertyPath);
  31233. }
  31234. Object.defineProperty(ValueCondition, "IsEqual", {
  31235. get: function () {
  31236. return ValueCondition._IsEqual;
  31237. },
  31238. enumerable: true,
  31239. configurable: true
  31240. });
  31241. Object.defineProperty(ValueCondition, "IsDifferent", {
  31242. get: function () {
  31243. return ValueCondition._IsDifferent;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(ValueCondition, "IsGreater", {
  31249. get: function () {
  31250. return ValueCondition._IsGreater;
  31251. },
  31252. enumerable: true,
  31253. configurable: true
  31254. });
  31255. Object.defineProperty(ValueCondition, "IsLesser", {
  31256. get: function () {
  31257. return ValueCondition._IsLesser;
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. // Methods
  31263. ValueCondition.prototype.isValid = function () {
  31264. switch (this.operator) {
  31265. case ValueCondition.IsGreater:
  31266. return this._effectiveTarget[this._property] > this.value;
  31267. case ValueCondition.IsLesser:
  31268. return this._effectiveTarget[this._property] < this.value;
  31269. case ValueCondition.IsEqual:
  31270. case ValueCondition.IsDifferent:
  31271. var check;
  31272. if (this.value.equals) {
  31273. check = this.value.equals(this._effectiveTarget[this._property]);
  31274. }
  31275. else {
  31276. check = this.value === this._effectiveTarget[this._property];
  31277. }
  31278. return this.operator === ValueCondition.IsEqual ? check : !check;
  31279. }
  31280. return false;
  31281. };
  31282. ValueCondition.prototype.serialize = function () {
  31283. return this._serialize({
  31284. name: "ValueCondition",
  31285. properties: [
  31286. BABYLON.Action._GetTargetProperty(this._target),
  31287. { name: "propertyPath", value: this.propertyPath },
  31288. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31289. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31290. ]
  31291. });
  31292. };
  31293. ValueCondition.GetOperatorName = function (operator) {
  31294. switch (operator) {
  31295. case ValueCondition._IsEqual: return "IsEqual";
  31296. case ValueCondition._IsDifferent: return "IsDifferent";
  31297. case ValueCondition._IsGreater: return "IsGreater";
  31298. case ValueCondition._IsLesser: return "IsLesser";
  31299. default: return "";
  31300. }
  31301. };
  31302. // Statics
  31303. ValueCondition._IsEqual = 0;
  31304. ValueCondition._IsDifferent = 1;
  31305. ValueCondition._IsGreater = 2;
  31306. ValueCondition._IsLesser = 3;
  31307. return ValueCondition;
  31308. })(Condition);
  31309. BABYLON.ValueCondition = ValueCondition;
  31310. var PredicateCondition = (function (_super) {
  31311. __extends(PredicateCondition, _super);
  31312. function PredicateCondition(actionManager, predicate) {
  31313. _super.call(this, actionManager);
  31314. this.predicate = predicate;
  31315. }
  31316. PredicateCondition.prototype.isValid = function () {
  31317. return this.predicate();
  31318. };
  31319. return PredicateCondition;
  31320. })(Condition);
  31321. BABYLON.PredicateCondition = PredicateCondition;
  31322. var StateCondition = (function (_super) {
  31323. __extends(StateCondition, _super);
  31324. function StateCondition(actionManager, target, value) {
  31325. _super.call(this, actionManager);
  31326. this.value = value;
  31327. this._target = target;
  31328. }
  31329. // Methods
  31330. StateCondition.prototype.isValid = function () {
  31331. return this._target.state === this.value;
  31332. };
  31333. StateCondition.prototype.serialize = function () {
  31334. return this._serialize({
  31335. name: "StateCondition",
  31336. properties: [
  31337. BABYLON.Action._GetTargetProperty(this._target),
  31338. { name: "value", value: this.value }
  31339. ]
  31340. });
  31341. };
  31342. return StateCondition;
  31343. })(Condition);
  31344. BABYLON.StateCondition = StateCondition;
  31345. })(BABYLON || (BABYLON = {}));
  31346. var BABYLON;
  31347. (function (BABYLON) {
  31348. var Action = (function () {
  31349. function Action(triggerOptions, condition) {
  31350. this.triggerOptions = triggerOptions;
  31351. if (triggerOptions.parameter) {
  31352. this.trigger = triggerOptions.trigger;
  31353. this._triggerParameter = triggerOptions.parameter;
  31354. }
  31355. else {
  31356. this.trigger = triggerOptions;
  31357. }
  31358. this._nextActiveAction = this;
  31359. this._condition = condition;
  31360. }
  31361. // Methods
  31362. Action.prototype._prepare = function () {
  31363. };
  31364. Action.prototype.getTriggerParameter = function () {
  31365. return this._triggerParameter;
  31366. };
  31367. Action.prototype._executeCurrent = function (evt) {
  31368. if (this._nextActiveAction._condition) {
  31369. var condition = this._nextActiveAction._condition;
  31370. var currentRenderId = this._actionManager.getScene().getRenderId();
  31371. // We cache the current evaluation for the current frame
  31372. if (condition._evaluationId === currentRenderId) {
  31373. if (!condition._currentResult) {
  31374. return;
  31375. }
  31376. }
  31377. else {
  31378. condition._evaluationId = currentRenderId;
  31379. if (!condition.isValid()) {
  31380. condition._currentResult = false;
  31381. return;
  31382. }
  31383. condition._currentResult = true;
  31384. }
  31385. }
  31386. this._nextActiveAction.execute(evt);
  31387. this.skipToNextActiveAction();
  31388. };
  31389. Action.prototype.execute = function (evt) {
  31390. };
  31391. Action.prototype.skipToNextActiveAction = function () {
  31392. if (this._nextActiveAction._child) {
  31393. if (!this._nextActiveAction._child._actionManager) {
  31394. this._nextActiveAction._child._actionManager = this._actionManager;
  31395. }
  31396. this._nextActiveAction = this._nextActiveAction._child;
  31397. }
  31398. else {
  31399. this._nextActiveAction = this;
  31400. }
  31401. };
  31402. Action.prototype.then = function (action) {
  31403. this._child = action;
  31404. action._actionManager = this._actionManager;
  31405. action._prepare();
  31406. return action;
  31407. };
  31408. Action.prototype._getProperty = function (propertyPath) {
  31409. return this._actionManager._getProperty(propertyPath);
  31410. };
  31411. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31412. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31413. };
  31414. Action.prototype.serialize = function (parent) {
  31415. };
  31416. // Called by BABYLON.Action objects in serialize(...). Internal use
  31417. Action.prototype._serialize = function (serializedAction, parent) {
  31418. var serializationObject = {
  31419. type: 1,
  31420. children: [],
  31421. name: serializedAction.name,
  31422. properties: serializedAction.properties || []
  31423. };
  31424. // Serialize child
  31425. if (this._child) {
  31426. this._child.serialize(serializationObject);
  31427. }
  31428. // Check if "this" has a condition
  31429. if (this._condition) {
  31430. var serializedCondition = this._condition.serialize();
  31431. serializedCondition.children.push(serializationObject);
  31432. if (parent) {
  31433. parent.children.push(serializedCondition);
  31434. }
  31435. return serializedCondition;
  31436. }
  31437. if (parent) {
  31438. parent.children.push(serializationObject);
  31439. }
  31440. return serializationObject;
  31441. };
  31442. Action._SerializeValueAsString = function (value) {
  31443. if (typeof value === "number") {
  31444. return value.toString();
  31445. }
  31446. if (typeof value === "boolean") {
  31447. return value ? "true" : "false";
  31448. }
  31449. if (value instanceof BABYLON.Vector2) {
  31450. return value.x + ", " + value.y;
  31451. }
  31452. if (value instanceof BABYLON.Vector3) {
  31453. return value.x + ", " + value.y + ", " + value.z;
  31454. }
  31455. if (value instanceof BABYLON.Color3) {
  31456. return value.r + ", " + value.g + ", " + value.b;
  31457. }
  31458. if (value instanceof BABYLON.Color4) {
  31459. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31460. }
  31461. return value; // string
  31462. };
  31463. Action._GetTargetProperty = function (target) {
  31464. return {
  31465. name: "target",
  31466. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31467. : target instanceof BABYLON.Light ? "LightProperties"
  31468. : target instanceof BABYLON.Camera ? "CameraProperties"
  31469. : "SceneProperties",
  31470. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31471. };
  31472. };
  31473. return Action;
  31474. })();
  31475. BABYLON.Action = Action;
  31476. })(BABYLON || (BABYLON = {}));
  31477. var BABYLON;
  31478. (function (BABYLON) {
  31479. /**
  31480. * ActionEvent is the event beint sent when an action is triggered.
  31481. */
  31482. var ActionEvent = (function () {
  31483. /**
  31484. * @constructor
  31485. * @param source The mesh or sprite that triggered the action.
  31486. * @param pointerX The X mouse cursor position at the time of the event
  31487. * @param pointerY The Y mouse cursor position at the time of the event
  31488. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31489. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31490. */
  31491. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31492. this.source = source;
  31493. this.pointerX = pointerX;
  31494. this.pointerY = pointerY;
  31495. this.meshUnderPointer = meshUnderPointer;
  31496. this.sourceEvent = sourceEvent;
  31497. this.additionalData = additionalData;
  31498. }
  31499. /**
  31500. * Helper function to auto-create an ActionEvent from a source mesh.
  31501. * @param source The source mesh that triggered the event
  31502. * @param evt {Event} The original (browser) event
  31503. */
  31504. ActionEvent.CreateNew = function (source, evt, additionalData) {
  31505. var scene = source.getScene();
  31506. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31507. };
  31508. /**
  31509. * Helper function to auto-create an ActionEvent from a source mesh.
  31510. * @param source The source sprite that triggered the event
  31511. * @param scene Scene associated with the sprite
  31512. * @param evt {Event} The original (browser) event
  31513. */
  31514. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  31515. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31516. };
  31517. /**
  31518. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  31519. * @param scene the scene where the event occurred
  31520. * @param evt {Event} The original (browser) event
  31521. */
  31522. ActionEvent.CreateNewFromScene = function (scene, evt) {
  31523. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  31524. };
  31525. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  31526. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  31527. };
  31528. return ActionEvent;
  31529. })();
  31530. BABYLON.ActionEvent = ActionEvent;
  31531. /**
  31532. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  31533. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  31534. */
  31535. var ActionManager = (function () {
  31536. function ActionManager(scene) {
  31537. // Members
  31538. this.actions = new Array();
  31539. this._scene = scene;
  31540. scene._actionManagers.push(this);
  31541. }
  31542. Object.defineProperty(ActionManager, "NothingTrigger", {
  31543. get: function () {
  31544. return ActionManager._NothingTrigger;
  31545. },
  31546. enumerable: true,
  31547. configurable: true
  31548. });
  31549. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31550. get: function () {
  31551. return ActionManager._OnPickTrigger;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31557. get: function () {
  31558. return ActionManager._OnLeftPickTrigger;
  31559. },
  31560. enumerable: true,
  31561. configurable: true
  31562. });
  31563. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  31564. get: function () {
  31565. return ActionManager._OnRightPickTrigger;
  31566. },
  31567. enumerable: true,
  31568. configurable: true
  31569. });
  31570. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  31571. get: function () {
  31572. return ActionManager._OnCenterPickTrigger;
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  31578. get: function () {
  31579. return ActionManager._OnPickDownTrigger;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  31585. get: function () {
  31586. return ActionManager._OnPickUpTrigger;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  31592. /// This trigger will only be raised if you also declared a OnPickDown
  31593. get: function () {
  31594. return ActionManager._OnPickOutTrigger;
  31595. },
  31596. enumerable: true,
  31597. configurable: true
  31598. });
  31599. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  31600. get: function () {
  31601. return ActionManager._OnLongPressTrigger;
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  31607. get: function () {
  31608. return ActionManager._OnPointerOverTrigger;
  31609. },
  31610. enumerable: true,
  31611. configurable: true
  31612. });
  31613. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  31614. get: function () {
  31615. return ActionManager._OnPointerOutTrigger;
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  31621. get: function () {
  31622. return ActionManager._OnEveryFrameTrigger;
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  31628. get: function () {
  31629. return ActionManager._OnIntersectionEnterTrigger;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  31635. get: function () {
  31636. return ActionManager._OnIntersectionExitTrigger;
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  31642. get: function () {
  31643. return ActionManager._OnKeyDownTrigger;
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  31649. get: function () {
  31650. return ActionManager._OnKeyUpTrigger;
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. // Methods
  31656. ActionManager.prototype.dispose = function () {
  31657. var index = this._scene._actionManagers.indexOf(this);
  31658. if (index > -1) {
  31659. this._scene._actionManagers.splice(index, 1);
  31660. }
  31661. };
  31662. ActionManager.prototype.getScene = function () {
  31663. return this._scene;
  31664. };
  31665. /**
  31666. * Does this action manager handles actions of any of the given triggers
  31667. * @param {number[]} triggers - the triggers to be tested
  31668. * @return {boolean} whether one (or more) of the triggers is handeled
  31669. */
  31670. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  31671. for (var index = 0; index < this.actions.length; index++) {
  31672. var action = this.actions[index];
  31673. if (triggers.indexOf(action.trigger) > -1) {
  31674. return true;
  31675. }
  31676. }
  31677. return false;
  31678. };
  31679. /**
  31680. * Does this action manager handles actions of a given trigger
  31681. * @param {number} trigger - the trigger to be tested
  31682. * @return {boolean} whether the trigger is handeled
  31683. */
  31684. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  31685. for (var index = 0; index < this.actions.length; index++) {
  31686. var action = this.actions[index];
  31687. if (action.trigger === trigger) {
  31688. return true;
  31689. }
  31690. }
  31691. return false;
  31692. };
  31693. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  31694. /**
  31695. * Does this action manager has pointer triggers
  31696. * @return {boolean} whether or not it has pointer triggers
  31697. */
  31698. get: function () {
  31699. for (var index = 0; index < this.actions.length; index++) {
  31700. var action = this.actions[index];
  31701. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  31702. return true;
  31703. }
  31704. }
  31705. return false;
  31706. },
  31707. enumerable: true,
  31708. configurable: true
  31709. });
  31710. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  31711. /**
  31712. * Does this action manager has pick triggers
  31713. * @return {boolean} whether or not it has pick triggers
  31714. */
  31715. get: function () {
  31716. for (var index = 0; index < this.actions.length; index++) {
  31717. var action = this.actions[index];
  31718. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  31719. return true;
  31720. }
  31721. }
  31722. return false;
  31723. },
  31724. enumerable: true,
  31725. configurable: true
  31726. });
  31727. /**
  31728. * Registers an action to this action manager
  31729. * @param {BABYLON.Action} action - the action to be registered
  31730. * @return {BABYLON.Action} the action amended (prepared) after registration
  31731. */
  31732. ActionManager.prototype.registerAction = function (action) {
  31733. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  31734. if (this.getScene().actionManager !== this) {
  31735. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  31736. return null;
  31737. }
  31738. }
  31739. this.actions.push(action);
  31740. action._actionManager = this;
  31741. action._prepare();
  31742. return action;
  31743. };
  31744. /**
  31745. * Process a specific trigger
  31746. * @param {number} trigger - the trigger to process
  31747. * @param evt {BABYLON.ActionEvent} the event details to be processed
  31748. */
  31749. ActionManager.prototype.processTrigger = function (trigger, evt) {
  31750. for (var index = 0; index < this.actions.length; index++) {
  31751. var action = this.actions[index];
  31752. if (action.trigger === trigger) {
  31753. if (trigger === ActionManager.OnKeyUpTrigger
  31754. || trigger === ActionManager.OnKeyDownTrigger) {
  31755. var parameter = action.getTriggerParameter();
  31756. if (parameter) {
  31757. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  31758. var actualkey = String.fromCharCode(unicode).toLowerCase();
  31759. if (actualkey !== parameter.toLowerCase()) {
  31760. continue;
  31761. }
  31762. }
  31763. }
  31764. action._executeCurrent(evt);
  31765. }
  31766. }
  31767. };
  31768. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  31769. var properties = propertyPath.split(".");
  31770. for (var index = 0; index < properties.length - 1; index++) {
  31771. target = target[properties[index]];
  31772. }
  31773. return target;
  31774. };
  31775. ActionManager.prototype._getProperty = function (propertyPath) {
  31776. var properties = propertyPath.split(".");
  31777. return properties[properties.length - 1];
  31778. };
  31779. ActionManager.prototype.serialize = function (name) {
  31780. var root = {
  31781. children: [],
  31782. name: name,
  31783. type: 3,
  31784. properties: [] // Empty for root but required
  31785. };
  31786. for (var i = 0; i < this.actions.length; i++) {
  31787. var triggerObject = {
  31788. type: 0,
  31789. children: [],
  31790. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  31791. properties: []
  31792. };
  31793. var triggerOptions = this.actions[i].triggerOptions;
  31794. if (triggerOptions && typeof triggerOptions !== "number") {
  31795. if (triggerOptions.parameter instanceof BABYLON.Node) {
  31796. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  31797. }
  31798. else {
  31799. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  31800. }
  31801. }
  31802. // Serialize child action, recursively
  31803. this.actions[i].serialize(triggerObject);
  31804. // Add serialized trigger
  31805. root.children.push(triggerObject);
  31806. }
  31807. return root;
  31808. };
  31809. ActionManager.Parse = function (parsedActions, object, scene) {
  31810. var actionManager = new BABYLON.ActionManager(scene);
  31811. if (object === null)
  31812. scene.actionManager = actionManager;
  31813. else
  31814. object.actionManager = actionManager;
  31815. // instanciate a new object
  31816. var instanciate = function (name, params) {
  31817. var newInstance = Object.create(BABYLON[name].prototype);
  31818. newInstance.constructor.apply(newInstance, params);
  31819. return newInstance;
  31820. };
  31821. var parseParameter = function (name, value, target, propertyPath) {
  31822. if (propertyPath === null) {
  31823. // String, boolean or float
  31824. var floatValue = parseFloat(value);
  31825. if (value === "true" || value === "false")
  31826. return value === "true";
  31827. else
  31828. return isNaN(floatValue) ? value : floatValue;
  31829. }
  31830. var effectiveTarget = propertyPath.split(".");
  31831. var values = value.split(",");
  31832. // Get effective Target
  31833. for (var i = 0; i < effectiveTarget.length; i++) {
  31834. target = target[effectiveTarget[i]];
  31835. }
  31836. // Return appropriate value with its type
  31837. if (typeof (target) === "boolean")
  31838. return values[0] === "true";
  31839. if (typeof (target) === "string")
  31840. return values[0];
  31841. // Parameters with multiple values such as Vector3 etc.
  31842. var split = new Array();
  31843. for (var i = 0; i < values.length; i++)
  31844. split.push(parseFloat(values[i]));
  31845. if (target instanceof BABYLON.Vector3)
  31846. return BABYLON.Vector3.FromArray(split);
  31847. if (target instanceof BABYLON.Vector4)
  31848. return BABYLON.Vector4.FromArray(split);
  31849. if (target instanceof BABYLON.Color3)
  31850. return BABYLON.Color3.FromArray(split);
  31851. if (target instanceof BABYLON.Color4)
  31852. return BABYLON.Color4.FromArray(split);
  31853. return parseFloat(values[0]);
  31854. };
  31855. // traverse graph per trigger
  31856. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  31857. if (combineArray === void 0) { combineArray = null; }
  31858. if (parsedAction.detached)
  31859. return;
  31860. var parameters = new Array();
  31861. var target = null;
  31862. var propertyPath = null;
  31863. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  31864. // Parameters
  31865. if (parsedAction.type === 2)
  31866. parameters.push(actionManager);
  31867. else
  31868. parameters.push(trigger);
  31869. if (combine) {
  31870. var actions = new Array();
  31871. for (var j = 0; j < parsedAction.combine.length; j++) {
  31872. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  31873. }
  31874. parameters.push(actions);
  31875. }
  31876. else {
  31877. for (var i = 0; i < parsedAction.properties.length; i++) {
  31878. var value = parsedAction.properties[i].value;
  31879. var name = parsedAction.properties[i].name;
  31880. var targetType = parsedAction.properties[i].targetType;
  31881. if (name === "target")
  31882. if (targetType !== null && targetType === "SceneProperties")
  31883. value = target = scene;
  31884. else
  31885. value = target = scene.getNodeByName(value);
  31886. else if (name === "parent")
  31887. value = scene.getNodeByName(value);
  31888. else if (name === "sound")
  31889. value = scene.getSoundByName(value);
  31890. else if (name !== "propertyPath") {
  31891. if (parsedAction.type === 2 && name === "operator")
  31892. value = BABYLON.ValueCondition[value];
  31893. else
  31894. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  31895. }
  31896. else {
  31897. propertyPath = value;
  31898. }
  31899. parameters.push(value);
  31900. }
  31901. }
  31902. if (combineArray === null) {
  31903. parameters.push(condition);
  31904. }
  31905. else {
  31906. parameters.push(null);
  31907. }
  31908. // If interpolate value action
  31909. if (parsedAction.name === "InterpolateValueAction") {
  31910. var param = parameters[parameters.length - 2];
  31911. parameters[parameters.length - 1] = param;
  31912. parameters[parameters.length - 2] = condition;
  31913. }
  31914. // Action or condition(s) and not CombineAction
  31915. var newAction = instanciate(parsedAction.name, parameters);
  31916. if (newAction instanceof BABYLON.Condition && condition !== null) {
  31917. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  31918. if (action)
  31919. action.then(nothing);
  31920. else
  31921. actionManager.registerAction(nothing);
  31922. action = nothing;
  31923. }
  31924. if (combineArray === null) {
  31925. if (newAction instanceof BABYLON.Condition) {
  31926. condition = newAction;
  31927. newAction = action;
  31928. }
  31929. else {
  31930. condition = null;
  31931. if (action)
  31932. action.then(newAction);
  31933. else
  31934. actionManager.registerAction(newAction);
  31935. }
  31936. }
  31937. else {
  31938. combineArray.push(newAction);
  31939. }
  31940. for (var i = 0; i < parsedAction.children.length; i++)
  31941. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  31942. };
  31943. // triggers
  31944. for (var i = 0; i < parsedActions.children.length; i++) {
  31945. var triggerParams;
  31946. var trigger = parsedActions.children[i];
  31947. if (trigger.properties.length > 0) {
  31948. var param = trigger.properties[0].value;
  31949. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  31950. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  31951. }
  31952. else
  31953. triggerParams = BABYLON.ActionManager[trigger.name];
  31954. for (var j = 0; j < trigger.children.length; j++) {
  31955. if (!trigger.detached)
  31956. traverse(trigger.children[j], triggerParams, null, null);
  31957. }
  31958. }
  31959. };
  31960. ActionManager.GetTriggerName = function (trigger) {
  31961. switch (trigger) {
  31962. case 0: return "NothingTrigger";
  31963. case 1: return "OnPickTrigger";
  31964. case 2: return "OnLeftPickTrigger";
  31965. case 3: return "OnRightPickTrigger";
  31966. case 4: return "OnCenterPickTrigger";
  31967. case 5: return "OnPickDownTrigger";
  31968. case 6: return "OnPickUpTrigger";
  31969. case 7: return "OnLongPressTrigger";
  31970. case 8: return "OnPointerOverTrigger";
  31971. case 9: return "OnPointerOutTrigger";
  31972. case 10: return "OnEveryFrameTrigger";
  31973. case 11: return "OnIntersectionEnterTrigger";
  31974. case 12: return "OnIntersectionExitTrigger";
  31975. case 13: return "OnKeyDownTrigger";
  31976. case 14: return "OnKeyUpTrigger";
  31977. case 15: return "OnPickOutTrigger";
  31978. default: return "";
  31979. }
  31980. };
  31981. // Statics
  31982. ActionManager._NothingTrigger = 0;
  31983. ActionManager._OnPickTrigger = 1;
  31984. ActionManager._OnLeftPickTrigger = 2;
  31985. ActionManager._OnRightPickTrigger = 3;
  31986. ActionManager._OnCenterPickTrigger = 4;
  31987. ActionManager._OnPickDownTrigger = 5;
  31988. ActionManager._OnPickUpTrigger = 6;
  31989. ActionManager._OnLongPressTrigger = 7;
  31990. ActionManager._OnPointerOverTrigger = 8;
  31991. ActionManager._OnPointerOutTrigger = 9;
  31992. ActionManager._OnEveryFrameTrigger = 10;
  31993. ActionManager._OnIntersectionEnterTrigger = 11;
  31994. ActionManager._OnIntersectionExitTrigger = 12;
  31995. ActionManager._OnKeyDownTrigger = 13;
  31996. ActionManager._OnKeyUpTrigger = 14;
  31997. ActionManager._OnPickOutTrigger = 15;
  31998. ActionManager.DragMovementThreshold = 10; // in pixels
  31999. ActionManager.LongPressDelay = 500; // in milliseconds
  32000. return ActionManager;
  32001. })();
  32002. BABYLON.ActionManager = ActionManager;
  32003. })(BABYLON || (BABYLON = {}));
  32004. var BABYLON;
  32005. (function (BABYLON) {
  32006. var InterpolateValueAction = (function (_super) {
  32007. __extends(InterpolateValueAction, _super);
  32008. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32009. if (duration === void 0) { duration = 1000; }
  32010. _super.call(this, triggerOptions, condition);
  32011. this.propertyPath = propertyPath;
  32012. this.value = value;
  32013. this.duration = duration;
  32014. this.stopOtherAnimations = stopOtherAnimations;
  32015. this.onInterpolationDone = onInterpolationDone;
  32016. this._target = this._effectiveTarget = target;
  32017. }
  32018. InterpolateValueAction.prototype._prepare = function () {
  32019. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32020. this._property = this._getProperty(this.propertyPath);
  32021. };
  32022. InterpolateValueAction.prototype.execute = function () {
  32023. var scene = this._actionManager.getScene();
  32024. var keys = [
  32025. {
  32026. frame: 0,
  32027. value: this._effectiveTarget[this._property]
  32028. }, {
  32029. frame: 100,
  32030. value: this.value
  32031. }
  32032. ];
  32033. var dataType;
  32034. if (typeof this.value === "number") {
  32035. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32036. }
  32037. else if (this.value instanceof BABYLON.Color3) {
  32038. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32039. }
  32040. else if (this.value instanceof BABYLON.Vector3) {
  32041. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32042. }
  32043. else if (this.value instanceof BABYLON.Matrix) {
  32044. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32045. }
  32046. else if (this.value instanceof BABYLON.Quaternion) {
  32047. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32048. }
  32049. else {
  32050. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32051. return;
  32052. }
  32053. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32054. animation.setKeys(keys);
  32055. if (this.stopOtherAnimations) {
  32056. scene.stopAnimation(this._effectiveTarget);
  32057. }
  32058. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32059. };
  32060. InterpolateValueAction.prototype.serialize = function (parent) {
  32061. return _super.prototype._serialize.call(this, {
  32062. name: "InterpolateValueAction",
  32063. properties: [
  32064. BABYLON.Action._GetTargetProperty(this._target),
  32065. { name: "propertyPath", value: this.propertyPath },
  32066. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32067. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32068. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32069. ]
  32070. }, parent);
  32071. };
  32072. return InterpolateValueAction;
  32073. })(BABYLON.Action);
  32074. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32075. })(BABYLON || (BABYLON = {}));
  32076. var BABYLON;
  32077. (function (BABYLON) {
  32078. var SwitchBooleanAction = (function (_super) {
  32079. __extends(SwitchBooleanAction, _super);
  32080. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32081. _super.call(this, triggerOptions, condition);
  32082. this.propertyPath = propertyPath;
  32083. this._target = this._effectiveTarget = target;
  32084. }
  32085. SwitchBooleanAction.prototype._prepare = function () {
  32086. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32087. this._property = this._getProperty(this.propertyPath);
  32088. };
  32089. SwitchBooleanAction.prototype.execute = function () {
  32090. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32091. };
  32092. SwitchBooleanAction.prototype.serialize = function (parent) {
  32093. return _super.prototype._serialize.call(this, {
  32094. name: "SwitchBooleanAction",
  32095. properties: [
  32096. BABYLON.Action._GetTargetProperty(this._target),
  32097. { name: "propertyPath", value: this.propertyPath }
  32098. ]
  32099. }, parent);
  32100. };
  32101. return SwitchBooleanAction;
  32102. })(BABYLON.Action);
  32103. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32104. var SetStateAction = (function (_super) {
  32105. __extends(SetStateAction, _super);
  32106. function SetStateAction(triggerOptions, target, value, condition) {
  32107. _super.call(this, triggerOptions, condition);
  32108. this.value = value;
  32109. this._target = target;
  32110. }
  32111. SetStateAction.prototype.execute = function () {
  32112. this._target.state = this.value;
  32113. };
  32114. SetStateAction.prototype.serialize = function (parent) {
  32115. return _super.prototype._serialize.call(this, {
  32116. name: "SetStateAction",
  32117. properties: [
  32118. BABYLON.Action._GetTargetProperty(this._target),
  32119. { name: "value", value: this.value }
  32120. ]
  32121. }, parent);
  32122. };
  32123. return SetStateAction;
  32124. })(BABYLON.Action);
  32125. BABYLON.SetStateAction = SetStateAction;
  32126. var SetValueAction = (function (_super) {
  32127. __extends(SetValueAction, _super);
  32128. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32129. _super.call(this, triggerOptions, condition);
  32130. this.propertyPath = propertyPath;
  32131. this.value = value;
  32132. this._target = this._effectiveTarget = target;
  32133. }
  32134. SetValueAction.prototype._prepare = function () {
  32135. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32136. this._property = this._getProperty(this.propertyPath);
  32137. };
  32138. SetValueAction.prototype.execute = function () {
  32139. this._effectiveTarget[this._property] = this.value;
  32140. if (this._target.markAsDirty) {
  32141. this._target.markAsDirty(this._property);
  32142. }
  32143. };
  32144. SetValueAction.prototype.serialize = function (parent) {
  32145. return _super.prototype._serialize.call(this, {
  32146. name: "SetValueAction",
  32147. properties: [
  32148. BABYLON.Action._GetTargetProperty(this._target),
  32149. { name: "propertyPath", value: this.propertyPath },
  32150. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32151. ]
  32152. }, parent);
  32153. };
  32154. return SetValueAction;
  32155. })(BABYLON.Action);
  32156. BABYLON.SetValueAction = SetValueAction;
  32157. var IncrementValueAction = (function (_super) {
  32158. __extends(IncrementValueAction, _super);
  32159. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32160. _super.call(this, triggerOptions, condition);
  32161. this.propertyPath = propertyPath;
  32162. this.value = value;
  32163. this._target = this._effectiveTarget = target;
  32164. }
  32165. IncrementValueAction.prototype._prepare = function () {
  32166. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32167. this._property = this._getProperty(this.propertyPath);
  32168. if (typeof this._effectiveTarget[this._property] !== "number") {
  32169. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32170. }
  32171. };
  32172. IncrementValueAction.prototype.execute = function () {
  32173. this._effectiveTarget[this._property] += this.value;
  32174. if (this._target.markAsDirty) {
  32175. this._target.markAsDirty(this._property);
  32176. }
  32177. };
  32178. IncrementValueAction.prototype.serialize = function (parent) {
  32179. return _super.prototype._serialize.call(this, {
  32180. name: "IncrementValueAction",
  32181. properties: [
  32182. BABYLON.Action._GetTargetProperty(this._target),
  32183. { name: "propertyPath", value: this.propertyPath },
  32184. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32185. ]
  32186. }, parent);
  32187. };
  32188. return IncrementValueAction;
  32189. })(BABYLON.Action);
  32190. BABYLON.IncrementValueAction = IncrementValueAction;
  32191. var PlayAnimationAction = (function (_super) {
  32192. __extends(PlayAnimationAction, _super);
  32193. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32194. _super.call(this, triggerOptions, condition);
  32195. this.from = from;
  32196. this.to = to;
  32197. this.loop = loop;
  32198. this._target = target;
  32199. }
  32200. PlayAnimationAction.prototype._prepare = function () {
  32201. };
  32202. PlayAnimationAction.prototype.execute = function () {
  32203. var scene = this._actionManager.getScene();
  32204. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32205. };
  32206. PlayAnimationAction.prototype.serialize = function (parent) {
  32207. return _super.prototype._serialize.call(this, {
  32208. name: "PlayAnimationAction",
  32209. properties: [
  32210. BABYLON.Action._GetTargetProperty(this._target),
  32211. { name: "from", value: String(this.from) },
  32212. { name: "to", value: String(this.to) },
  32213. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32214. ]
  32215. }, parent);
  32216. };
  32217. return PlayAnimationAction;
  32218. })(BABYLON.Action);
  32219. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32220. var StopAnimationAction = (function (_super) {
  32221. __extends(StopAnimationAction, _super);
  32222. function StopAnimationAction(triggerOptions, target, condition) {
  32223. _super.call(this, triggerOptions, condition);
  32224. this._target = target;
  32225. }
  32226. StopAnimationAction.prototype._prepare = function () {
  32227. };
  32228. StopAnimationAction.prototype.execute = function () {
  32229. var scene = this._actionManager.getScene();
  32230. scene.stopAnimation(this._target);
  32231. };
  32232. StopAnimationAction.prototype.serialize = function (parent) {
  32233. return _super.prototype._serialize.call(this, {
  32234. name: "StopAnimationAction",
  32235. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32236. }, parent);
  32237. };
  32238. return StopAnimationAction;
  32239. })(BABYLON.Action);
  32240. BABYLON.StopAnimationAction = StopAnimationAction;
  32241. var DoNothingAction = (function (_super) {
  32242. __extends(DoNothingAction, _super);
  32243. function DoNothingAction(triggerOptions, condition) {
  32244. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32245. _super.call(this, triggerOptions, condition);
  32246. }
  32247. DoNothingAction.prototype.execute = function () {
  32248. };
  32249. DoNothingAction.prototype.serialize = function (parent) {
  32250. return _super.prototype._serialize.call(this, {
  32251. name: "DoNothingAction",
  32252. properties: []
  32253. }, parent);
  32254. };
  32255. return DoNothingAction;
  32256. })(BABYLON.Action);
  32257. BABYLON.DoNothingAction = DoNothingAction;
  32258. var CombineAction = (function (_super) {
  32259. __extends(CombineAction, _super);
  32260. function CombineAction(triggerOptions, children, condition) {
  32261. _super.call(this, triggerOptions, condition);
  32262. this.children = children;
  32263. }
  32264. CombineAction.prototype._prepare = function () {
  32265. for (var index = 0; index < this.children.length; index++) {
  32266. this.children[index]._actionManager = this._actionManager;
  32267. this.children[index]._prepare();
  32268. }
  32269. };
  32270. CombineAction.prototype.execute = function (evt) {
  32271. for (var index = 0; index < this.children.length; index++) {
  32272. this.children[index].execute(evt);
  32273. }
  32274. };
  32275. CombineAction.prototype.serialize = function (parent) {
  32276. var serializationObject = _super.prototype._serialize.call(this, {
  32277. name: "CombineAction",
  32278. properties: [],
  32279. combine: []
  32280. }, parent);
  32281. for (var i = 0; i < this.children.length; i++) {
  32282. serializationObject.combine.push(this.children[i].serialize(null));
  32283. }
  32284. return serializationObject;
  32285. };
  32286. return CombineAction;
  32287. })(BABYLON.Action);
  32288. BABYLON.CombineAction = CombineAction;
  32289. var ExecuteCodeAction = (function (_super) {
  32290. __extends(ExecuteCodeAction, _super);
  32291. function ExecuteCodeAction(triggerOptions, func, condition) {
  32292. _super.call(this, triggerOptions, condition);
  32293. this.func = func;
  32294. }
  32295. ExecuteCodeAction.prototype.execute = function (evt) {
  32296. this.func(evt);
  32297. };
  32298. return ExecuteCodeAction;
  32299. })(BABYLON.Action);
  32300. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32301. var SetParentAction = (function (_super) {
  32302. __extends(SetParentAction, _super);
  32303. function SetParentAction(triggerOptions, target, parent, condition) {
  32304. _super.call(this, triggerOptions, condition);
  32305. this._target = target;
  32306. this._parent = parent;
  32307. }
  32308. SetParentAction.prototype._prepare = function () {
  32309. };
  32310. SetParentAction.prototype.execute = function () {
  32311. if (this._target.parent === this._parent) {
  32312. return;
  32313. }
  32314. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32315. invertParentWorldMatrix.invert();
  32316. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32317. this._target.parent = this._parent;
  32318. };
  32319. SetParentAction.prototype.serialize = function (parent) {
  32320. return _super.prototype._serialize.call(this, {
  32321. name: "SetParentAction",
  32322. properties: [
  32323. BABYLON.Action._GetTargetProperty(this._target),
  32324. BABYLON.Action._GetTargetProperty(this._parent),
  32325. ]
  32326. }, parent);
  32327. };
  32328. return SetParentAction;
  32329. })(BABYLON.Action);
  32330. BABYLON.SetParentAction = SetParentAction;
  32331. var PlaySoundAction = (function (_super) {
  32332. __extends(PlaySoundAction, _super);
  32333. function PlaySoundAction(triggerOptions, sound, condition) {
  32334. _super.call(this, triggerOptions, condition);
  32335. this._sound = sound;
  32336. }
  32337. PlaySoundAction.prototype._prepare = function () {
  32338. };
  32339. PlaySoundAction.prototype.execute = function () {
  32340. if (this._sound !== undefined)
  32341. this._sound.play();
  32342. };
  32343. PlaySoundAction.prototype.serialize = function (parent) {
  32344. return _super.prototype._serialize.call(this, {
  32345. name: "PlaySoundAction",
  32346. properties: [{ name: "sound", value: this._sound.name }]
  32347. }, parent);
  32348. };
  32349. return PlaySoundAction;
  32350. })(BABYLON.Action);
  32351. BABYLON.PlaySoundAction = PlaySoundAction;
  32352. var StopSoundAction = (function (_super) {
  32353. __extends(StopSoundAction, _super);
  32354. function StopSoundAction(triggerOptions, sound, condition) {
  32355. _super.call(this, triggerOptions, condition);
  32356. this._sound = sound;
  32357. }
  32358. StopSoundAction.prototype._prepare = function () {
  32359. };
  32360. StopSoundAction.prototype.execute = function () {
  32361. if (this._sound !== undefined)
  32362. this._sound.stop();
  32363. };
  32364. StopSoundAction.prototype.serialize = function (parent) {
  32365. return _super.prototype._serialize.call(this, {
  32366. name: "StopSoundAction",
  32367. properties: [{ name: "sound", value: this._sound.name }]
  32368. }, parent);
  32369. };
  32370. return StopSoundAction;
  32371. })(BABYLON.Action);
  32372. BABYLON.StopSoundAction = StopSoundAction;
  32373. })(BABYLON || (BABYLON = {}));
  32374. var BABYLON;
  32375. (function (BABYLON) {
  32376. var Geometry = (function () {
  32377. function Geometry(id, scene, vertexData, updatable, mesh) {
  32378. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32379. this._totalVertices = 0;
  32380. this._isDisposed = false;
  32381. this.id = id;
  32382. this._engine = scene.getEngine();
  32383. this._meshes = [];
  32384. this._scene = scene;
  32385. //Init vertex buffer cache
  32386. this._vertexBuffers = {};
  32387. this._indices = [];
  32388. // vertexData
  32389. if (vertexData) {
  32390. this.setAllVerticesData(vertexData, updatable);
  32391. }
  32392. else {
  32393. this._totalVertices = 0;
  32394. this._indices = [];
  32395. }
  32396. // applyToMesh
  32397. if (mesh) {
  32398. if (mesh instanceof BABYLON.LinesMesh) {
  32399. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32400. this.updateExtend();
  32401. }
  32402. this.applyToMesh(mesh);
  32403. mesh.computeWorldMatrix(true);
  32404. }
  32405. }
  32406. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32407. /**
  32408. * 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
  32409. * @returns The Bias Vector
  32410. */
  32411. get: function () {
  32412. return this._boundingBias;
  32413. },
  32414. set: function (value) {
  32415. if (this._boundingBias && this._boundingBias.equals(value)) {
  32416. return;
  32417. }
  32418. this._boundingBias = value.clone();
  32419. this.updateBoundingInfo(true, null);
  32420. },
  32421. enumerable: true,
  32422. configurable: true
  32423. });
  32424. Object.defineProperty(Geometry.prototype, "extend", {
  32425. get: function () {
  32426. return this._extend;
  32427. },
  32428. enumerable: true,
  32429. configurable: true
  32430. });
  32431. Geometry.prototype.getScene = function () {
  32432. return this._scene;
  32433. };
  32434. Geometry.prototype.getEngine = function () {
  32435. return this._engine;
  32436. };
  32437. Geometry.prototype.isReady = function () {
  32438. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32439. };
  32440. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32441. vertexData.applyToGeometry(this, updatable);
  32442. this.notifyUpdate();
  32443. };
  32444. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32445. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32446. this.setVerticesBuffer(buffer);
  32447. };
  32448. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32449. var kind = buffer.getKind();
  32450. if (this._vertexBuffers[kind]) {
  32451. this._vertexBuffers[kind].dispose();
  32452. }
  32453. this._vertexBuffers[kind] = buffer;
  32454. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32455. var data = buffer.getData();
  32456. var stride = buffer.getStrideSize();
  32457. this._totalVertices = data.length / stride;
  32458. this.updateExtend(data, stride);
  32459. var meshes = this._meshes;
  32460. var numOfMeshes = meshes.length;
  32461. for (var index = 0; index < numOfMeshes; index++) {
  32462. var mesh = meshes[index];
  32463. mesh._resetPointsArrayCache();
  32464. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32465. mesh._createGlobalSubMesh();
  32466. mesh.computeWorldMatrix(true);
  32467. }
  32468. }
  32469. this.notifyUpdate(kind);
  32470. };
  32471. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32472. var vertexBuffer = this.getVertexBuffer(kind);
  32473. if (!vertexBuffer) {
  32474. return;
  32475. }
  32476. vertexBuffer.updateDirectly(data, offset);
  32477. this.notifyUpdate(kind);
  32478. };
  32479. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32480. var vertexBuffer = this.getVertexBuffer(kind);
  32481. if (!vertexBuffer) {
  32482. return;
  32483. }
  32484. vertexBuffer.update(data);
  32485. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32486. var stride = vertexBuffer.getStrideSize();
  32487. this._totalVertices = data.length / stride;
  32488. this.updateBoundingInfo(updateExtends, data);
  32489. }
  32490. this.notifyUpdate(kind);
  32491. };
  32492. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32493. if (updateExtends) {
  32494. this.updateExtend(data);
  32495. }
  32496. var meshes = this._meshes;
  32497. var numOfMeshes = meshes.length;
  32498. for (var index = 0; index < numOfMeshes; index++) {
  32499. var mesh = meshes[index];
  32500. mesh._resetPointsArrayCache();
  32501. if (updateExtends) {
  32502. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32503. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32504. var subMesh = mesh.subMeshes[subIndex];
  32505. subMesh.refreshBoundingInfo();
  32506. }
  32507. }
  32508. }
  32509. };
  32510. Geometry.prototype.getTotalVertices = function () {
  32511. if (!this.isReady()) {
  32512. return 0;
  32513. }
  32514. return this._totalVertices;
  32515. };
  32516. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  32517. var vertexBuffer = this.getVertexBuffer(kind);
  32518. if (!vertexBuffer) {
  32519. return null;
  32520. }
  32521. var orig = vertexBuffer.getData();
  32522. if (!copyWhenShared || this._meshes.length === 1) {
  32523. return orig;
  32524. }
  32525. else {
  32526. var len = orig.length;
  32527. var copy = [];
  32528. for (var i = 0; i < len; i++) {
  32529. copy.push(orig[i]);
  32530. }
  32531. return copy;
  32532. }
  32533. };
  32534. Geometry.prototype.getVertexBuffer = function (kind) {
  32535. if (!this.isReady()) {
  32536. return null;
  32537. }
  32538. return this._vertexBuffers[kind];
  32539. };
  32540. Geometry.prototype.getVertexBuffers = function () {
  32541. if (!this.isReady()) {
  32542. return null;
  32543. }
  32544. return this._vertexBuffers;
  32545. };
  32546. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32547. if (!this._vertexBuffers) {
  32548. if (this._delayInfo) {
  32549. return this._delayInfo.indexOf(kind) !== -1;
  32550. }
  32551. return false;
  32552. }
  32553. return this._vertexBuffers[kind] !== undefined;
  32554. };
  32555. Geometry.prototype.getVerticesDataKinds = function () {
  32556. var result = [];
  32557. var kind;
  32558. if (!this._vertexBuffers && this._delayInfo) {
  32559. for (kind in this._delayInfo) {
  32560. result.push(kind);
  32561. }
  32562. }
  32563. else {
  32564. for (kind in this._vertexBuffers) {
  32565. result.push(kind);
  32566. }
  32567. }
  32568. return result;
  32569. };
  32570. Geometry.prototype.setIndices = function (indices, totalVertices) {
  32571. if (this._indexBuffer) {
  32572. this._engine._releaseBuffer(this._indexBuffer);
  32573. }
  32574. this._indices = indices;
  32575. if (this._meshes.length !== 0 && this._indices) {
  32576. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32577. }
  32578. if (totalVertices !== undefined) {
  32579. this._totalVertices = totalVertices;
  32580. }
  32581. var meshes = this._meshes;
  32582. var numOfMeshes = meshes.length;
  32583. for (var index = 0; index < numOfMeshes; index++) {
  32584. meshes[index]._createGlobalSubMesh();
  32585. }
  32586. this.notifyUpdate();
  32587. };
  32588. Geometry.prototype.getTotalIndices = function () {
  32589. if (!this.isReady()) {
  32590. return 0;
  32591. }
  32592. return this._indices.length;
  32593. };
  32594. Geometry.prototype.getIndices = function (copyWhenShared) {
  32595. if (!this.isReady()) {
  32596. return null;
  32597. }
  32598. var orig = this._indices;
  32599. if (!copyWhenShared || this._meshes.length === 1) {
  32600. return orig;
  32601. }
  32602. else {
  32603. var len = orig.length;
  32604. var copy = [];
  32605. for (var i = 0; i < len; i++) {
  32606. copy.push(orig[i]);
  32607. }
  32608. return copy;
  32609. }
  32610. };
  32611. Geometry.prototype.getIndexBuffer = function () {
  32612. if (!this.isReady()) {
  32613. return null;
  32614. }
  32615. return this._indexBuffer;
  32616. };
  32617. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32618. var meshes = this._meshes;
  32619. var index = meshes.indexOf(mesh);
  32620. if (index === -1) {
  32621. return;
  32622. }
  32623. for (var kind in this._vertexBuffers) {
  32624. this._vertexBuffers[kind].dispose();
  32625. }
  32626. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  32627. this._indexBuffer = null;
  32628. }
  32629. meshes.splice(index, 1);
  32630. mesh._geometry = null;
  32631. if (meshes.length === 0 && shouldDispose) {
  32632. this.dispose();
  32633. }
  32634. };
  32635. Geometry.prototype.applyToMesh = function (mesh) {
  32636. if (mesh._geometry === this) {
  32637. return;
  32638. }
  32639. var previousGeometry = mesh._geometry;
  32640. if (previousGeometry) {
  32641. previousGeometry.releaseForMesh(mesh);
  32642. }
  32643. var meshes = this._meshes;
  32644. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32645. mesh._geometry = this;
  32646. this._scene.pushGeometry(this);
  32647. meshes.push(mesh);
  32648. if (this.isReady()) {
  32649. this._applyToMesh(mesh);
  32650. }
  32651. else {
  32652. mesh._boundingInfo = this._boundingInfo;
  32653. }
  32654. };
  32655. Geometry.prototype.updateExtend = function (data, stride) {
  32656. if (data === void 0) { data = null; }
  32657. if (!data) {
  32658. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32659. }
  32660. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32661. };
  32662. Geometry.prototype._applyToMesh = function (mesh) {
  32663. var numOfMeshes = this._meshes.length;
  32664. // vertexBuffers
  32665. for (var kind in this._vertexBuffers) {
  32666. if (numOfMeshes === 1) {
  32667. this._vertexBuffers[kind].create();
  32668. }
  32669. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  32670. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32671. mesh._resetPointsArrayCache();
  32672. if (!this._extend) {
  32673. this.updateExtend(this._vertexBuffers[kind].getData());
  32674. }
  32675. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32676. mesh._createGlobalSubMesh();
  32677. //bounding info was just created again, world matrix should be applied again.
  32678. mesh._updateBoundingInfo();
  32679. }
  32680. }
  32681. // indexBuffer
  32682. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32683. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32684. }
  32685. if (this._indexBuffer) {
  32686. this._indexBuffer.references = numOfMeshes;
  32687. }
  32688. };
  32689. Geometry.prototype.notifyUpdate = function (kind) {
  32690. if (this.onGeometryUpdated) {
  32691. this.onGeometryUpdated(this, kind);
  32692. }
  32693. };
  32694. Geometry.prototype.load = function (scene, onLoaded) {
  32695. var _this = this;
  32696. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32697. return;
  32698. }
  32699. if (this.isReady()) {
  32700. if (onLoaded) {
  32701. onLoaded();
  32702. }
  32703. return;
  32704. }
  32705. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32706. scene._addPendingData(this);
  32707. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32708. _this._delayLoadingFunction(JSON.parse(data), _this);
  32709. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32710. _this._delayInfo = [];
  32711. scene._removePendingData(_this);
  32712. var meshes = _this._meshes;
  32713. var numOfMeshes = meshes.length;
  32714. for (var index = 0; index < numOfMeshes; index++) {
  32715. _this._applyToMesh(meshes[index]);
  32716. }
  32717. if (onLoaded) {
  32718. onLoaded();
  32719. }
  32720. }, function () { }, scene.database);
  32721. };
  32722. /**
  32723. * Invert the geometry to move from a right handed system to a left handed one.
  32724. */
  32725. Geometry.prototype.toLeftHanded = function () {
  32726. // Flip faces
  32727. var tIndices = this.getIndices(false);
  32728. if (tIndices != null && tIndices.length > 0) {
  32729. for (var i = 0; i < tIndices.length; i += 3) {
  32730. var tTemp = tIndices[i + 0];
  32731. tIndices[i + 0] = tIndices[i + 2];
  32732. tIndices[i + 2] = tTemp;
  32733. }
  32734. this.setIndices(tIndices);
  32735. }
  32736. // Negate position.z
  32737. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32738. if (tPositions != null && tPositions.length > 0) {
  32739. for (var i = 0; i < tPositions.length; i += 3) {
  32740. tPositions[i + 2] = -tPositions[i + 2];
  32741. }
  32742. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32743. }
  32744. // Negate normal.z
  32745. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32746. if (tNormals != null && tNormals.length > 0) {
  32747. for (var i = 0; i < tNormals.length; i += 3) {
  32748. tNormals[i + 2] = -tNormals[i + 2];
  32749. }
  32750. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32751. }
  32752. };
  32753. Geometry.prototype.isDisposed = function () {
  32754. return this._isDisposed;
  32755. };
  32756. Geometry.prototype.dispose = function () {
  32757. var meshes = this._meshes;
  32758. var numOfMeshes = meshes.length;
  32759. var index;
  32760. for (index = 0; index < numOfMeshes; index++) {
  32761. this.releaseForMesh(meshes[index]);
  32762. }
  32763. this._meshes = [];
  32764. for (var kind in this._vertexBuffers) {
  32765. this._vertexBuffers[kind].dispose();
  32766. }
  32767. this._vertexBuffers = {};
  32768. this._totalVertices = 0;
  32769. if (this._indexBuffer) {
  32770. this._engine._releaseBuffer(this._indexBuffer);
  32771. }
  32772. this._indexBuffer = null;
  32773. this._indices = [];
  32774. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32775. this.delayLoadingFile = null;
  32776. this._delayLoadingFunction = null;
  32777. this._delayInfo = [];
  32778. this._boundingInfo = null;
  32779. this._scene.removeGeometry(this);
  32780. this._isDisposed = true;
  32781. };
  32782. Geometry.prototype.copy = function (id) {
  32783. var vertexData = new BABYLON.VertexData();
  32784. vertexData.indices = [];
  32785. var indices = this.getIndices();
  32786. for (var index = 0; index < indices.length; index++) {
  32787. vertexData.indices.push(indices[index]);
  32788. }
  32789. var updatable = false;
  32790. var stopChecking = false;
  32791. var kind;
  32792. for (kind in this._vertexBuffers) {
  32793. // using slice() to make a copy of the array and not just reference it
  32794. var data = this.getVerticesData(kind);
  32795. if (data instanceof Float32Array) {
  32796. vertexData.set(new Float32Array(data), kind);
  32797. }
  32798. else {
  32799. vertexData.set(data.slice(0), kind);
  32800. }
  32801. if (!stopChecking) {
  32802. updatable = this.getVertexBuffer(kind).isUpdatable();
  32803. stopChecking = !updatable;
  32804. }
  32805. }
  32806. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  32807. geometry.delayLoadState = this.delayLoadState;
  32808. geometry.delayLoadingFile = this.delayLoadingFile;
  32809. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32810. for (kind in this._delayInfo) {
  32811. geometry._delayInfo = geometry._delayInfo || [];
  32812. geometry._delayInfo.push(kind);
  32813. }
  32814. // Bounding info
  32815. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32816. return geometry;
  32817. };
  32818. Geometry.prototype.serialize = function () {
  32819. var serializationObject = {};
  32820. serializationObject.id = this.id;
  32821. if (BABYLON.Tags.HasTags(this)) {
  32822. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32823. }
  32824. return serializationObject;
  32825. };
  32826. Geometry.prototype.serializeVerticeData = function () {
  32827. var serializationObject = this.serialize();
  32828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32829. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32830. }
  32831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32832. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32833. }
  32834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32835. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32836. }
  32837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32838. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  32839. }
  32840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32841. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  32842. }
  32843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32844. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  32845. }
  32846. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32847. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  32848. }
  32849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32850. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  32851. }
  32852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32853. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32854. }
  32855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32856. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32857. serializationObject.matricesIndices._isExpanded = true;
  32858. }
  32859. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32860. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32861. }
  32862. serializationObject.indices = this.getIndices();
  32863. return serializationObject;
  32864. };
  32865. // Statics
  32866. Geometry.ExtractFromMesh = function (mesh, id) {
  32867. var geometry = mesh._geometry;
  32868. if (!geometry) {
  32869. return null;
  32870. }
  32871. return geometry.copy(id);
  32872. };
  32873. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32874. // be aware Math.random() could cause collisions
  32875. Geometry.RandomId = function () {
  32876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  32877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  32878. return v.toString(16);
  32879. });
  32880. };
  32881. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32882. var scene = mesh.getScene();
  32883. // Geometry
  32884. var geometryId = parsedGeometry.geometryId;
  32885. if (geometryId) {
  32886. var geometry = scene.getGeometryByID(geometryId);
  32887. if (geometry) {
  32888. geometry.applyToMesh(mesh);
  32889. }
  32890. }
  32891. else if (parsedGeometry instanceof ArrayBuffer) {
  32892. var binaryInfo = mesh._binaryInfo;
  32893. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32894. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32895. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32896. }
  32897. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32898. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32899. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32900. }
  32901. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32902. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32903. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32904. }
  32905. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32906. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32907. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32908. }
  32909. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32910. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32911. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32912. }
  32913. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32914. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32915. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32916. }
  32917. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32918. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32919. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32920. }
  32921. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32922. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32923. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32924. }
  32925. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32926. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32927. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32928. }
  32929. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32930. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32931. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32932. }
  32933. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32934. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32936. }
  32937. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32938. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32939. mesh.setIndices(indicesData);
  32940. }
  32941. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32942. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32943. mesh.subMeshes = [];
  32944. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32945. var materialIndex = subMeshesData[(i * 5) + 0];
  32946. var verticesStart = subMeshesData[(i * 5) + 1];
  32947. var verticesCount = subMeshesData[(i * 5) + 2];
  32948. var indexStart = subMeshesData[(i * 5) + 3];
  32949. var indexCount = subMeshesData[(i * 5) + 4];
  32950. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32951. }
  32952. }
  32953. }
  32954. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32955. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  32956. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  32957. if (parsedGeometry.uvs) {
  32958. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  32959. }
  32960. if (parsedGeometry.uvs2) {
  32961. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  32962. }
  32963. if (parsedGeometry.uvs3) {
  32964. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  32965. }
  32966. if (parsedGeometry.uvs4) {
  32967. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  32968. }
  32969. if (parsedGeometry.uvs5) {
  32970. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  32971. }
  32972. if (parsedGeometry.uvs6) {
  32973. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  32974. }
  32975. if (parsedGeometry.colors) {
  32976. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  32977. }
  32978. if (parsedGeometry.matricesIndices) {
  32979. if (!parsedGeometry.matricesIndices._isExpanded) {
  32980. var floatIndices = [];
  32981. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32982. var matricesIndex = parsedGeometry.matricesIndices[i];
  32983. floatIndices.push(matricesIndex & 0x000000FF);
  32984. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32985. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32986. floatIndices.push(matricesIndex >> 24);
  32987. }
  32988. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  32989. }
  32990. else {
  32991. delete parsedGeometry.matricesIndices._isExpanded;
  32992. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  32993. }
  32994. }
  32995. if (parsedGeometry.matricesIndicesExtra) {
  32996. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32997. var floatIndices = [];
  32998. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32999. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33000. floatIndices.push(matricesIndex & 0x000000FF);
  33001. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33002. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33003. floatIndices.push(matricesIndex >> 24);
  33004. }
  33005. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33006. }
  33007. else {
  33008. delete parsedGeometry.matricesIndices._isExpanded;
  33009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33010. }
  33011. }
  33012. if (parsedGeometry.matricesWeights) {
  33013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33014. }
  33015. if (parsedGeometry.matricesWeightsExtra) {
  33016. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33017. }
  33018. mesh.setIndices(parsedGeometry.indices);
  33019. }
  33020. // SubMeshes
  33021. if (parsedGeometry.subMeshes) {
  33022. mesh.subMeshes = [];
  33023. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33024. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33025. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33026. }
  33027. }
  33028. // Flat shading
  33029. if (mesh._shouldGenerateFlatShading) {
  33030. mesh.convertToFlatShadedMesh();
  33031. delete mesh._shouldGenerateFlatShading;
  33032. }
  33033. // Update
  33034. mesh.computeWorldMatrix(true);
  33035. // Octree
  33036. if (scene['_selectionOctree']) {
  33037. scene['_selectionOctree'].addMesh(mesh);
  33038. }
  33039. };
  33040. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33041. if (scene.getGeometryByID(parsedVertexData.id)) {
  33042. return null; // null since geometry could be something else than a box...
  33043. }
  33044. var geometry = new Geometry(parsedVertexData.id, scene);
  33045. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33046. if (parsedVertexData.delayLoadingFile) {
  33047. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33048. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33049. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33050. geometry._delayInfo = [];
  33051. if (parsedVertexData.hasUVs) {
  33052. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33053. }
  33054. if (parsedVertexData.hasUVs2) {
  33055. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33056. }
  33057. if (parsedVertexData.hasUVs3) {
  33058. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33059. }
  33060. if (parsedVertexData.hasUVs4) {
  33061. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33062. }
  33063. if (parsedVertexData.hasUVs5) {
  33064. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33065. }
  33066. if (parsedVertexData.hasUVs6) {
  33067. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33068. }
  33069. if (parsedVertexData.hasColors) {
  33070. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33071. }
  33072. if (parsedVertexData.hasMatricesIndices) {
  33073. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33074. }
  33075. if (parsedVertexData.hasMatricesWeights) {
  33076. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33077. }
  33078. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33079. }
  33080. else {
  33081. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33082. }
  33083. scene.pushGeometry(geometry, true);
  33084. return geometry;
  33085. };
  33086. return Geometry;
  33087. })();
  33088. BABYLON.Geometry = Geometry;
  33089. /////// Primitives //////////////////////////////////////////////
  33090. var Geometry;
  33091. (function (Geometry) {
  33092. var Primitives;
  33093. (function (Primitives) {
  33094. /// Abstract class
  33095. var _Primitive = (function (_super) {
  33096. __extends(_Primitive, _super);
  33097. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33098. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33099. this._canBeRegenerated = _canBeRegenerated;
  33100. this._beingRegenerated = true;
  33101. this.regenerate();
  33102. this._beingRegenerated = false;
  33103. }
  33104. _Primitive.prototype.canBeRegenerated = function () {
  33105. return this._canBeRegenerated;
  33106. };
  33107. _Primitive.prototype.regenerate = function () {
  33108. if (!this._canBeRegenerated) {
  33109. return;
  33110. }
  33111. this._beingRegenerated = true;
  33112. this.setAllVerticesData(this._regenerateVertexData(), false);
  33113. this._beingRegenerated = false;
  33114. };
  33115. _Primitive.prototype.asNewGeometry = function (id) {
  33116. return _super.prototype.copy.call(this, id);
  33117. };
  33118. // overrides
  33119. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33120. if (!this._beingRegenerated) {
  33121. return;
  33122. }
  33123. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33124. };
  33125. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33126. if (!this._beingRegenerated) {
  33127. return;
  33128. }
  33129. _super.prototype.setVerticesData.call(this, kind, data, false);
  33130. };
  33131. // to override
  33132. // protected
  33133. _Primitive.prototype._regenerateVertexData = function () {
  33134. throw new Error("Abstract method");
  33135. };
  33136. _Primitive.prototype.copy = function (id) {
  33137. throw new Error("Must be overriden in sub-classes.");
  33138. };
  33139. _Primitive.prototype.serialize = function () {
  33140. var serializationObject = _super.prototype.serialize.call(this);
  33141. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33142. return serializationObject;
  33143. };
  33144. return _Primitive;
  33145. })(Geometry);
  33146. Primitives._Primitive = _Primitive;
  33147. var Ribbon = (function (_super) {
  33148. __extends(Ribbon, _super);
  33149. // Members
  33150. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33151. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33152. _super.call(this, id, scene, canBeRegenerated, mesh);
  33153. this.pathArray = pathArray;
  33154. this.closeArray = closeArray;
  33155. this.closePath = closePath;
  33156. this.offset = offset;
  33157. this.side = side;
  33158. }
  33159. Ribbon.prototype._regenerateVertexData = function () {
  33160. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33161. };
  33162. Ribbon.prototype.copy = function (id) {
  33163. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33164. };
  33165. return Ribbon;
  33166. })(_Primitive);
  33167. Primitives.Ribbon = Ribbon;
  33168. var Box = (function (_super) {
  33169. __extends(Box, _super);
  33170. // Members
  33171. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33172. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33173. _super.call(this, id, scene, canBeRegenerated, mesh);
  33174. this.size = size;
  33175. this.side = side;
  33176. }
  33177. Box.prototype._regenerateVertexData = function () {
  33178. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33179. };
  33180. Box.prototype.copy = function (id) {
  33181. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33182. };
  33183. Box.prototype.serialize = function () {
  33184. var serializationObject = _super.prototype.serialize.call(this);
  33185. serializationObject.size = this.size;
  33186. return serializationObject;
  33187. };
  33188. Box.Parse = function (parsedBox, scene) {
  33189. if (scene.getGeometryByID(parsedBox.id)) {
  33190. return null; // null since geometry could be something else than a box...
  33191. }
  33192. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33193. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33194. scene.pushGeometry(box, true);
  33195. return box;
  33196. };
  33197. return Box;
  33198. })(_Primitive);
  33199. Primitives.Box = Box;
  33200. var Sphere = (function (_super) {
  33201. __extends(Sphere, _super);
  33202. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33204. _super.call(this, id, scene, canBeRegenerated, mesh);
  33205. this.segments = segments;
  33206. this.diameter = diameter;
  33207. this.side = side;
  33208. }
  33209. Sphere.prototype._regenerateVertexData = function () {
  33210. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33211. };
  33212. Sphere.prototype.copy = function (id) {
  33213. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33214. };
  33215. Sphere.prototype.serialize = function () {
  33216. var serializationObject = _super.prototype.serialize.call(this);
  33217. serializationObject.segments = this.segments;
  33218. serializationObject.diameter = this.diameter;
  33219. return serializationObject;
  33220. };
  33221. Sphere.Parse = function (parsedSphere, scene) {
  33222. if (scene.getGeometryByID(parsedSphere.id)) {
  33223. return null; // null since geometry could be something else than a sphere...
  33224. }
  33225. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33226. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33227. scene.pushGeometry(sphere, true);
  33228. return sphere;
  33229. };
  33230. return Sphere;
  33231. })(_Primitive);
  33232. Primitives.Sphere = Sphere;
  33233. var Disc = (function (_super) {
  33234. __extends(Disc, _super);
  33235. // Members
  33236. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33237. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33238. _super.call(this, id, scene, canBeRegenerated, mesh);
  33239. this.radius = radius;
  33240. this.tessellation = tessellation;
  33241. this.side = side;
  33242. }
  33243. Disc.prototype._regenerateVertexData = function () {
  33244. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33245. };
  33246. Disc.prototype.copy = function (id) {
  33247. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33248. };
  33249. return Disc;
  33250. })(_Primitive);
  33251. Primitives.Disc = Disc;
  33252. var Cylinder = (function (_super) {
  33253. __extends(Cylinder, _super);
  33254. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33255. if (subdivisions === void 0) { subdivisions = 1; }
  33256. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33257. _super.call(this, id, scene, canBeRegenerated, mesh);
  33258. this.height = height;
  33259. this.diameterTop = diameterTop;
  33260. this.diameterBottom = diameterBottom;
  33261. this.tessellation = tessellation;
  33262. this.subdivisions = subdivisions;
  33263. this.side = side;
  33264. }
  33265. Cylinder.prototype._regenerateVertexData = function () {
  33266. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33267. };
  33268. Cylinder.prototype.copy = function (id) {
  33269. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33270. };
  33271. Cylinder.prototype.serialize = function () {
  33272. var serializationObject = _super.prototype.serialize.call(this);
  33273. serializationObject.height = this.height;
  33274. serializationObject.diameterTop = this.diameterTop;
  33275. serializationObject.diameterBottom = this.diameterBottom;
  33276. serializationObject.tessellation = this.tessellation;
  33277. return serializationObject;
  33278. };
  33279. Cylinder.Parse = function (parsedCylinder, scene) {
  33280. if (scene.getGeometryByID(parsedCylinder.id)) {
  33281. return null; // null since geometry could be something else than a cylinder...
  33282. }
  33283. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33284. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33285. scene.pushGeometry(cylinder, true);
  33286. return cylinder;
  33287. };
  33288. return Cylinder;
  33289. })(_Primitive);
  33290. Primitives.Cylinder = Cylinder;
  33291. var Torus = (function (_super) {
  33292. __extends(Torus, _super);
  33293. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33294. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33295. _super.call(this, id, scene, canBeRegenerated, mesh);
  33296. this.diameter = diameter;
  33297. this.thickness = thickness;
  33298. this.tessellation = tessellation;
  33299. this.side = side;
  33300. }
  33301. Torus.prototype._regenerateVertexData = function () {
  33302. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33303. };
  33304. Torus.prototype.copy = function (id) {
  33305. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33306. };
  33307. Torus.prototype.serialize = function () {
  33308. var serializationObject = _super.prototype.serialize.call(this);
  33309. serializationObject.diameter = this.diameter;
  33310. serializationObject.thickness = this.thickness;
  33311. serializationObject.tessellation = this.tessellation;
  33312. return serializationObject;
  33313. };
  33314. Torus.Parse = function (parsedTorus, scene) {
  33315. if (scene.getGeometryByID(parsedTorus.id)) {
  33316. return null; // null since geometry could be something else than a torus...
  33317. }
  33318. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33319. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33320. scene.pushGeometry(torus, true);
  33321. return torus;
  33322. };
  33323. return Torus;
  33324. })(_Primitive);
  33325. Primitives.Torus = Torus;
  33326. var Ground = (function (_super) {
  33327. __extends(Ground, _super);
  33328. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33329. _super.call(this, id, scene, canBeRegenerated, mesh);
  33330. this.width = width;
  33331. this.height = height;
  33332. this.subdivisions = subdivisions;
  33333. }
  33334. Ground.prototype._regenerateVertexData = function () {
  33335. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33336. };
  33337. Ground.prototype.copy = function (id) {
  33338. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33339. };
  33340. Ground.prototype.serialize = function () {
  33341. var serializationObject = _super.prototype.serialize.call(this);
  33342. serializationObject.width = this.width;
  33343. serializationObject.height = this.height;
  33344. serializationObject.subdivisions = this.subdivisions;
  33345. return serializationObject;
  33346. };
  33347. Ground.Parse = function (parsedGround, scene) {
  33348. if (scene.getGeometryByID(parsedGround.id)) {
  33349. return null; // null since geometry could be something else than a ground...
  33350. }
  33351. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33352. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33353. scene.pushGeometry(ground, true);
  33354. return ground;
  33355. };
  33356. return Ground;
  33357. })(_Primitive);
  33358. Primitives.Ground = Ground;
  33359. var TiledGround = (function (_super) {
  33360. __extends(TiledGround, _super);
  33361. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  33362. _super.call(this, id, scene, canBeRegenerated, mesh);
  33363. this.xmin = xmin;
  33364. this.zmin = zmin;
  33365. this.xmax = xmax;
  33366. this.zmax = zmax;
  33367. this.subdivisions = subdivisions;
  33368. this.precision = precision;
  33369. }
  33370. TiledGround.prototype._regenerateVertexData = function () {
  33371. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33372. };
  33373. TiledGround.prototype.copy = function (id) {
  33374. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33375. };
  33376. return TiledGround;
  33377. })(_Primitive);
  33378. Primitives.TiledGround = TiledGround;
  33379. var Plane = (function (_super) {
  33380. __extends(Plane, _super);
  33381. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  33382. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33383. _super.call(this, id, scene, canBeRegenerated, mesh);
  33384. this.size = size;
  33385. this.side = side;
  33386. }
  33387. Plane.prototype._regenerateVertexData = function () {
  33388. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33389. };
  33390. Plane.prototype.copy = function (id) {
  33391. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33392. };
  33393. Plane.prototype.serialize = function () {
  33394. var serializationObject = _super.prototype.serialize.call(this);
  33395. serializationObject.size = this.size;
  33396. return serializationObject;
  33397. };
  33398. Plane.Parse = function (parsedPlane, scene) {
  33399. if (scene.getGeometryByID(parsedPlane.id)) {
  33400. return null; // null since geometry could be something else than a ground...
  33401. }
  33402. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33403. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33404. scene.pushGeometry(plane, true);
  33405. return plane;
  33406. };
  33407. return Plane;
  33408. })(_Primitive);
  33409. Primitives.Plane = Plane;
  33410. var TorusKnot = (function (_super) {
  33411. __extends(TorusKnot, _super);
  33412. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33413. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33414. _super.call(this, id, scene, canBeRegenerated, mesh);
  33415. this.radius = radius;
  33416. this.tube = tube;
  33417. this.radialSegments = radialSegments;
  33418. this.tubularSegments = tubularSegments;
  33419. this.p = p;
  33420. this.q = q;
  33421. this.side = side;
  33422. }
  33423. TorusKnot.prototype._regenerateVertexData = function () {
  33424. 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 });
  33425. };
  33426. TorusKnot.prototype.copy = function (id) {
  33427. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33428. };
  33429. TorusKnot.prototype.serialize = function () {
  33430. var serializationObject = _super.prototype.serialize.call(this);
  33431. serializationObject.radius = this.radius;
  33432. serializationObject.tube = this.tube;
  33433. serializationObject.radialSegments = this.radialSegments;
  33434. serializationObject.tubularSegments = this.tubularSegments;
  33435. serializationObject.p = this.p;
  33436. serializationObject.q = this.q;
  33437. return serializationObject;
  33438. };
  33439. ;
  33440. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33441. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33442. return null; // null since geometry could be something else than a ground...
  33443. }
  33444. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33445. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33446. scene.pushGeometry(torusKnot, true);
  33447. return torusKnot;
  33448. };
  33449. return TorusKnot;
  33450. })(_Primitive);
  33451. Primitives.TorusKnot = TorusKnot;
  33452. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33453. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33454. })(BABYLON || (BABYLON = {}));
  33455. var BABYLON;
  33456. (function (BABYLON) {
  33457. var GroundMesh = (function (_super) {
  33458. __extends(GroundMesh, _super);
  33459. function GroundMesh(name, scene) {
  33460. _super.call(this, name, scene);
  33461. this.generateOctree = false;
  33462. this._worldInverse = new BABYLON.Matrix();
  33463. }
  33464. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33465. get: function () {
  33466. return this._subdivisions;
  33467. },
  33468. enumerable: true,
  33469. configurable: true
  33470. });
  33471. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33472. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33473. this._subdivisions = chunksCount;
  33474. this.subdivide(this._subdivisions);
  33475. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33476. };
  33477. /**
  33478. * Returns a height (y) value in the Worl system :
  33479. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33480. * Returns the ground y position if (x, z) are outside the ground surface.
  33481. * Not pertinent if the ground is rotated.
  33482. */
  33483. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33484. // express x and y in the ground local system
  33485. x -= this.position.x;
  33486. z -= this.position.z;
  33487. x /= this.scaling.x;
  33488. z /= this.scaling.z;
  33489. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33490. return this.position.y;
  33491. }
  33492. if (!this._heightQuads || this._heightQuads.length == 0) {
  33493. this._initHeightQuads();
  33494. this._computeHeightQuads();
  33495. }
  33496. var facet = this._getFacetAt(x, z);
  33497. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33498. // return y in the World system
  33499. return y * this.scaling.y + this.position.y;
  33500. };
  33501. /**
  33502. * Returns a normalized vector (Vector3) orthogonal to the ground
  33503. * at the ground coordinates (x, z) expressed in the World system.
  33504. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  33505. * Not pertinent if the ground is rotated.
  33506. */
  33507. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33508. var normal = new BABYLON.Vector3(0, 1, 0);
  33509. this.getNormalAtCoordinatesToRef(x, z, normal);
  33510. return normal;
  33511. };
  33512. /**
  33513. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33514. * at the ground coordinates (x, z) expressed in the World system.
  33515. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33516. * Not pertinent if the ground is rotated.
  33517. */
  33518. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33519. // express x and y in the ground local system
  33520. x -= this.position.x;
  33521. z -= this.position.z;
  33522. x /= this.scaling.x;
  33523. z /= this.scaling.z;
  33524. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33525. return;
  33526. }
  33527. if (!this._heightQuads || this._heightQuads.length == 0) {
  33528. this._initHeightQuads();
  33529. this._computeHeightQuads();
  33530. }
  33531. var facet = this._getFacetAt(x, z);
  33532. ref.x = facet.x;
  33533. ref.y = facet.y;
  33534. ref.z = facet.z;
  33535. };
  33536. /**
  33537. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33538. * if the ground has been updated.
  33539. * This can be used in the render loop
  33540. */
  33541. GroundMesh.prototype.updateCoordinateHeights = function () {
  33542. if (!this._heightQuads || this._heightQuads.length == 0) {
  33543. this._initHeightQuads();
  33544. }
  33545. this._computeHeightQuads();
  33546. };
  33547. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33548. GroundMesh.prototype._getFacetAt = function (x, z) {
  33549. // retrieve col and row from x, z coordinates in the ground local system
  33550. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  33551. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  33552. var quad = this._heightQuads[row * this._subdivisions + col];
  33553. var facet;
  33554. if (z < quad.slope.x * x + quad.slope.y) {
  33555. facet = quad.facet1;
  33556. }
  33557. else {
  33558. facet = quad.facet2;
  33559. }
  33560. return facet;
  33561. };
  33562. // Creates and populates the heightMap array with "facet" elements :
  33563. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  33564. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33565. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33566. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33567. GroundMesh.prototype._initHeightQuads = function () {
  33568. this._heightQuads = new Array();
  33569. for (var row = 0; row < this._subdivisions; row++) {
  33570. for (var col = 0; col < this._subdivisions; col++) {
  33571. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  33572. this._heightQuads[row * this._subdivisions + col] = quad;
  33573. }
  33574. }
  33575. };
  33576. // Compute each quad element values and update the the heightMap array :
  33577. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33578. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33579. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33580. GroundMesh.prototype._computeHeightQuads = function () {
  33581. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33582. var v1 = BABYLON.Tmp.Vector3[0];
  33583. var v2 = BABYLON.Tmp.Vector3[1];
  33584. var v3 = BABYLON.Tmp.Vector3[2];
  33585. var v4 = BABYLON.Tmp.Vector3[3];
  33586. var v1v2 = BABYLON.Tmp.Vector3[4];
  33587. var v1v3 = BABYLON.Tmp.Vector3[5];
  33588. var v1v4 = BABYLON.Tmp.Vector3[6];
  33589. var norm1 = BABYLON.Tmp.Vector3[7];
  33590. var norm2 = BABYLON.Tmp.Vector3[8];
  33591. var i = 0;
  33592. var j = 0;
  33593. var k = 0;
  33594. var cd = 0; // 2D slope coefficient : z = cd * x + h
  33595. var h = 0;
  33596. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  33597. var d2 = 0;
  33598. for (var row = 0; row < this._subdivisions; row++) {
  33599. for (var col = 0; col < this._subdivisions; col++) {
  33600. i = col * 3;
  33601. j = row * (this._subdivisions + 1) * 3;
  33602. k = (row + 1) * (this._subdivisions + 1) * 3;
  33603. v1.x = positions[j + i];
  33604. v1.y = positions[j + i + 1];
  33605. v1.z = positions[j + i + 2];
  33606. v2.x = positions[j + i + 3];
  33607. v2.y = positions[j + i + 4];
  33608. v2.z = positions[j + i + 5];
  33609. v3.x = positions[k + i];
  33610. v3.y = positions[k + i + 1];
  33611. v3.z = positions[k + i + 2];
  33612. v4.x = positions[k + i + 3];
  33613. v4.y = positions[k + i + 4];
  33614. v4.z = positions[k + i + 5];
  33615. // 2D slope V1V4
  33616. cd = (v4.z - v1.z) / (v4.x - v1.x);
  33617. h = v1.z - cd * v1.x; // v1 belongs to the slope
  33618. // facet equations :
  33619. // we compute each facet normal vector
  33620. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  33621. // we compute the value d by applying the equation to v1 which belongs to the plane
  33622. // then we store the facet equation in a Vector4
  33623. v2.subtractToRef(v1, v1v2);
  33624. v3.subtractToRef(v1, v1v3);
  33625. v4.subtractToRef(v1, v1v4);
  33626. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  33627. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  33628. norm1.normalize();
  33629. norm2.normalize();
  33630. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  33631. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  33632. var quad = this._heightQuads[row * this._subdivisions + col];
  33633. quad.slope.copyFromFloats(cd, h);
  33634. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  33635. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  33636. }
  33637. }
  33638. };
  33639. return GroundMesh;
  33640. })(BABYLON.Mesh);
  33641. BABYLON.GroundMesh = GroundMesh;
  33642. })(BABYLON || (BABYLON = {}));
  33643. var BABYLON;
  33644. (function (BABYLON) {
  33645. var LinesMesh = (function (_super) {
  33646. __extends(LinesMesh, _super);
  33647. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  33648. if (parent === void 0) { parent = null; }
  33649. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  33650. this.color = new BABYLON.Color3(1, 1, 1);
  33651. this.alpha = 1;
  33652. this._positionBuffer = {};
  33653. if (source) {
  33654. this.color = source.color.clone();
  33655. this.alpha = source.alpha;
  33656. }
  33657. this._intersectionThreshold = 0.1;
  33658. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  33659. attributes: [BABYLON.VertexBuffer.PositionKind],
  33660. uniforms: ["worldViewProjection", "color"],
  33661. needAlphaBlending: true
  33662. });
  33663. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  33664. }
  33665. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  33666. /**
  33667. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33668. * This margin is expressed in world space coordinates, so its value may vary.
  33669. * Default value is 0.1
  33670. * @returns the intersection Threshold value.
  33671. */
  33672. get: function () {
  33673. return this._intersectionThreshold;
  33674. },
  33675. /**
  33676. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33677. * This margin is expressed in world space coordinates, so its value may vary.
  33678. * @param value the new threshold to apply
  33679. */
  33680. set: function (value) {
  33681. if (this._intersectionThreshold === value) {
  33682. return;
  33683. }
  33684. this._intersectionThreshold = value;
  33685. if (this.geometry) {
  33686. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  33687. }
  33688. },
  33689. enumerable: true,
  33690. configurable: true
  33691. });
  33692. Object.defineProperty(LinesMesh.prototype, "material", {
  33693. get: function () {
  33694. return this._colorShader;
  33695. },
  33696. enumerable: true,
  33697. configurable: true
  33698. });
  33699. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  33700. get: function () {
  33701. return false;
  33702. },
  33703. enumerable: true,
  33704. configurable: true
  33705. });
  33706. LinesMesh.prototype.createInstance = function (name) {
  33707. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  33708. return null;
  33709. };
  33710. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  33711. var engine = this.getScene().getEngine();
  33712. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  33713. // VBOs
  33714. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  33715. // Color
  33716. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  33717. };
  33718. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  33719. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  33720. return;
  33721. }
  33722. var engine = this.getScene().getEngine();
  33723. // Draw order
  33724. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  33725. };
  33726. LinesMesh.prototype.dispose = function (doNotRecurse) {
  33727. this._colorShader.dispose();
  33728. _super.prototype.dispose.call(this, doNotRecurse);
  33729. };
  33730. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  33731. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  33732. };
  33733. return LinesMesh;
  33734. })(BABYLON.Mesh);
  33735. BABYLON.LinesMesh = LinesMesh;
  33736. })(BABYLON || (BABYLON = {}));
  33737. var BABYLON;
  33738. (function (BABYLON) {
  33739. var DefaultLoadingScreen = (function () {
  33740. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33741. var _this = this;
  33742. if (_loadingText === void 0) { _loadingText = ""; }
  33743. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33744. this._renderingCanvas = _renderingCanvas;
  33745. this._loadingText = _loadingText;
  33746. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33747. // Resize
  33748. this._resizeLoadingUI = function () {
  33749. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33750. _this._loadingDiv.style.position = "absolute";
  33751. _this._loadingDiv.style.left = canvasRect.left + "px";
  33752. _this._loadingDiv.style.top = canvasRect.top + "px";
  33753. _this._loadingDiv.style.width = canvasRect.width + "px";
  33754. _this._loadingDiv.style.height = canvasRect.height + "px";
  33755. };
  33756. }
  33757. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33758. var _this = this;
  33759. if (this._loadingDiv) {
  33760. // Do not add a loading screen if there is already one
  33761. return;
  33762. }
  33763. this._loadingDiv = document.createElement("div");
  33764. this._loadingDiv.id = "babylonjsLoadingDiv";
  33765. this._loadingDiv.style.opacity = "0";
  33766. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33767. // Loading text
  33768. this._loadingTextDiv = document.createElement("div");
  33769. this._loadingTextDiv.style.position = "absolute";
  33770. this._loadingTextDiv.style.left = "0";
  33771. this._loadingTextDiv.style.top = "50%";
  33772. this._loadingTextDiv.style.marginTop = "80px";
  33773. this._loadingTextDiv.style.width = "100%";
  33774. this._loadingTextDiv.style.height = "20px";
  33775. this._loadingTextDiv.style.fontFamily = "Arial";
  33776. this._loadingTextDiv.style.fontSize = "14px";
  33777. this._loadingTextDiv.style.color = "white";
  33778. this._loadingTextDiv.style.textAlign = "center";
  33779. this._loadingTextDiv.innerHTML = "Loading";
  33780. this._loadingDiv.appendChild(this._loadingTextDiv);
  33781. //set the predefined text
  33782. this._loadingTextDiv.innerHTML = this._loadingText;
  33783. // Loading img
  33784. var imgBack = new Image();
  33785. 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==";
  33786. imgBack.style.position = "absolute";
  33787. imgBack.style.left = "50%";
  33788. imgBack.style.top = "50%";
  33789. imgBack.style.marginLeft = "-50px";
  33790. imgBack.style.marginTop = "-50px";
  33791. imgBack.style.transition = "transform 1.0s ease";
  33792. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33793. var deg = 360;
  33794. var onTransitionEnd = function () {
  33795. deg += 360;
  33796. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33797. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33798. };
  33799. imgBack.addEventListener("transitionend", onTransitionEnd);
  33800. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33801. this._loadingDiv.appendChild(imgBack);
  33802. // front image
  33803. var imgFront = new Image();
  33804. 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=";
  33805. imgFront.style.position = "absolute";
  33806. imgFront.style.left = "50%";
  33807. imgFront.style.top = "50%";
  33808. imgFront.style.marginLeft = "-50px";
  33809. imgFront.style.marginTop = "-50px";
  33810. this._loadingDiv.appendChild(imgFront);
  33811. this._resizeLoadingUI();
  33812. window.addEventListener("resize", this._resizeLoadingUI);
  33813. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33814. document.body.appendChild(this._loadingDiv);
  33815. setTimeout(function () {
  33816. _this._loadingDiv.style.opacity = "1";
  33817. imgBack.style.transform = "rotateZ(360deg)";
  33818. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33819. }, 0);
  33820. };
  33821. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33822. var _this = this;
  33823. if (!this._loadingDiv) {
  33824. return;
  33825. }
  33826. var onTransitionEnd = function () {
  33827. if (!_this._loadingDiv) {
  33828. return;
  33829. }
  33830. document.body.removeChild(_this._loadingDiv);
  33831. window.removeEventListener("resize", _this._resizeLoadingUI);
  33832. _this._loadingDiv = null;
  33833. };
  33834. this._loadingDiv.style.opacity = "0";
  33835. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33836. };
  33837. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33838. set: function (text) {
  33839. this._loadingText = text;
  33840. if (this._loadingTextDiv) {
  33841. this._loadingTextDiv.innerHTML = this._loadingText;
  33842. }
  33843. },
  33844. enumerable: true,
  33845. configurable: true
  33846. });
  33847. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33848. get: function () {
  33849. return this._loadingDivBackgroundColor;
  33850. },
  33851. set: function (color) {
  33852. this._loadingDivBackgroundColor = color;
  33853. if (!this._loadingDiv) {
  33854. return;
  33855. }
  33856. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33857. },
  33858. enumerable: true,
  33859. configurable: true
  33860. });
  33861. return DefaultLoadingScreen;
  33862. })();
  33863. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33864. })(BABYLON || (BABYLON = {}));
  33865. var BABYLON;
  33866. (function (BABYLON) {
  33867. var AudioEngine = (function () {
  33868. function AudioEngine() {
  33869. this._audioContext = null;
  33870. this._audioContextInitialized = false;
  33871. this.canUseWebAudio = false;
  33872. this.WarnedWebAudioUnsupported = false;
  33873. this.unlocked = false;
  33874. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33875. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33876. this.canUseWebAudio = true;
  33877. }
  33878. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33879. this._unlockiOSaudio();
  33880. }
  33881. else {
  33882. this.unlocked = true;
  33883. }
  33884. }
  33885. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33886. get: function () {
  33887. if (!this._audioContextInitialized) {
  33888. this._initializeAudioContext();
  33889. }
  33890. return this._audioContext;
  33891. },
  33892. enumerable: true,
  33893. configurable: true
  33894. });
  33895. AudioEngine.prototype._unlockiOSaudio = function () {
  33896. var _this = this;
  33897. var unlockaudio = function () {
  33898. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33899. var source = _this.audioContext.createBufferSource();
  33900. source.buffer = buffer;
  33901. source.connect(_this.audioContext.destination);
  33902. source.start(0);
  33903. setTimeout(function () {
  33904. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33905. _this.unlocked = true;
  33906. window.removeEventListener('touchend', unlockaudio, false);
  33907. if (_this.onAudioUnlocked) {
  33908. _this.onAudioUnlocked();
  33909. }
  33910. }
  33911. }, 0);
  33912. };
  33913. window.addEventListener('touchend', unlockaudio, false);
  33914. };
  33915. AudioEngine.prototype._initializeAudioContext = function () {
  33916. try {
  33917. if (this.canUseWebAudio) {
  33918. this._audioContext = new AudioContext();
  33919. // create a global volume gain node
  33920. this.masterGain = this._audioContext.createGain();
  33921. this.masterGain.gain.value = 1;
  33922. this.masterGain.connect(this._audioContext.destination);
  33923. this._audioContextInitialized = true;
  33924. }
  33925. }
  33926. catch (e) {
  33927. this.canUseWebAudio = false;
  33928. BABYLON.Tools.Error("Web Audio: " + e.message);
  33929. }
  33930. };
  33931. AudioEngine.prototype.dispose = function () {
  33932. if (this.canUseWebAudio && this._audioContextInitialized) {
  33933. if (this._connectedAnalyser) {
  33934. this._connectedAnalyser.stopDebugCanvas();
  33935. this._connectedAnalyser.dispose();
  33936. this.masterGain.disconnect();
  33937. this.masterGain.connect(this._audioContext.destination);
  33938. this._connectedAnalyser = null;
  33939. }
  33940. this.masterGain.gain.value = 1;
  33941. }
  33942. this.WarnedWebAudioUnsupported = false;
  33943. };
  33944. AudioEngine.prototype.getGlobalVolume = function () {
  33945. if (this.canUseWebAudio && this._audioContextInitialized) {
  33946. return this.masterGain.gain.value;
  33947. }
  33948. else {
  33949. return -1;
  33950. }
  33951. };
  33952. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33953. if (this.canUseWebAudio && this._audioContextInitialized) {
  33954. this.masterGain.gain.value = newVolume;
  33955. }
  33956. };
  33957. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33958. if (this._connectedAnalyser) {
  33959. this._connectedAnalyser.stopDebugCanvas();
  33960. }
  33961. if (this.canUseWebAudio && this._audioContextInitialized) {
  33962. this._connectedAnalyser = analyser;
  33963. this.masterGain.disconnect();
  33964. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33965. }
  33966. };
  33967. return AudioEngine;
  33968. })();
  33969. BABYLON.AudioEngine = AudioEngine;
  33970. })(BABYLON || (BABYLON = {}));
  33971. var BABYLON;
  33972. (function (BABYLON) {
  33973. var Sound = (function () {
  33974. /**
  33975. * Create a sound and attach it to a scene
  33976. * @param name Name of your sound
  33977. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33978. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33979. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33980. */
  33981. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33982. var _this = this;
  33983. this.autoplay = false;
  33984. this.loop = false;
  33985. this.useCustomAttenuation = false;
  33986. this.spatialSound = false;
  33987. this.refDistance = 1;
  33988. this.rolloffFactor = 1;
  33989. this.maxDistance = 100;
  33990. this.distanceModel = "linear";
  33991. this._panningModel = "equalpower";
  33992. this._playbackRate = 1;
  33993. this._streaming = false;
  33994. this._startTime = 0;
  33995. this._startOffset = 0;
  33996. this._position = BABYLON.Vector3.Zero();
  33997. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33998. this._volume = 1;
  33999. this._isLoaded = false;
  34000. this._isReadyToPlay = false;
  34001. this.isPlaying = false;
  34002. this.isPaused = false;
  34003. this._isDirectional = false;
  34004. // Used if you'd like to create a directional sound.
  34005. // If not set, the sound will be omnidirectional
  34006. this._coneInnerAngle = 360;
  34007. this._coneOuterAngle = 360;
  34008. this._coneOuterGain = 0;
  34009. this._isOutputConnected = false;
  34010. this.name = name;
  34011. this._scene = scene;
  34012. this._readyToPlayCallback = readyToPlayCallback;
  34013. // Default custom attenuation function is a linear attenuation
  34014. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34015. if (currentDistance < maxDistance) {
  34016. return currentVolume * (1 - currentDistance / maxDistance);
  34017. }
  34018. else {
  34019. return 0;
  34020. }
  34021. };
  34022. if (options) {
  34023. this.autoplay = options.autoplay || false;
  34024. this.loop = options.loop || false;
  34025. // if volume === 0, we need another way to check this option
  34026. if (options.volume !== undefined) {
  34027. this._volume = options.volume;
  34028. }
  34029. this.spatialSound = options.spatialSound || false;
  34030. this.maxDistance = options.maxDistance || 100;
  34031. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34032. this.rolloffFactor = options.rolloffFactor || 1;
  34033. this.refDistance = options.refDistance || 1;
  34034. this.distanceModel = options.distanceModel || "linear";
  34035. this._playbackRate = options.playbackRate || 1;
  34036. this._streaming = options.streaming || false;
  34037. }
  34038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34039. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34040. this._soundGain.gain.value = this._volume;
  34041. this._inputAudioNode = this._soundGain;
  34042. this._ouputAudioNode = this._soundGain;
  34043. if (this.spatialSound) {
  34044. this._createSpatialParameters();
  34045. }
  34046. this._scene.mainSoundTrack.AddSound(this);
  34047. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34048. if (urlOrArrayBuffer) {
  34049. // If it's an URL
  34050. if (typeof (urlOrArrayBuffer) === "string") {
  34051. // Loading sound using XHR2
  34052. if (!this._streaming) {
  34053. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34054. }
  34055. else {
  34056. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34057. this._htmlAudioElement.controls = false;
  34058. this._htmlAudioElement.loop = this.loop;
  34059. this._htmlAudioElement.crossOrigin = "anonymous";
  34060. this._htmlAudioElement.preload = "auto";
  34061. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34062. _this._isReadyToPlay = true;
  34063. if (_this.autoplay) {
  34064. _this.play();
  34065. }
  34066. if (_this._readyToPlayCallback) {
  34067. _this._readyToPlayCallback();
  34068. }
  34069. });
  34070. document.body.appendChild(this._htmlAudioElement);
  34071. }
  34072. }
  34073. else {
  34074. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34075. if (urlOrArrayBuffer.byteLength > 0) {
  34076. this._soundLoaded(urlOrArrayBuffer);
  34077. }
  34078. }
  34079. else {
  34080. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34081. }
  34082. }
  34083. }
  34084. }
  34085. else {
  34086. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34087. this._scene.mainSoundTrack.AddSound(this);
  34088. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34089. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34090. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34091. }
  34092. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34093. if (this._readyToPlayCallback) {
  34094. window.setTimeout(function () {
  34095. _this._readyToPlayCallback();
  34096. }, 1000);
  34097. }
  34098. }
  34099. }
  34100. Sound.prototype.dispose = function () {
  34101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34102. if (this.isPlaying) {
  34103. this.stop();
  34104. }
  34105. this._isReadyToPlay = false;
  34106. if (this.soundTrackId === -1) {
  34107. this._scene.mainSoundTrack.RemoveSound(this);
  34108. }
  34109. else {
  34110. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34111. }
  34112. if (this._soundGain) {
  34113. this._soundGain.disconnect();
  34114. this._soundGain = null;
  34115. }
  34116. if (this._soundPanner) {
  34117. this._soundPanner.disconnect();
  34118. this._soundPanner = null;
  34119. }
  34120. if (this._soundSource) {
  34121. this._soundSource.disconnect();
  34122. this._soundSource = null;
  34123. }
  34124. this._audioBuffer = null;
  34125. if (this._htmlAudioElement) {
  34126. this._htmlAudioElement.pause();
  34127. this._htmlAudioElement.src = "";
  34128. document.body.removeChild(this._htmlAudioElement);
  34129. }
  34130. if (this._connectedMesh) {
  34131. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34132. this._connectedMesh = null;
  34133. }
  34134. }
  34135. };
  34136. Sound.prototype._soundLoaded = function (audioData) {
  34137. var _this = this;
  34138. this._isLoaded = true;
  34139. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34140. _this._audioBuffer = buffer;
  34141. _this._isReadyToPlay = true;
  34142. if (_this.autoplay) {
  34143. _this.play();
  34144. }
  34145. if (_this._readyToPlayCallback) {
  34146. _this._readyToPlayCallback();
  34147. }
  34148. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34149. };
  34150. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34152. this._audioBuffer = audioBuffer;
  34153. this._isReadyToPlay = true;
  34154. }
  34155. };
  34156. Sound.prototype.updateOptions = function (options) {
  34157. if (options) {
  34158. this.loop = options.loop || this.loop;
  34159. this.maxDistance = options.maxDistance || this.maxDistance;
  34160. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34161. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34162. this.refDistance = options.refDistance || this.refDistance;
  34163. this.distanceModel = options.distanceModel || this.distanceModel;
  34164. this._playbackRate = options.playbackRate || this._playbackRate;
  34165. this._updateSpatialParameters();
  34166. if (this.isPlaying) {
  34167. if (this._streaming) {
  34168. this._htmlAudioElement.playbackRate = this._playbackRate;
  34169. }
  34170. else {
  34171. this._soundSource.playbackRate.value = this._playbackRate;
  34172. }
  34173. }
  34174. }
  34175. };
  34176. Sound.prototype._createSpatialParameters = function () {
  34177. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34178. if (this._scene.headphone) {
  34179. this._panningModel = "HRTF";
  34180. }
  34181. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34182. this._updateSpatialParameters();
  34183. this._soundPanner.connect(this._ouputAudioNode);
  34184. this._inputAudioNode = this._soundPanner;
  34185. }
  34186. };
  34187. Sound.prototype._updateSpatialParameters = function () {
  34188. if (this.spatialSound) {
  34189. if (this.useCustomAttenuation) {
  34190. // Tricks to disable in a way embedded Web Audio attenuation
  34191. this._soundPanner.distanceModel = "linear";
  34192. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34193. this._soundPanner.refDistance = 1;
  34194. this._soundPanner.rolloffFactor = 1;
  34195. this._soundPanner.panningModel = this._panningModel;
  34196. }
  34197. else {
  34198. this._soundPanner.distanceModel = this.distanceModel;
  34199. this._soundPanner.maxDistance = this.maxDistance;
  34200. this._soundPanner.refDistance = this.refDistance;
  34201. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34202. this._soundPanner.panningModel = this._panningModel;
  34203. }
  34204. }
  34205. };
  34206. Sound.prototype.switchPanningModelToHRTF = function () {
  34207. this._panningModel = "HRTF";
  34208. this._switchPanningModel();
  34209. };
  34210. Sound.prototype.switchPanningModelToEqualPower = function () {
  34211. this._panningModel = "equalpower";
  34212. this._switchPanningModel();
  34213. };
  34214. Sound.prototype._switchPanningModel = function () {
  34215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34216. this._soundPanner.panningModel = this._panningModel;
  34217. }
  34218. };
  34219. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34220. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34221. if (this._isOutputConnected) {
  34222. this._ouputAudioNode.disconnect();
  34223. }
  34224. this._ouputAudioNode.connect(soundTrackAudioNode);
  34225. this._isOutputConnected = true;
  34226. }
  34227. };
  34228. /**
  34229. * Transform this sound into a directional source
  34230. * @param coneInnerAngle Size of the inner cone in degree
  34231. * @param coneOuterAngle Size of the outer cone in degree
  34232. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34233. */
  34234. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34235. if (coneOuterAngle < coneInnerAngle) {
  34236. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34237. return;
  34238. }
  34239. this._coneInnerAngle = coneInnerAngle;
  34240. this._coneOuterAngle = coneOuterAngle;
  34241. this._coneOuterGain = coneOuterGain;
  34242. this._isDirectional = true;
  34243. if (this.isPlaying && this.loop) {
  34244. this.stop();
  34245. this.play();
  34246. }
  34247. };
  34248. Sound.prototype.setPosition = function (newPosition) {
  34249. this._position = newPosition;
  34250. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34251. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34252. }
  34253. };
  34254. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34255. this._localDirection = newLocalDirection;
  34256. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34257. this._updateDirection();
  34258. }
  34259. };
  34260. Sound.prototype._updateDirection = function () {
  34261. var mat = this._connectedMesh.getWorldMatrix();
  34262. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34263. direction.normalize();
  34264. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34265. };
  34266. Sound.prototype.updateDistanceFromListener = function () {
  34267. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34268. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34269. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34270. }
  34271. };
  34272. Sound.prototype.setAttenuationFunction = function (callback) {
  34273. this._customAttenuationFunction = callback;
  34274. };
  34275. /**
  34276. * Play the sound
  34277. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34278. */
  34279. Sound.prototype.play = function (time) {
  34280. var _this = this;
  34281. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34282. try {
  34283. if (this._startOffset < 0) {
  34284. time = -this._startOffset;
  34285. this._startOffset = 0;
  34286. }
  34287. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34288. if (!this._soundSource || !this._streamingSource) {
  34289. if (this.spatialSound) {
  34290. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34291. if (this._isDirectional) {
  34292. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34293. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34294. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34295. if (this._connectedMesh) {
  34296. this._updateDirection();
  34297. }
  34298. else {
  34299. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34300. }
  34301. }
  34302. }
  34303. }
  34304. if (this._streaming) {
  34305. if (!this._streamingSource) {
  34306. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34307. this._htmlAudioElement.onended = function () { _this._onended(); };
  34308. this._htmlAudioElement.playbackRate = this._playbackRate;
  34309. }
  34310. this._streamingSource.disconnect();
  34311. this._streamingSource.connect(this._inputAudioNode);
  34312. this._htmlAudioElement.play();
  34313. }
  34314. else {
  34315. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34316. this._soundSource.buffer = this._audioBuffer;
  34317. this._soundSource.connect(this._inputAudioNode);
  34318. this._soundSource.loop = this.loop;
  34319. this._soundSource.playbackRate.value = this._playbackRate;
  34320. this._soundSource.onended = function () { _this._onended(); };
  34321. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34322. }
  34323. this._startTime = startTime;
  34324. this.isPlaying = true;
  34325. this.isPaused = false;
  34326. }
  34327. catch (ex) {
  34328. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34329. }
  34330. }
  34331. };
  34332. Sound.prototype._onended = function () {
  34333. this.isPlaying = false;
  34334. if (this.onended) {
  34335. this.onended();
  34336. }
  34337. };
  34338. /**
  34339. * Stop the sound
  34340. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34341. */
  34342. Sound.prototype.stop = function (time) {
  34343. if (this.isPlaying) {
  34344. if (this._streaming) {
  34345. this._htmlAudioElement.pause();
  34346. // Test needed for Firefox or it will generate an Invalid State Error
  34347. if (this._htmlAudioElement.currentTime > 0) {
  34348. this._htmlAudioElement.currentTime = 0;
  34349. }
  34350. }
  34351. else {
  34352. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34353. this._soundSource.stop(stopTime);
  34354. this._soundSource.onended = null;
  34355. if (!this.isPaused) {
  34356. this._startOffset = 0;
  34357. }
  34358. }
  34359. this.isPlaying = false;
  34360. }
  34361. };
  34362. Sound.prototype.pause = function () {
  34363. if (this.isPlaying) {
  34364. this.isPaused = true;
  34365. if (this._streaming) {
  34366. this._htmlAudioElement.pause();
  34367. }
  34368. else {
  34369. this.stop(0);
  34370. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34371. }
  34372. }
  34373. };
  34374. Sound.prototype.setVolume = function (newVolume, time) {
  34375. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34376. if (time) {
  34377. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34378. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34379. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34380. }
  34381. else {
  34382. this._soundGain.gain.value = newVolume;
  34383. }
  34384. }
  34385. this._volume = newVolume;
  34386. };
  34387. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34388. this._playbackRate = newPlaybackRate;
  34389. if (this.isPlaying) {
  34390. if (this._streaming) {
  34391. this._htmlAudioElement.playbackRate = this._playbackRate;
  34392. }
  34393. else {
  34394. this._soundSource.playbackRate.value = this._playbackRate;
  34395. }
  34396. }
  34397. };
  34398. Sound.prototype.getVolume = function () {
  34399. return this._volume;
  34400. };
  34401. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34402. var _this = this;
  34403. if (this._connectedMesh) {
  34404. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34405. this._registerFunc = null;
  34406. }
  34407. this._connectedMesh = meshToConnectTo;
  34408. if (!this.spatialSound) {
  34409. this.spatialSound = true;
  34410. this._createSpatialParameters();
  34411. if (this.isPlaying && this.loop) {
  34412. this.stop();
  34413. this.play();
  34414. }
  34415. }
  34416. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34417. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34418. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34419. };
  34420. Sound.prototype.detachFromMesh = function () {
  34421. if (this._connectedMesh) {
  34422. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34423. this._registerFunc = null;
  34424. this._connectedMesh = null;
  34425. }
  34426. };
  34427. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34428. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34429. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34430. this._updateDirection();
  34431. }
  34432. };
  34433. Sound.prototype.clone = function () {
  34434. var _this = this;
  34435. if (!this._streaming) {
  34436. var setBufferAndRun = function () {
  34437. if (_this._isReadyToPlay) {
  34438. clonedSound._audioBuffer = _this.getAudioBuffer();
  34439. clonedSound._isReadyToPlay = true;
  34440. if (clonedSound.autoplay) {
  34441. clonedSound.play();
  34442. }
  34443. }
  34444. else {
  34445. window.setTimeout(setBufferAndRun, 300);
  34446. }
  34447. };
  34448. var currentOptions = {
  34449. autoplay: this.autoplay, loop: this.loop,
  34450. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34451. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34452. refDistance: this.refDistance, distanceModel: this.distanceModel
  34453. };
  34454. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34455. if (this.useCustomAttenuation) {
  34456. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34457. }
  34458. clonedSound.setPosition(this._position);
  34459. clonedSound.setPlaybackRate(this._playbackRate);
  34460. setBufferAndRun();
  34461. return clonedSound;
  34462. }
  34463. else {
  34464. return null;
  34465. }
  34466. };
  34467. Sound.prototype.getAudioBuffer = function () {
  34468. return this._audioBuffer;
  34469. };
  34470. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34471. var soundName = parsedSound.name;
  34472. var soundUrl;
  34473. if (parsedSound.url) {
  34474. soundUrl = rootUrl + parsedSound.url;
  34475. }
  34476. else {
  34477. soundUrl = rootUrl + soundName;
  34478. }
  34479. var options = {
  34480. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34481. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34482. rolloffFactor: parsedSound.rolloffFactor,
  34483. refDistance: parsedSound.refDistance,
  34484. distanceModel: parsedSound.distanceModel,
  34485. playbackRate: parsedSound.playbackRate
  34486. };
  34487. var newSound;
  34488. if (!sourceSound) {
  34489. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34490. scene._addPendingData(newSound);
  34491. }
  34492. else {
  34493. var setBufferAndRun = function () {
  34494. if (sourceSound._isReadyToPlay) {
  34495. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34496. newSound._isReadyToPlay = true;
  34497. if (newSound.autoplay) {
  34498. newSound.play();
  34499. }
  34500. }
  34501. else {
  34502. window.setTimeout(setBufferAndRun, 300);
  34503. }
  34504. };
  34505. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34506. setBufferAndRun();
  34507. }
  34508. if (parsedSound.position) {
  34509. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34510. newSound.setPosition(soundPosition);
  34511. }
  34512. if (parsedSound.isDirectional) {
  34513. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34514. if (parsedSound.localDirectionToMesh) {
  34515. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34516. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34517. }
  34518. }
  34519. if (parsedSound.connectedMeshId) {
  34520. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34521. if (connectedMesh) {
  34522. newSound.attachToMesh(connectedMesh);
  34523. }
  34524. }
  34525. return newSound;
  34526. };
  34527. return Sound;
  34528. })();
  34529. BABYLON.Sound = Sound;
  34530. })(BABYLON || (BABYLON = {}));
  34531. var BABYLON;
  34532. (function (BABYLON) {
  34533. var SoundTrack = (function () {
  34534. function SoundTrack(scene, options) {
  34535. this.id = -1;
  34536. this._isMainTrack = false;
  34537. this._isInitialized = false;
  34538. this._scene = scene;
  34539. this.soundCollection = new Array();
  34540. this._options = options;
  34541. if (!this._isMainTrack) {
  34542. this._scene.soundTracks.push(this);
  34543. this.id = this._scene.soundTracks.length - 1;
  34544. }
  34545. }
  34546. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34547. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34548. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34549. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34550. if (this._options) {
  34551. if (this._options.volume) {
  34552. this._outputAudioNode.gain.value = this._options.volume;
  34553. }
  34554. if (this._options.mainTrack) {
  34555. this._isMainTrack = this._options.mainTrack;
  34556. }
  34557. }
  34558. this._isInitialized = true;
  34559. }
  34560. };
  34561. SoundTrack.prototype.dispose = function () {
  34562. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34563. if (this._connectedAnalyser) {
  34564. this._connectedAnalyser.stopDebugCanvas();
  34565. }
  34566. while (this.soundCollection.length) {
  34567. this.soundCollection[0].dispose();
  34568. }
  34569. if (this._outputAudioNode) {
  34570. this._outputAudioNode.disconnect();
  34571. }
  34572. this._outputAudioNode = null;
  34573. }
  34574. };
  34575. SoundTrack.prototype.AddSound = function (sound) {
  34576. if (!this._isInitialized) {
  34577. this._initializeSoundTrackAudioGraph();
  34578. }
  34579. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34580. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34581. }
  34582. if (sound.soundTrackId) {
  34583. if (sound.soundTrackId === -1) {
  34584. this._scene.mainSoundTrack.RemoveSound(sound);
  34585. }
  34586. else {
  34587. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34588. }
  34589. }
  34590. this.soundCollection.push(sound);
  34591. sound.soundTrackId = this.id;
  34592. };
  34593. SoundTrack.prototype.RemoveSound = function (sound) {
  34594. var index = this.soundCollection.indexOf(sound);
  34595. if (index !== -1) {
  34596. this.soundCollection.splice(index, 1);
  34597. }
  34598. };
  34599. SoundTrack.prototype.setVolume = function (newVolume) {
  34600. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34601. this._outputAudioNode.gain.value = newVolume;
  34602. }
  34603. };
  34604. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34605. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34606. for (var i = 0; i < this.soundCollection.length; i++) {
  34607. this.soundCollection[i].switchPanningModelToHRTF();
  34608. }
  34609. }
  34610. };
  34611. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34612. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34613. for (var i = 0; i < this.soundCollection.length; i++) {
  34614. this.soundCollection[i].switchPanningModelToEqualPower();
  34615. }
  34616. }
  34617. };
  34618. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34619. if (this._connectedAnalyser) {
  34620. this._connectedAnalyser.stopDebugCanvas();
  34621. }
  34622. this._connectedAnalyser = analyser;
  34623. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34624. this._outputAudioNode.disconnect();
  34625. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34626. }
  34627. };
  34628. return SoundTrack;
  34629. })();
  34630. BABYLON.SoundTrack = SoundTrack;
  34631. })(BABYLON || (BABYLON = {}));
  34632. var BABYLON;
  34633. (function (BABYLON) {
  34634. var SIMDVector3 = (function () {
  34635. function SIMDVector3() {
  34636. }
  34637. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34638. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34639. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34640. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34641. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34642. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34643. 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));
  34644. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34645. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34646. };
  34647. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34648. var v0 = SIMD.float32x4.splat(x);
  34649. var v1 = SIMD.float32x4.splat(y);
  34650. var v2 = SIMD.float32x4.splat(z);
  34651. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34652. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34653. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34654. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34655. 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));
  34656. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34657. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34658. };
  34659. return SIMDVector3;
  34660. })();
  34661. BABYLON.SIMDVector3 = SIMDVector3;
  34662. var SIMDMatrix = (function () {
  34663. function SIMDMatrix() {
  34664. }
  34665. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34666. if (offset === void 0) { offset = 0; }
  34667. var tm = this.m;
  34668. var om = other.m;
  34669. var om0 = SIMD.float32x4.load(om, 0);
  34670. var om1 = SIMD.float32x4.load(om, 4);
  34671. var om2 = SIMD.float32x4.load(om, 8);
  34672. var om3 = SIMD.float32x4.load(om, 12);
  34673. var tm0 = SIMD.float32x4.load(tm, 0);
  34674. 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)))));
  34675. var tm1 = SIMD.float32x4.load(tm, 4);
  34676. 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)))));
  34677. var tm2 = SIMD.float32x4.load(tm, 8);
  34678. 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)))));
  34679. var tm3 = SIMD.float32x4.load(tm, 12);
  34680. 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)))));
  34681. };
  34682. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34683. var src = this.m;
  34684. var dest = other.m;
  34685. var row0, row1, row2, row3;
  34686. var tmp1;
  34687. var minor0, minor1, minor2, minor3;
  34688. var det;
  34689. // Load the 4 rows
  34690. var src0 = SIMD.float32x4.load(src, 0);
  34691. var src1 = SIMD.float32x4.load(src, 4);
  34692. var src2 = SIMD.float32x4.load(src, 8);
  34693. var src3 = SIMD.float32x4.load(src, 12);
  34694. // Transpose the source matrix. Sort of. Not a true transpose operation
  34695. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34696. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34697. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34698. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34699. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34700. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34701. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34702. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34703. // This is a true transposition, but it will lead to an incorrect result
  34704. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34705. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34706. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34707. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34708. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34709. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34710. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34711. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34712. // ----
  34713. tmp1 = SIMD.float32x4.mul(row2, row3);
  34714. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34715. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34716. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34717. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34718. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34719. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34720. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34721. // ----
  34722. tmp1 = SIMD.float32x4.mul(row1, row2);
  34723. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34724. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34725. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34726. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34727. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34728. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34729. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34730. // ----
  34731. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34732. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34733. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34734. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34735. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34736. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34737. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34738. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34739. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34740. // ----
  34741. tmp1 = SIMD.float32x4.mul(row0, row1);
  34742. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34743. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34744. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34745. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34746. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34747. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34748. // ----
  34749. tmp1 = SIMD.float32x4.mul(row0, row3);
  34750. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34751. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34752. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34753. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34754. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34755. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34756. // ----
  34757. tmp1 = SIMD.float32x4.mul(row0, row2);
  34758. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34759. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34760. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34761. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34762. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34763. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34764. // Compute determinant
  34765. det = SIMD.float32x4.mul(row0, minor0);
  34766. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34767. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34768. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34769. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34770. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34771. // These shuffles aren't necessary if the faulty transposition is done
  34772. // up at the top of this function.
  34773. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34774. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34775. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34776. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34777. // Compute final values by multiplying with 1/det
  34778. minor0 = SIMD.float32x4.mul(det, minor0);
  34779. minor1 = SIMD.float32x4.mul(det, minor1);
  34780. minor2 = SIMD.float32x4.mul(det, minor2);
  34781. minor3 = SIMD.float32x4.mul(det, minor3);
  34782. SIMD.float32x4.store(dest, 0, minor0);
  34783. SIMD.float32x4.store(dest, 4, minor1);
  34784. SIMD.float32x4.store(dest, 8, minor2);
  34785. SIMD.float32x4.store(dest, 12, minor3);
  34786. return this;
  34787. };
  34788. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34789. var out = result.m;
  34790. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34791. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34792. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34793. // cc.kmVec3Subtract(f, pCenter, pEye);
  34794. var f = SIMD.float32x4.sub(center, eye);
  34795. // cc.kmVec3Normalize(f, f);
  34796. var tmp = SIMD.float32x4.mul(f, f);
  34797. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34798. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34799. // cc.kmVec3Assign(up, pUp);
  34800. // cc.kmVec3Normalize(up, up);
  34801. tmp = SIMD.float32x4.mul(up, up);
  34802. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34803. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34804. // cc.kmVec3Cross(s, f, up);
  34805. 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)));
  34806. // cc.kmVec3Normalize(s, s);
  34807. tmp = SIMD.float32x4.mul(s, s);
  34808. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34809. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34810. // cc.kmVec3Cross(u, s, f);
  34811. 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)));
  34812. // cc.kmVec3Normalize(s, s);
  34813. tmp = SIMD.float32x4.mul(s, s);
  34814. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34815. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34816. var zero = SIMD.float32x4.splat(0.0);
  34817. s = SIMD.float32x4.neg(s);
  34818. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34819. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34820. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34821. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34822. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34823. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34824. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34825. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34826. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34827. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34828. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34829. var b3 = SIMD.float32x4.neg(eye);
  34830. b3 = SIMD.float32x4.withW(b3, 1.0);
  34831. 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)))));
  34832. 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)))));
  34833. 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)))));
  34834. 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)))));
  34835. };
  34836. return SIMDMatrix;
  34837. })();
  34838. BABYLON.SIMDMatrix = SIMDMatrix;
  34839. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34840. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34841. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34842. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34843. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34844. var SIMDHelper = (function () {
  34845. function SIMDHelper() {
  34846. }
  34847. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34848. get: function () {
  34849. return SIMDHelper._isEnabled;
  34850. },
  34851. enumerable: true,
  34852. configurable: true
  34853. });
  34854. SIMDHelper.DisableSIMD = function () {
  34855. // Replace functions
  34856. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34857. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34858. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34859. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34861. SIMDHelper._isEnabled = false;
  34862. };
  34863. SIMDHelper.EnableSIMD = function () {
  34864. if (window.SIMD === undefined) {
  34865. return;
  34866. }
  34867. // Replace functions
  34868. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34869. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34870. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34871. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34872. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34873. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34874. get: function () { return this._data[0]; },
  34875. set: function (value) {
  34876. if (!this._data) {
  34877. this._data = new Float32Array(3);
  34878. }
  34879. this._data[0] = value;
  34880. }
  34881. });
  34882. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34883. get: function () { return this._data[1]; },
  34884. set: function (value) {
  34885. this._data[1] = value;
  34886. }
  34887. });
  34888. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34889. get: function () { return this._data[2]; },
  34890. set: function (value) {
  34891. this._data[2] = value;
  34892. }
  34893. });
  34894. SIMDHelper._isEnabled = true;
  34895. };
  34896. SIMDHelper._isEnabled = false;
  34897. return SIMDHelper;
  34898. })();
  34899. BABYLON.SIMDHelper = SIMDHelper;
  34900. })(BABYLON || (BABYLON = {}));
  34901. var BABYLON;
  34902. (function (BABYLON) {
  34903. /**
  34904. * This class describe a rectangle that were added to the map.
  34905. * You have access to its coordinates either in pixel or normalized (UV)
  34906. */
  34907. var PackedRect = (function () {
  34908. function PackedRect(root, parent, pos, size) {
  34909. this._pos = pos;
  34910. this._size = size;
  34911. this._root = root;
  34912. this._parent = parent;
  34913. }
  34914. Object.defineProperty(PackedRect.prototype, "pos", {
  34915. /**
  34916. * @returns the position of this node into the map
  34917. */
  34918. get: function () {
  34919. return this._pos;
  34920. },
  34921. enumerable: true,
  34922. configurable: true
  34923. });
  34924. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34925. /**
  34926. * @returns the size of the rectangle this node handles
  34927. */
  34928. get: function () {
  34929. return this._contentSize;
  34930. },
  34931. enumerable: true,
  34932. configurable: true
  34933. });
  34934. Object.defineProperty(PackedRect.prototype, "UVs", {
  34935. /**
  34936. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34937. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34938. */
  34939. get: function () {
  34940. var mainWidth = this._root._size.width;
  34941. var mainHeight = this._root._size.height;
  34942. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34943. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34944. var uvs = new Array();
  34945. uvs.push(topLeft);
  34946. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34947. uvs.push(rightBottom);
  34948. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34949. return uvs;
  34950. },
  34951. enumerable: true,
  34952. configurable: true
  34953. });
  34954. /**
  34955. * Free this rectangle from the map.
  34956. * Call this method when you no longer need the rectangle to be in the map.
  34957. */
  34958. PackedRect.prototype.freeContent = function () {
  34959. if (!this.contentSize) {
  34960. return;
  34961. }
  34962. this._contentSize = null;
  34963. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34964. this.attemptDefrag();
  34965. };
  34966. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34967. get: function () {
  34968. return this._contentSize != null || this._leftNode != null;
  34969. },
  34970. enumerable: true,
  34971. configurable: true
  34972. });
  34973. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34974. var node = this.findNode(contentSize);
  34975. // Not enough space...
  34976. if (!node) {
  34977. return null;
  34978. }
  34979. node.splitNode(contentSize);
  34980. return node;
  34981. };
  34982. PackedRect.prototype.findNode = function (size) {
  34983. var resNode = null;
  34984. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34985. if (this.isUsed) {
  34986. if (this._leftNode) {
  34987. resNode = this._leftNode.findNode(size);
  34988. }
  34989. if (!resNode && this._rightNode) {
  34990. resNode = this._rightNode.findNode(size);
  34991. }
  34992. if (!resNode && this._bottomNode) {
  34993. resNode = this._bottomNode.findNode(size);
  34994. }
  34995. }
  34996. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34997. resNode = this;
  34998. }
  34999. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35000. resNode = this;
  35001. }
  35002. return resNode;
  35003. };
  35004. PackedRect.prototype.splitNode = function (contentSize) {
  35005. // 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)
  35006. if (!this._contentSize && this._initialSize) {
  35007. 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));
  35008. return this._leftNode.splitNode(contentSize);
  35009. }
  35010. else {
  35011. this._contentSize = contentSize.clone();
  35012. this._initialSize = contentSize.clone();
  35013. if (contentSize.width !== this._size.width) {
  35014. 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));
  35015. }
  35016. if (contentSize.height !== this._size.height) {
  35017. 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));
  35018. }
  35019. return this;
  35020. }
  35021. };
  35022. PackedRect.prototype.attemptDefrag = function () {
  35023. if (!this.isUsed && this.isRecursiveFree) {
  35024. this.clearNode();
  35025. if (this._parent) {
  35026. this._parent.attemptDefrag();
  35027. }
  35028. }
  35029. };
  35030. PackedRect.prototype.clearNode = function () {
  35031. this._initialSize = null;
  35032. this._rightNode = null;
  35033. this._bottomNode = null;
  35034. };
  35035. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35036. get: function () {
  35037. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. PackedRect.prototype.evalFreeSize = function (size) {
  35043. var levelSize = 0;
  35044. if (!this.isUsed) {
  35045. if (this._initialSize) {
  35046. levelSize = this._initialSize.surface;
  35047. }
  35048. else {
  35049. levelSize = this._size.surface;
  35050. }
  35051. }
  35052. if (this._rightNode) {
  35053. levelSize += this._rightNode.evalFreeSize(0);
  35054. }
  35055. if (this._bottomNode) {
  35056. levelSize += this._bottomNode.evalFreeSize(0);
  35057. }
  35058. return levelSize + size;
  35059. };
  35060. return PackedRect;
  35061. })();
  35062. BABYLON.PackedRect = PackedRect;
  35063. /**
  35064. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35065. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35066. * 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.
  35067. */
  35068. var RectPackingMap = (function (_super) {
  35069. __extends(RectPackingMap, _super);
  35070. /**
  35071. * Create an instance of the object with a dimension using the given size
  35072. * @param size The dimension of the rectangle that will contain all the sub ones.
  35073. */
  35074. function RectPackingMap(size) {
  35075. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35076. this._root = this;
  35077. }
  35078. /**
  35079. * Add a rectangle, finding the best location to store it into the map
  35080. * @param size the dimension of the rectangle to store
  35081. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35082. */
  35083. RectPackingMap.prototype.addRect = function (size) {
  35084. var node = this.findAndSplitNode(size);
  35085. return node;
  35086. };
  35087. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35088. /**
  35089. * Return the current space free normalized between [0;1]
  35090. * @returns {}
  35091. */
  35092. get: function () {
  35093. var freeSize = 0;
  35094. freeSize = this.evalFreeSize(freeSize);
  35095. return freeSize / (this._size.width * this._size.height);
  35096. },
  35097. enumerable: true,
  35098. configurable: true
  35099. });
  35100. return RectPackingMap;
  35101. })(PackedRect);
  35102. BABYLON.RectPackingMap = RectPackingMap;
  35103. })(BABYLON || (BABYLON = {}));
  35104. var BABYLON;
  35105. (function (BABYLON) {
  35106. var DynamicFloatArrayElementInfo = (function () {
  35107. function DynamicFloatArrayElementInfo() {
  35108. }
  35109. return DynamicFloatArrayElementInfo;
  35110. })();
  35111. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35112. /**
  35113. * 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.
  35114. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35115. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35116. * 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.
  35117. * 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.
  35118. * 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".
  35119. */
  35120. var DynamicFloatArray = (function () {
  35121. /**
  35122. * Construct an instance of the dynamic float array
  35123. * @param stride size of one element in float (i.e. not bytes!)
  35124. * @param initialElementCount the number of available entries at construction
  35125. */
  35126. function DynamicFloatArray(stride, initialElementCount) {
  35127. this.compareValueOffset = null;
  35128. this.sortingAscending = true;
  35129. this._stride = stride;
  35130. this.buffer = new Float32Array(stride * initialElementCount);
  35131. this._lastUsed = 0;
  35132. this._firstFree = 0;
  35133. this._allEntries = new Array(initialElementCount);
  35134. this._freeEntries = new Array(initialElementCount);
  35135. for (var i = 0; i < initialElementCount; i++) {
  35136. var element = new DynamicFloatArrayElementInfo();
  35137. element.offset = i * stride;
  35138. this._allEntries[i] = element;
  35139. this._freeEntries[initialElementCount - i - 1] = element;
  35140. }
  35141. }
  35142. /**
  35143. * Allocate an element in the array.
  35144. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35145. * Beware, this offset may change when you call pack()
  35146. */
  35147. DynamicFloatArray.prototype.allocElement = function () {
  35148. if (this._freeEntries.length === 0) {
  35149. this._growBuffer();
  35150. }
  35151. var el = this._freeEntries.pop();
  35152. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35153. if (el.offset === this._firstFree) {
  35154. if (this._freeEntries.length > 0) {
  35155. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35156. }
  35157. else {
  35158. this._firstFree += this._stride;
  35159. }
  35160. }
  35161. return el;
  35162. };
  35163. /**
  35164. * Free the element corresponding to the given element info
  35165. * @param elInfo the element that describe the allocated element
  35166. */
  35167. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35168. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35169. this._freeEntries.push(elInfo);
  35170. };
  35171. /**
  35172. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35173. * 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().
  35174. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35175. */
  35176. DynamicFloatArray.prototype.pack = function () {
  35177. // no free slot? no need to pack
  35178. if (this._freeEntries.length === 0) {
  35179. return this.buffer;
  35180. }
  35181. // If the buffer is already packed the last used will always be lower than the first free
  35182. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  35183. if (this._lastUsed < this._firstFree) {
  35184. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35185. return elementsBuffer_1;
  35186. }
  35187. var s = this._stride;
  35188. // 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
  35189. var lastFree = new DynamicFloatArrayElementInfo();
  35190. lastFree.offset = this.totalElementCount * s;
  35191. this._freeEntries.push(lastFree);
  35192. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35193. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35194. var firstFreeSlotOffset = sortedFree[0].offset;
  35195. var freeZoneSize = 1;
  35196. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35197. var prevOffset = sortedFree[0].offset;
  35198. for (var i = 1; i < sortedFree.length; i++) {
  35199. // 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
  35200. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35201. break;
  35202. }
  35203. var curFree = sortedFree[i];
  35204. var curOffset = curFree.offset;
  35205. // Compute the distance between this offset and the previous
  35206. var distance = curOffset - prevOffset;
  35207. // If the distance is the stride size, they are adjacent, it good, move to the next
  35208. if (distance === s) {
  35209. // Free zone is one element bigger
  35210. ++freeZoneSize;
  35211. // as we're about to iterate to the next, the cur becomes the previous...
  35212. prevOffset = curOffset;
  35213. continue;
  35214. }
  35215. // Distance is bigger, which means there's x element between the previous free and this one
  35216. var usedRange = (distance / s) - 1;
  35217. // Two cases the free zone is smaller than the data to move or bigger
  35218. // Copy what can fit in the free zone
  35219. var curMoveOffset = curOffset - s;
  35220. var copyCount = Math.min(freeZoneSize, usedRange);
  35221. for (var j = 0; j < copyCount; j++) {
  35222. var freeI = firstFreeSlotOffset / s;
  35223. var curI = curMoveOffset / s;
  35224. var moveEl = sortedAll[curI];
  35225. this._moveElement(moveEl, firstFreeSlotOffset);
  35226. var replacedEl = sortedAll[freeI];
  35227. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35228. replacedEl.offset = curMoveOffset;
  35229. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35230. sortedAll[freeI] = moveEl;
  35231. sortedAll[curI] = replacedEl;
  35232. curMoveOffset -= s;
  35233. firstFreeSlotOffset += s;
  35234. }
  35235. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35236. if (freeZoneSize <= usedRange) {
  35237. firstFreeSlotOffset = curMoveOffset + s;
  35238. freeZoneSize = 1 + copyCount;
  35239. }
  35240. else {
  35241. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35242. }
  35243. // as we're about to iterate to the next, the cur becomes the previous...
  35244. prevOffset = curOffset;
  35245. }
  35246. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35247. this._lastUsed = firstFreeSlotOffset - s;
  35248. this._firstFree = firstFreeSlotOffset;
  35249. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35250. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35251. this._allEntries = sortedAll;
  35252. return elementsBuffer;
  35253. };
  35254. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35255. for (var i = 0; i < this._stride; i++) {
  35256. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35257. }
  35258. element.offset = destOffset;
  35259. };
  35260. DynamicFloatArray.prototype._growBuffer = function () {
  35261. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35262. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35263. var newBuffer = new Float32Array(newElCount * this._stride);
  35264. newBuffer.set(this.buffer);
  35265. var curCount = this.totalElementCount;
  35266. var addedCount = newElCount - this.totalElementCount;
  35267. for (var i = 0; i < addedCount; i++) {
  35268. var element = new DynamicFloatArrayElementInfo();
  35269. element.offset = (curCount + i) * this.stride;
  35270. this._allEntries.push(element);
  35271. this._freeEntries[addedCount - i - 1] = element;
  35272. }
  35273. this._firstFree = curCount * this.stride;
  35274. this.buffer = newBuffer;
  35275. };
  35276. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35277. /**
  35278. * Get the total count of entries that can fit in the current buffer
  35279. * @returns the elements count
  35280. */
  35281. get: function () {
  35282. return this._allEntries.length;
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35288. /**
  35289. * Get the count of free entries that can still be allocated without resizing the buffer
  35290. * @returns the free elements count
  35291. */
  35292. get: function () {
  35293. return this._freeEntries.length;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  35299. /**
  35300. * Get the count of allocated elements
  35301. * @returns the allocated elements count
  35302. */
  35303. get: function () {
  35304. return this._allEntries.length - this._freeEntries.length;
  35305. },
  35306. enumerable: true,
  35307. configurable: true
  35308. });
  35309. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  35310. /**
  35311. * Return the size of one element in float
  35312. * @returns the size in float
  35313. */
  35314. get: function () {
  35315. return this._stride;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. DynamicFloatArray.prototype.sort = function () {
  35321. var _this = this;
  35322. if (!this.compareValueOffset) {
  35323. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  35324. }
  35325. var count = this.usedElementCount;
  35326. // Do we have to (re)create the sort table?
  35327. if (!this._sortTable || this._sortTable.length < count) {
  35328. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  35329. var newCount = Math.min(this.totalElementCount, count * 2);
  35330. this._sortTable = new Array(newCount);
  35331. this._sortedTable = new Array(newCount);
  35332. }
  35333. // Because, you know...
  35334. this.pack();
  35335. //let stride = this.stride;
  35336. //for (let i = 0; i < count; i++) {
  35337. // let si = this._sortTable[i];
  35338. // if (!si) {
  35339. // si = new SortInfo();
  35340. // this._sortTable[i] = si;
  35341. // }
  35342. // si.entry = this._allEntries[i];
  35343. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  35344. // si.swapedOffset = null;
  35345. // this._sortedTable[i] = si;
  35346. //}
  35347. var curOffset = 0;
  35348. var stride = this.stride;
  35349. for (var i = 0; i < count; i++, curOffset += stride) {
  35350. var si = this._sortTable[i];
  35351. if (!si) {
  35352. si = new SortInfo();
  35353. this._sortTable[i] = si;
  35354. }
  35355. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  35356. si.offset = curOffset;
  35357. si.swapedOffset = null;
  35358. this._sortedTable[i] = si;
  35359. }
  35360. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  35361. if (this.sortingAscending) {
  35362. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  35363. }
  35364. else {
  35365. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  35366. }
  35367. var swapElements = function (src, dst) {
  35368. for (var i = 0; i < stride; i++) {
  35369. var tps = _this.buffer[dst + i];
  35370. _this.buffer[dst + i] = _this.buffer[src + i];
  35371. _this.buffer[src + i] = tps;
  35372. }
  35373. };
  35374. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  35375. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  35376. // and I still want something with a good algorithm complexity.
  35377. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  35378. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  35379. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  35380. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  35381. // until we find a SortInfo object without a swapedOffset which means we got the right location
  35382. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  35383. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  35384. for (var i = 0; i < count; i++) {
  35385. // Get the element to move
  35386. var sourceSI = this._sortedTable[i];
  35387. var destSI = this._sortTable[i];
  35388. var sourceOff = sourceSI.offset;
  35389. // If the source changed location, find the new one
  35390. if (sourceSI.swapedOffset) {
  35391. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  35392. var curSI = sourceSI;
  35393. while (curSI.swapedOffset) {
  35394. curSI = this._sortTable[curSI.swapedOffset / stride];
  35395. }
  35396. // Finally get the right location
  35397. sourceOff = curSI.offset;
  35398. }
  35399. // Tag the element being replaced with its new location
  35400. destSI.swapedOffset = sourceOff;
  35401. // Swap elements (only if needed)
  35402. if (sourceOff !== destSI.offset) {
  35403. swapElements(sourceOff, destSI.offset);
  35404. }
  35405. // Update the offset in the corresponding DFAE
  35406. //sourceSI.entry.offset = destSI.entry.offset;
  35407. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  35408. }
  35409. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35410. return true;
  35411. };
  35412. return DynamicFloatArray;
  35413. })();
  35414. BABYLON.DynamicFloatArray = DynamicFloatArray;
  35415. var SortInfo = (function () {
  35416. function SortInfo() {
  35417. this.compareData = this.offset = this.swapedOffset = null;
  35418. }
  35419. return SortInfo;
  35420. })();
  35421. })(BABYLON || (BABYLON = {}));
  35422. var BABYLON;
  35423. (function (BABYLON) {
  35424. /**
  35425. * This class given information about a given character.
  35426. */
  35427. var CharInfo = (function () {
  35428. function CharInfo() {
  35429. }
  35430. return CharInfo;
  35431. })();
  35432. BABYLON.CharInfo = CharInfo;
  35433. var FontTexture = (function (_super) {
  35434. __extends(FontTexture, _super);
  35435. /**
  35436. * Create a new instance of the FontTexture class
  35437. * @param name the name of the texture
  35438. * @param font the font to use, use the W3C CSS notation
  35439. * @param scene the scene that owns the texture
  35440. * @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
  35441. * @param samplingMode the texture sampling mode
  35442. */
  35443. function FontTexture(name, font, scene, maxCharCount, samplingMode) {
  35444. if (maxCharCount === void 0) { maxCharCount = 200; }
  35445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35446. _super.call(this, null, scene, true, false, samplingMode);
  35447. this._charInfos = {};
  35448. this._curCharCount = 0;
  35449. this._lastUpdateCharCount = -1;
  35450. this._usedCounter = 1;
  35451. this.name = name;
  35452. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35453. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35454. // First canvas creation to determine the size of the texture to create
  35455. this._canvas = document.createElement("canvas");
  35456. this._context = this._canvas.getContext("2d");
  35457. this._context.font = font;
  35458. this._context.fillStyle = "white";
  35459. var res = this.getFontHeight(font);
  35460. this._lineHeight = res.height;
  35461. this._offset = res.offset - 1;
  35462. var maxCharWidth = this._context.measureText("W").width;
  35463. this._spaceWidth = this._context.measureText(" ").width;
  35464. // This is an approximate size, but should always be able to fit at least the maxCharCount
  35465. var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
  35466. var edge = Math.sqrt(totalEstSurface);
  35467. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  35468. // Create the texture that will store the font characters
  35469. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  35470. var textureSize = this.getSize();
  35471. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  35472. this._canvas = document.createElement("canvas");
  35473. this._canvas.width = textureSize.width;
  35474. this._canvas.height = textureSize.height;
  35475. this._context = this._canvas.getContext("2d");
  35476. this._context.textBaseline = "top";
  35477. this._context.font = font;
  35478. this._context.fillStyle = "white";
  35479. this._context.imageSmoothingEnabled = false;
  35480. this._currentFreePosition = BABYLON.Vector2.Zero();
  35481. // Add the basic ASCII based characters
  35482. for (var i = 0x20; i < 0x7F; i++) {
  35483. var c = String.fromCharCode(i);
  35484. this.getChar(c);
  35485. }
  35486. this.update();
  35487. }
  35488. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  35489. get: function () {
  35490. return this._spaceWidth;
  35491. },
  35492. enumerable: true,
  35493. configurable: true
  35494. });
  35495. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  35496. get: function () {
  35497. return this._lineHeight;
  35498. },
  35499. enumerable: true,
  35500. configurable: true
  35501. });
  35502. FontTexture.GetCachedFontTexture = function (scene, fontName) {
  35503. var s = scene;
  35504. if (!s.__fontTextureCache__) {
  35505. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  35506. }
  35507. var dic = s.__fontTextureCache__;
  35508. var lfn = fontName.toLocaleLowerCase();
  35509. var ft = dic.get(lfn);
  35510. if (ft) {
  35511. ++ft._usedCounter;
  35512. return ft;
  35513. }
  35514. ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35515. dic.add(lfn, ft);
  35516. return ft;
  35517. };
  35518. FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
  35519. var s = scene;
  35520. var dic = s.__fontTextureCache__;
  35521. if (!dic) {
  35522. return;
  35523. }
  35524. var lfn = fontName.toLocaleLowerCase();
  35525. var font = dic.get(lfn);
  35526. if (--font._usedCounter === 0) {
  35527. dic.remove(lfn);
  35528. font.dispose();
  35529. }
  35530. };
  35531. /**
  35532. * Make sure the given char is present in the font map.
  35533. * @param char the character to get or add
  35534. * @return the CharInfo instance corresponding to the given character
  35535. */
  35536. FontTexture.prototype.getChar = function (char) {
  35537. if (char.length !== 1) {
  35538. return null;
  35539. }
  35540. var info = this._charInfos[char];
  35541. if (info) {
  35542. return info;
  35543. }
  35544. info = new CharInfo();
  35545. var measure = this._context.measureText(char);
  35546. var textureSize = this.getSize();
  35547. // we reached the end of the current line?
  35548. var xMargin = 2;
  35549. var yMargin = 2;
  35550. var width = measure.width;
  35551. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  35552. this._currentFreePosition.x = 0;
  35553. this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
  35554. // No more room?
  35555. if (this._currentFreePosition.y > textureSize.height) {
  35556. return this.getChar("!");
  35557. }
  35558. }
  35559. // Draw the character in the texture
  35560. this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
  35561. // Fill the CharInfo object
  35562. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  35563. info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
  35564. info.charWidth = width;
  35565. // Add the info structure
  35566. this._charInfos[char] = info;
  35567. this._curCharCount++;
  35568. // Set the next position
  35569. this._currentFreePosition.x += width + xMargin;
  35570. return info;
  35571. };
  35572. FontTexture.prototype.measureText = function (text, tabulationSize) {
  35573. if (tabulationSize === void 0) { tabulationSize = 4; }
  35574. var maxWidth = 0;
  35575. var curWidth = 0;
  35576. var lineCount = 1;
  35577. var charxpos = 0;
  35578. // Parse each char of the string
  35579. for (var _i = 0; _i < text.length; _i++) {
  35580. var char = text[_i];
  35581. // Next line feed?
  35582. if (char === "\n") {
  35583. maxWidth = Math.max(maxWidth, curWidth);
  35584. charxpos = 0;
  35585. curWidth = 0;
  35586. ++lineCount;
  35587. continue;
  35588. }
  35589. // Tabulation ?
  35590. if (char === "\t") {
  35591. var nextPos = charxpos + tabulationSize;
  35592. nextPos = nextPos - (nextPos % tabulationSize);
  35593. curWidth += (nextPos - charxpos) * this.spaceWidth;
  35594. charxpos = nextPos;
  35595. continue;
  35596. }
  35597. if (char < " ") {
  35598. continue;
  35599. }
  35600. curWidth += this.getChar(char).charWidth;
  35601. ++charxpos;
  35602. }
  35603. maxWidth = Math.max(maxWidth, curWidth);
  35604. return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
  35605. };
  35606. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  35607. FontTexture.prototype.getFontHeight = function (font) {
  35608. var fontDraw = document.createElement("canvas");
  35609. var ctx = fontDraw.getContext('2d');
  35610. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  35611. ctx.textBaseline = 'top';
  35612. ctx.fillStyle = 'white';
  35613. ctx.font = font;
  35614. ctx.fillText('jH|', 0, 0);
  35615. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  35616. var start = -1;
  35617. var end = -1;
  35618. for (var row = 0; row < fontDraw.height; row++) {
  35619. for (var column = 0; column < fontDraw.width; column++) {
  35620. var index = (row * fontDraw.width + column) * 4;
  35621. if (pixels[index] === 0) {
  35622. if (column === fontDraw.width - 1 && start !== -1) {
  35623. end = row;
  35624. row = fontDraw.height;
  35625. break;
  35626. }
  35627. continue;
  35628. }
  35629. else {
  35630. if (start === -1) {
  35631. start = row;
  35632. }
  35633. break;
  35634. }
  35635. }
  35636. }
  35637. return { height: end - start, offset: start - 1 };
  35638. };
  35639. Object.defineProperty(FontTexture.prototype, "canRescale", {
  35640. get: function () {
  35641. return false;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. FontTexture.prototype.getContext = function () {
  35647. return this._context;
  35648. };
  35649. /**
  35650. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  35651. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  35652. */
  35653. FontTexture.prototype.update = function () {
  35654. // Update only if there's new char added since the previous update
  35655. if (this._lastUpdateCharCount < this._curCharCount) {
  35656. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  35657. this._lastUpdateCharCount = this._curCharCount;
  35658. }
  35659. };
  35660. // cloning should be prohibited, there's no point to duplicate this texture at all
  35661. FontTexture.prototype.clone = function () {
  35662. return null;
  35663. };
  35664. return FontTexture;
  35665. })(BABYLON.Texture);
  35666. BABYLON.FontTexture = FontTexture;
  35667. })(BABYLON || (BABYLON = {}));
  35668. var BABYLON;
  35669. (function (BABYLON) {
  35670. var MapTexture = (function (_super) {
  35671. __extends(MapTexture, _super);
  35672. function MapTexture(name, scene, size, samplingMode) {
  35673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35674. _super.call(this, null, scene, true, false, samplingMode);
  35675. this.name = name;
  35676. this._size = size;
  35677. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35678. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35679. // Create the rectPackMap that will allocate portion of the texture
  35680. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  35681. // Create the texture that will store the content
  35682. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  35683. }
  35684. /**
  35685. * Allocate a rectangle of a given size in the texture map
  35686. * @param size the size of the rectangle to allocation
  35687. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  35688. */
  35689. MapTexture.prototype.allocateRect = function (size) {
  35690. return this._rectPackingMap.addRect(size);
  35691. };
  35692. /**
  35693. * Free a given rectangle from the texture map
  35694. * @param rectInfo the instance corresponding to the rect to free.
  35695. */
  35696. MapTexture.prototype.freeRect = function (rectInfo) {
  35697. if (rectInfo) {
  35698. rectInfo.freeContent();
  35699. }
  35700. };
  35701. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  35702. /**
  35703. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  35704. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  35705. * @returns {}
  35706. */
  35707. get: function () {
  35708. return this._rectPackingMap.freeSpace;
  35709. },
  35710. enumerable: true,
  35711. configurable: true
  35712. });
  35713. /**
  35714. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  35715. * 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.
  35716. * Don't forget to call unbindTexture when you're done rendering
  35717. * @param rect the zone to render to
  35718. * @param clear true to clear the portion's color/depth data
  35719. */
  35720. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  35721. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  35722. };
  35723. /**
  35724. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  35725. * 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.
  35726. * Don't forget to call unbindTexture when you're done rendering
  35727. * @param pos the position into the texture
  35728. * @param size the portion to fit the clip space to
  35729. * @param clear true to clear the portion's color/depth data
  35730. */
  35731. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  35732. var engine = this.getScene().getEngine();
  35733. engine.bindFramebuffer(this._texture);
  35734. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  35735. if (clear) {
  35736. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  35737. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  35738. }
  35739. };
  35740. /**
  35741. * Unbind the texture map from the rendering engine.
  35742. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  35743. * @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.
  35744. */
  35745. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  35746. // Dump ?
  35747. if (dumpForDebug) {
  35748. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  35749. }
  35750. var engine = this.getScene().getEngine();
  35751. if (this._replacedViewport) {
  35752. engine.setViewport(this._replacedViewport);
  35753. this._replacedViewport = null;
  35754. }
  35755. engine.unBindFramebuffer(this._texture);
  35756. };
  35757. Object.defineProperty(MapTexture.prototype, "canRescale", {
  35758. get: function () {
  35759. return false;
  35760. },
  35761. enumerable: true,
  35762. configurable: true
  35763. });
  35764. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  35765. // Anyway, there's not much point to use this method for this kind of texture I guess
  35766. MapTexture.prototype.clone = function () {
  35767. return null;
  35768. };
  35769. return MapTexture;
  35770. })(BABYLON.Texture);
  35771. BABYLON.MapTexture = MapTexture;
  35772. })(BABYLON || (BABYLON = {}));
  35773. var BABYLON;
  35774. (function (BABYLON) {
  35775. /**
  35776. * Stores 2D Bounding Information.
  35777. * This class handles a circle area and a bounding rectangle one.
  35778. */
  35779. var BoundingInfo2D = (function () {
  35780. function BoundingInfo2D() {
  35781. this.radius = 0;
  35782. this.center = BABYLON.Vector2.Zero();
  35783. this.extent = BABYLON.Vector2.Zero();
  35784. }
  35785. BoundingInfo2D.CreateFromSize = function (size, origin) {
  35786. var r = new BoundingInfo2D();
  35787. BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
  35788. return r;
  35789. };
  35790. BoundingInfo2D.CreateFromRadius = function (radius, origin) {
  35791. var r = new BoundingInfo2D();
  35792. BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
  35793. return r;
  35794. };
  35795. BoundingInfo2D.CreateFromPoints = function (points, origin) {
  35796. var r = new BoundingInfo2D();
  35797. BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
  35798. return r;
  35799. };
  35800. BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
  35801. b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
  35802. b.extent = b.center.clone();
  35803. if (origin) {
  35804. b.center.x -= size.width * origin.x;
  35805. b.center.y -= size.height * origin.y;
  35806. }
  35807. b.radius = b.extent.length();
  35808. };
  35809. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
  35810. b.center = BABYLON.Vector2.Zero();
  35811. if (origin) {
  35812. b.center.x -= radius * origin.x;
  35813. b.center.y -= radius * origin.y;
  35814. }
  35815. b.extent = new BABYLON.Vector2(radius, radius);
  35816. b.radius = radius;
  35817. };
  35818. BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
  35819. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  35820. for (var _i = 0; _i < points.length; _i++) {
  35821. var p = points[_i];
  35822. xmin = Math.min(p.x, xmin);
  35823. xmax = Math.max(p.x, xmax);
  35824. ymin = Math.min(p.y, ymin);
  35825. ymax = Math.max(p.y, ymax);
  35826. }
  35827. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
  35828. };
  35829. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
  35830. var w = xmax - xmin;
  35831. var h = ymax - ymin;
  35832. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  35833. if (origin) {
  35834. b.center.x -= w * origin.x;
  35835. b.center.y -= h * origin.y;
  35836. }
  35837. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  35838. b.radius = b.extent.length();
  35839. };
  35840. /**
  35841. * Duplicate this instance and return a new one
  35842. * @return the duplicated instance
  35843. */
  35844. BoundingInfo2D.prototype.clone = function () {
  35845. var r = new BoundingInfo2D();
  35846. r.center = this.center.clone();
  35847. r.radius = this.radius;
  35848. r.extent = this.extent.clone();
  35849. return r;
  35850. };
  35851. BoundingInfo2D.prototype.max = function () {
  35852. var r = BABYLON.Vector2.Zero();
  35853. this.maxToRef(r);
  35854. return r;
  35855. };
  35856. BoundingInfo2D.prototype.maxToRef = function (result) {
  35857. result.x = this.center.x + this.extent.x;
  35858. result.y = this.center.y + this.extent.y;
  35859. };
  35860. /**
  35861. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  35862. * @param matrix the transformation matrix to apply
  35863. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  35864. */
  35865. BoundingInfo2D.prototype.transform = function (matrix) {
  35866. var r = new BoundingInfo2D();
  35867. this.transformToRef(matrix, r);
  35868. return r;
  35869. };
  35870. /**
  35871. * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
  35872. * @param other the second BoundingInfo2D to compute the union with this one
  35873. * @return a new instance containing the result of the union
  35874. */
  35875. BoundingInfo2D.prototype.union = function (other) {
  35876. var r = new BoundingInfo2D();
  35877. this.unionToRef(other, r);
  35878. return r;
  35879. };
  35880. /**
  35881. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  35882. * 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.
  35883. * @param matrix The matrix to use to compute the transformation
  35884. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  35885. */
  35886. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  35887. // Construct a bounding box based on the extent values
  35888. var p = BoundingInfo2D._transform;
  35889. p[0].x = this.center.x + this.extent.x;
  35890. p[0].y = this.center.y + this.extent.y;
  35891. p[1].x = this.center.x + this.extent.x;
  35892. p[1].y = this.center.y - this.extent.y;
  35893. p[2].x = this.center.x - this.extent.x;
  35894. p[2].y = this.center.y - this.extent.y;
  35895. p[3].x = this.center.x - this.extent.x;
  35896. p[3].y = this.center.y + this.extent.y;
  35897. // Transform the four points of the bounding box with the matrix
  35898. for (var i = 0; i < 4; i++) {
  35899. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  35900. }
  35901. BoundingInfo2D.CreateFromPointsToRef(p, result);
  35902. };
  35903. /**
  35904. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  35905. * 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.
  35906. * @param other the second object used to compute the union
  35907. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  35908. */
  35909. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  35910. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  35911. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  35912. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  35913. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  35914. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  35915. };
  35916. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  35917. // is it inside the radius?
  35918. var pickLocal = pickPosition.subtract(this.center);
  35919. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  35920. // is it inside the rectangle?
  35921. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  35922. }
  35923. return false;
  35924. };
  35925. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  35926. return BoundingInfo2D;
  35927. })();
  35928. BABYLON.BoundingInfo2D = BoundingInfo2D;
  35929. })(BABYLON || (BABYLON = {}));
  35930. var BABYLON;
  35931. (function (BABYLON) {
  35932. /**
  35933. * Base class implementing the ILocable interface.
  35934. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  35935. */
  35936. var LockableBase = (function () {
  35937. function LockableBase() {
  35938. }
  35939. LockableBase.prototype.isLocked = function () {
  35940. return this._isLocked;
  35941. };
  35942. LockableBase.prototype.lock = function () {
  35943. if (this._isLocked) {
  35944. return true;
  35945. }
  35946. this.onLock();
  35947. this._isLocked = true;
  35948. return false;
  35949. };
  35950. /**
  35951. * Protected handler that will be called when the instance is about to be locked.
  35952. */
  35953. LockableBase.prototype.onLock = function () {
  35954. };
  35955. return LockableBase;
  35956. })();
  35957. BABYLON.LockableBase = LockableBase;
  35958. /**
  35959. * 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).
  35960. */
  35961. var SolidColorBrush2D = (function (_super) {
  35962. __extends(SolidColorBrush2D, _super);
  35963. function SolidColorBrush2D(color, lock) {
  35964. if (lock === void 0) { lock = false; }
  35965. _super.call(this);
  35966. this._color = color;
  35967. if (lock) {
  35968. {
  35969. this.lock();
  35970. }
  35971. }
  35972. }
  35973. SolidColorBrush2D.prototype.isTransparent = function () {
  35974. return this._color && this._color.a < 1.0;
  35975. };
  35976. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  35977. /**
  35978. * The color used by this instance to render
  35979. * @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.
  35980. */
  35981. get: function () {
  35982. return this._color;
  35983. },
  35984. set: function (value) {
  35985. if (this.isLocked()) {
  35986. return;
  35987. }
  35988. this._color = value;
  35989. },
  35990. enumerable: true,
  35991. configurable: true
  35992. });
  35993. /**
  35994. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  35995. */
  35996. SolidColorBrush2D.prototype.toString = function () {
  35997. return this._color.toHexString();
  35998. };
  35999. SolidColorBrush2D = __decorate([
  36000. BABYLON.className("SolidColorBrush2D")
  36001. ], SolidColorBrush2D);
  36002. return SolidColorBrush2D;
  36003. })(LockableBase);
  36004. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36005. var GradientColorBrush2D = (function (_super) {
  36006. __extends(GradientColorBrush2D, _super);
  36007. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36008. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36009. if (rotation === void 0) { rotation = 0; }
  36010. if (scale === void 0) { scale = 1; }
  36011. if (lock === void 0) { lock = false; }
  36012. _super.call(this);
  36013. this._color1 = color1;
  36014. this._color2 = color2;
  36015. this._translation = translation;
  36016. this._rotation = rotation;
  36017. this._scale = scale;
  36018. if (lock) {
  36019. this.lock();
  36020. }
  36021. }
  36022. GradientColorBrush2D.prototype.isTransparent = function () {
  36023. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36024. };
  36025. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36026. get: function () {
  36027. return this._color1;
  36028. },
  36029. set: function (value) {
  36030. if (this.isLocked()) {
  36031. return;
  36032. }
  36033. this._color1 = value;
  36034. },
  36035. enumerable: true,
  36036. configurable: true
  36037. });
  36038. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36039. get: function () {
  36040. return this._color2;
  36041. },
  36042. set: function (value) {
  36043. if (this.isLocked()) {
  36044. return;
  36045. }
  36046. this._color2 = value;
  36047. },
  36048. enumerable: true,
  36049. configurable: true
  36050. });
  36051. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36052. get: function () {
  36053. return this._translation;
  36054. },
  36055. set: function (value) {
  36056. if (this.isLocked()) {
  36057. return;
  36058. }
  36059. this._translation = value;
  36060. },
  36061. enumerable: true,
  36062. configurable: true
  36063. });
  36064. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  36065. get: function () {
  36066. return this._rotation;
  36067. },
  36068. set: function (value) {
  36069. if (this.isLocked()) {
  36070. return;
  36071. }
  36072. this._rotation = value;
  36073. },
  36074. enumerable: true,
  36075. configurable: true
  36076. });
  36077. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  36078. get: function () {
  36079. return this._scale;
  36080. },
  36081. set: function (value) {
  36082. if (this.isLocked()) {
  36083. return;
  36084. }
  36085. this._scale = value;
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. GradientColorBrush2D.prototype.toString = function () {
  36091. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  36092. };
  36093. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  36094. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  36095. };
  36096. GradientColorBrush2D = __decorate([
  36097. BABYLON.className("GradientColorBrush2D")
  36098. ], GradientColorBrush2D);
  36099. return GradientColorBrush2D;
  36100. })(LockableBase);
  36101. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  36102. })(BABYLON || (BABYLON = {}));
  36103. var BABYLON;
  36104. (function (BABYLON) {
  36105. var Prim2DClassInfo = (function () {
  36106. function Prim2DClassInfo() {
  36107. }
  36108. return Prim2DClassInfo;
  36109. })();
  36110. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  36111. var Prim2DPropInfo = (function () {
  36112. function Prim2DPropInfo() {
  36113. }
  36114. Prim2DPropInfo.PROPKIND_MODEL = 1;
  36115. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  36116. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  36117. return Prim2DPropInfo;
  36118. })();
  36119. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  36120. var PropertyChangedInfo = (function () {
  36121. function PropertyChangedInfo() {
  36122. }
  36123. return PropertyChangedInfo;
  36124. })();
  36125. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  36126. var ClassTreeInfo = (function () {
  36127. function ClassTreeInfo(baseClass, type, classContentFactory) {
  36128. this._baseClass = baseClass;
  36129. this._type = type;
  36130. this._subClasses = new Array();
  36131. this._levelContent = new BABYLON.StringDictionary();
  36132. this._classContentFactory = classContentFactory;
  36133. }
  36134. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  36135. get: function () {
  36136. if (!this._classContent) {
  36137. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  36138. }
  36139. return this._classContent;
  36140. },
  36141. enumerable: true,
  36142. configurable: true
  36143. });
  36144. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  36145. get: function () {
  36146. return this._type;
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  36152. get: function () {
  36153. return this._levelContent;
  36154. },
  36155. enumerable: true,
  36156. configurable: true
  36157. });
  36158. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  36159. get: function () {
  36160. if (!this._fullContent) {
  36161. var dic = new BABYLON.StringDictionary();
  36162. var curLevel = this;
  36163. while (curLevel) {
  36164. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  36165. curLevel = curLevel._baseClass;
  36166. }
  36167. this._fullContent = dic;
  36168. }
  36169. return this._fullContent;
  36170. },
  36171. enumerable: true,
  36172. configurable: true
  36173. });
  36174. ClassTreeInfo.prototype.getLevelOf = function (type) {
  36175. // Are we already there?
  36176. if (type === this._type) {
  36177. return this;
  36178. }
  36179. var baseProto = Object.getPrototypeOf(type);
  36180. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  36181. if (!curProtoContent) {
  36182. this.getLevelOf(baseProto);
  36183. }
  36184. return this.getOrAddType(baseProto, type);
  36185. };
  36186. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  36187. // Are we at the level corresponding to the baseType?
  36188. // If so, get or add the level we're looking for
  36189. if (baseType === this._type) {
  36190. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  36191. var subType = _a[_i];
  36192. if (subType.type === type) {
  36193. return subType.node;
  36194. }
  36195. }
  36196. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  36197. var info = { type: type, node: node };
  36198. this._subClasses.push(info);
  36199. return info.node;
  36200. }
  36201. // Recurse down to keep looking for the node corresponding to the baseTypeName
  36202. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  36203. var subType = _c[_b];
  36204. var info = subType.node.getOrAddType(baseType, type);
  36205. if (info) {
  36206. return info;
  36207. }
  36208. }
  36209. return null;
  36210. };
  36211. ClassTreeInfo.get = function (type) {
  36212. var dic = type["__classTreeInfo"];
  36213. if (!dic) {
  36214. return null;
  36215. }
  36216. return dic.getLevelOf(type);
  36217. };
  36218. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  36219. var dic = type["__classTreeInfo"];
  36220. if (!dic) {
  36221. dic = new ClassTreeInfo(null, type, classContentFactory);
  36222. type["__classTreeInfo"] = dic;
  36223. }
  36224. return dic;
  36225. };
  36226. return ClassTreeInfo;
  36227. })();
  36228. BABYLON.ClassTreeInfo = ClassTreeInfo;
  36229. var SmartPropertyPrim = (function () {
  36230. function SmartPropertyPrim() {
  36231. }
  36232. SmartPropertyPrim.prototype.setupSmartPropertyPrim = function () {
  36233. this._modelKey = null;
  36234. this._modelDirty = false;
  36235. this._levelBoundingInfoDirty = false;
  36236. this._instanceDirtyFlags = 0;
  36237. this._isDisposed = false;
  36238. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  36239. this.animations = new Array();
  36240. };
  36241. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  36242. /**
  36243. * Check if the object is disposed or not.
  36244. * @returns true if the object is dispose, false otherwise.
  36245. */
  36246. get: function () {
  36247. return this._isDisposed;
  36248. },
  36249. enumerable: true,
  36250. configurable: true
  36251. });
  36252. /**
  36253. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  36254. * @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.
  36255. */
  36256. SmartPropertyPrim.prototype.dispose = function () {
  36257. if (this.isDisposed) {
  36258. return false;
  36259. }
  36260. // Don't set to null, it may upset somebody...
  36261. this.animations.splice(0);
  36262. this._isDisposed = true;
  36263. return true;
  36264. };
  36265. /**
  36266. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  36267. * Look at Sprite2D for more information
  36268. */
  36269. SmartPropertyPrim.prototype.getAnimatables = function () {
  36270. return new Array();
  36271. };
  36272. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  36273. /**
  36274. * Property giving the Model Key associated to the property.
  36275. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  36276. * @returns the model key string.
  36277. */
  36278. get: function () {
  36279. var _this = this;
  36280. // No need to compute it?
  36281. if (!this._modelDirty && this._modelKey) {
  36282. return this._modelKey;
  36283. }
  36284. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  36285. var propDic = this.propDic;
  36286. propDic.forEach(function (k, v) {
  36287. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36288. var propVal = _this[v.name];
  36289. // 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
  36290. if (propVal && propVal.constructor === Array) {
  36291. var firstVal = propVal[0];
  36292. if (!firstVal) {
  36293. propVal = 0;
  36294. }
  36295. else {
  36296. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  36297. }
  36298. }
  36299. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  36300. }
  36301. });
  36302. this._modelDirty = false;
  36303. this._modelKey = modelKey;
  36304. return modelKey;
  36305. },
  36306. enumerable: true,
  36307. configurable: true
  36308. });
  36309. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  36310. /**
  36311. * States if the Primitive is dirty and should be rendered again next time.
  36312. * @returns true is dirty, false otherwise
  36313. */
  36314. get: function () {
  36315. return (this._instanceDirtyFlags !== 0) || this._modelDirty;
  36316. },
  36317. enumerable: true,
  36318. configurable: true
  36319. });
  36320. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  36321. /**
  36322. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  36323. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  36324. */
  36325. get: function () {
  36326. if (!this._propInfo) {
  36327. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  36328. if (!cti) {
  36329. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  36330. }
  36331. this._propInfo = cti.fullContent;
  36332. }
  36333. return this._propInfo;
  36334. },
  36335. enumerable: true,
  36336. configurable: true
  36337. });
  36338. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  36339. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  36340. var node = dic.getLevelOf(target);
  36341. var propInfo = node.levelContent.get(propId.toString());
  36342. if (propInfo) {
  36343. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  36344. }
  36345. // Create, setup and add the PropInfo object to our prop dictionary
  36346. propInfo = new Prim2DPropInfo();
  36347. propInfo.id = propId;
  36348. propInfo.flagId = Math.pow(2, propId);
  36349. propInfo.kind = kind;
  36350. propInfo.name = propName;
  36351. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  36352. propInfo.typeLevelCompare = typeLevelCompare;
  36353. node.levelContent.add(propName, propInfo);
  36354. return propInfo;
  36355. };
  36356. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  36357. // Nothing to nothing: nothing to do!
  36358. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  36359. return true;
  36360. }
  36361. // Check value unchanged
  36362. if ((curValue != null) && (newValue != null)) {
  36363. if (typeof (curValue.equals) == "function") {
  36364. if (curValue.equals(newValue)) {
  36365. return true;
  36366. }
  36367. }
  36368. else {
  36369. if (curValue === newValue) {
  36370. return true;
  36371. }
  36372. }
  36373. }
  36374. return false;
  36375. };
  36376. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  36377. if (this.isDisposed) {
  36378. return;
  36379. }
  36380. var i = propertyName.indexOf(".");
  36381. if (i !== -1) {
  36382. propertyName = propertyName.substr(0, i);
  36383. }
  36384. var propInfo = this.propDic.get(propertyName);
  36385. if (!propInfo) {
  36386. return;
  36387. }
  36388. var newValue = this[propertyName];
  36389. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  36390. };
  36391. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  36392. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  36393. if (propInfo.dirtyBoundingInfo) {
  36394. this._levelBoundingInfoDirty = true;
  36395. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  36396. if (this instanceof BABYLON.Prim2DBase) {
  36397. var curprim = this.parent;
  36398. while (curprim) {
  36399. curprim._boundingInfoDirty = true;
  36400. if (curprim instanceof BABYLON.Group2D) {
  36401. if (curprim.isRenderableGroup) {
  36402. break;
  36403. }
  36404. }
  36405. curprim = curprim.parent;
  36406. }
  36407. }
  36408. }
  36409. // Trigger property changed
  36410. var info = SmartPropertyPrim.propChangedInfo;
  36411. info.oldValue = curValue;
  36412. info.newValue = newValue;
  36413. info.propertyName = propName;
  36414. var propMask = propInfo.flagId;
  36415. this.propertyChanged.notifyObservers(info, propMask);
  36416. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  36417. if (this instanceof BABYLON.Group2D) {
  36418. this.handleGroupChanged(propInfo);
  36419. }
  36420. // Check if we need to dirty only if the type change and make the test
  36421. var skipDirty = false;
  36422. if (typeLevelCompare && curValue != null && newValue != null) {
  36423. var cvProto = curValue.__proto__;
  36424. var nvProto = newValue.__proto__;
  36425. skipDirty = (cvProto === nvProto);
  36426. }
  36427. // Set the dirty flags
  36428. if (!skipDirty) {
  36429. if (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36430. if (!this.isDirty) {
  36431. this.onPrimBecomesDirty();
  36432. }
  36433. this._modelDirty = true;
  36434. }
  36435. else if ((propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  36436. if (!this.isDirty) {
  36437. this.onPrimBecomesDirty();
  36438. }
  36439. this._instanceDirtyFlags |= propMask;
  36440. }
  36441. }
  36442. };
  36443. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  36444. };
  36445. /**
  36446. * Check if a given set of properties are dirty or not.
  36447. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36448. * @return true if at least one property is dirty, false if none of them are.
  36449. */
  36450. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  36451. return (this._instanceDirtyFlags & flags) !== 0;
  36452. };
  36453. /**
  36454. * Clear a given set of properties.
  36455. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36456. * @return the new set of property still marked as dirty
  36457. */
  36458. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  36459. this._instanceDirtyFlags &= ~flags;
  36460. return this._instanceDirtyFlags;
  36461. };
  36462. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  36463. this._instanceDirtyFlags = 0;
  36464. };
  36465. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  36466. /**
  36467. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  36468. * @returns {}
  36469. */
  36470. get: function () {
  36471. if (this._levelBoundingInfoDirty) {
  36472. this.updateLevelBoundingInfo();
  36473. this._levelBoundingInfoDirty = false;
  36474. }
  36475. return this._levelBoundingInfo;
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. /**
  36481. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  36482. */
  36483. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  36484. };
  36485. /**
  36486. * Property method called when the Primitive becomes dirty
  36487. */
  36488. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  36489. };
  36490. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  36491. return function (target, propName, descriptor) {
  36492. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  36493. if (piStore) {
  36494. piStore(propInfo);
  36495. }
  36496. var getter = descriptor.get, setter = descriptor.set;
  36497. // Overload the property setter implementation to add our own logic
  36498. descriptor.set = function (val) {
  36499. // check for disposed first, do nothing
  36500. if (this.isDisposed) {
  36501. return;
  36502. }
  36503. var curVal = getter.call(this);
  36504. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  36505. return;
  36506. }
  36507. // Cast the object we're working one
  36508. var prim = this;
  36509. // Change the value
  36510. setter.call(this, val);
  36511. // Notify change, dirty flags update
  36512. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  36513. };
  36514. };
  36515. };
  36516. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  36517. SmartPropertyPrim = __decorate([
  36518. BABYLON.className("SmartPropertyPrim")
  36519. ], SmartPropertyPrim);
  36520. return SmartPropertyPrim;
  36521. })();
  36522. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  36523. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36524. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36525. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36526. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  36527. }
  36528. BABYLON.modelLevelProperty = modelLevelProperty;
  36529. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36530. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36531. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36532. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  36533. }
  36534. BABYLON.instanceLevelProperty = instanceLevelProperty;
  36535. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36536. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36537. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36538. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  36539. }
  36540. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  36541. })(BABYLON || (BABYLON = {}));
  36542. var BABYLON;
  36543. (function (BABYLON) {
  36544. var PrepareRender2DContext = (function () {
  36545. function PrepareRender2DContext() {
  36546. this.forceRefreshPrimitive = false;
  36547. }
  36548. return PrepareRender2DContext;
  36549. })();
  36550. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  36551. var Render2DContext = (function () {
  36552. function Render2DContext(renderMode) {
  36553. this._renderMode = renderMode;
  36554. this.useInstancing = false;
  36555. this.groupInfoPartData = null;
  36556. this.partDataStartIndex = this.partDataEndIndex = null;
  36557. }
  36558. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  36559. /**
  36560. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  36561. */
  36562. get: function () {
  36563. return this._renderMode;
  36564. },
  36565. enumerable: true,
  36566. configurable: true
  36567. });
  36568. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  36569. /**
  36570. * The set of primitives to render is opaque.
  36571. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  36572. */
  36573. get: function () {
  36574. return Render2DContext._renderModeOpaque;
  36575. },
  36576. enumerable: true,
  36577. configurable: true
  36578. });
  36579. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  36580. /**
  36581. * The set of primitives to render is using Alpha Test (aka masking).
  36582. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  36583. */
  36584. get: function () {
  36585. return Render2DContext._renderModeAlphaTest;
  36586. },
  36587. enumerable: true,
  36588. configurable: true
  36589. });
  36590. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  36591. /**
  36592. * The set of primitives to render is transparent.
  36593. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  36594. */
  36595. get: function () {
  36596. return Render2DContext._renderModeTransparent;
  36597. },
  36598. enumerable: true,
  36599. configurable: true
  36600. });
  36601. Render2DContext._renderModeOpaque = 1;
  36602. Render2DContext._renderModeAlphaTest = 2;
  36603. Render2DContext._renderModeTransparent = 3;
  36604. return Render2DContext;
  36605. })();
  36606. BABYLON.Render2DContext = Render2DContext;
  36607. /**
  36608. * This class store information for the pointerEventObservable Observable.
  36609. * 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.
  36610. */
  36611. var PrimitivePointerInfo = (function () {
  36612. function PrimitivePointerInfo() {
  36613. this.primitivePointerPos = BABYLON.Vector2.Zero();
  36614. this.tilt = BABYLON.Vector2.Zero();
  36615. this.cancelBubble = false;
  36616. }
  36617. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  36618. // 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.
  36619. /**
  36620. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  36621. * Bubbles: yes
  36622. */
  36623. get: function () {
  36624. return PrimitivePointerInfo._pointerOver;
  36625. },
  36626. enumerable: true,
  36627. configurable: true
  36628. });
  36629. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  36630. /**
  36631. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  36632. * Bubbles: no
  36633. */
  36634. get: function () {
  36635. return PrimitivePointerInfo._pointerEnter;
  36636. },
  36637. enumerable: true,
  36638. configurable: true
  36639. });
  36640. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  36641. /**
  36642. * 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.
  36643. * Bubbles: yes
  36644. */
  36645. get: function () {
  36646. return PrimitivePointerInfo._pointerDown;
  36647. },
  36648. enumerable: true,
  36649. configurable: true
  36650. });
  36651. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  36652. /**
  36653. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  36654. * Bubbles: yes
  36655. */
  36656. get: function () {
  36657. return PrimitivePointerInfo._pointerMouseWheel;
  36658. },
  36659. enumerable: true,
  36660. configurable: true
  36661. });
  36662. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  36663. /**
  36664. * 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.
  36665. * Bubbles: yes
  36666. */
  36667. get: function () {
  36668. return PrimitivePointerInfo._pointerMove;
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  36674. /**
  36675. * 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.
  36676. * Bubbles: yes
  36677. */
  36678. get: function () {
  36679. return PrimitivePointerInfo._pointerUp;
  36680. },
  36681. enumerable: true,
  36682. configurable: true
  36683. });
  36684. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  36685. /**
  36686. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  36687. * Bubbles: yes
  36688. */
  36689. get: function () {
  36690. return PrimitivePointerInfo._pointerOut;
  36691. },
  36692. enumerable: true,
  36693. configurable: true
  36694. });
  36695. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  36696. /**
  36697. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  36698. * Bubbles: no
  36699. */
  36700. get: function () {
  36701. return PrimitivePointerInfo._pointerLeave;
  36702. },
  36703. enumerable: true,
  36704. configurable: true
  36705. });
  36706. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  36707. /**
  36708. * 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.
  36709. * Bubbles: yes
  36710. */
  36711. get: function () {
  36712. return PrimitivePointerInfo._pointerGotCapture;
  36713. },
  36714. enumerable: true,
  36715. configurable: true
  36716. });
  36717. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  36718. /**
  36719. * This event type is raised after pointer capture is released for a pointer.
  36720. * Bubbles: yes
  36721. */
  36722. get: function () {
  36723. return PrimitivePointerInfo._pointerLostCapture;
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  36729. get: function () {
  36730. return PrimitivePointerInfo._mouseWheelPrecision;
  36731. },
  36732. enumerable: true,
  36733. configurable: true
  36734. });
  36735. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  36736. this.relatedTarget = prim;
  36737. this.relatedTargetPointerPos = primPointerPos;
  36738. };
  36739. PrimitivePointerInfo.getEventTypeName = function (mask) {
  36740. switch (mask) {
  36741. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  36742. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  36743. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  36744. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  36745. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  36746. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  36747. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  36748. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  36749. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  36750. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  36751. }
  36752. };
  36753. PrimitivePointerInfo._pointerOver = 0x0001;
  36754. PrimitivePointerInfo._pointerEnter = 0x0002;
  36755. PrimitivePointerInfo._pointerDown = 0x0004;
  36756. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  36757. PrimitivePointerInfo._pointerMove = 0x0010;
  36758. PrimitivePointerInfo._pointerUp = 0x0020;
  36759. PrimitivePointerInfo._pointerOut = 0x0040;
  36760. PrimitivePointerInfo._pointerLeave = 0x0080;
  36761. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  36762. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  36763. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  36764. return PrimitivePointerInfo;
  36765. })();
  36766. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  36767. /**
  36768. * Stores information about a Primitive that was intersected
  36769. */
  36770. var PrimitiveIntersectedInfo = (function () {
  36771. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  36772. this.prim = prim;
  36773. this.intersectionLocation = intersectionLocation;
  36774. }
  36775. return PrimitiveIntersectedInfo;
  36776. })();
  36777. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  36778. var PrimitiveMargin = (function () {
  36779. function PrimitiveMargin(owner) {
  36780. this._owner = owner;
  36781. this._left = this._top = this._bottom = this.right = 0;
  36782. }
  36783. Object.defineProperty(PrimitiveMargin.prototype, "top", {
  36784. get: function () {
  36785. return this._top;
  36786. },
  36787. set: function (value) {
  36788. if (value === this._top) {
  36789. return;
  36790. }
  36791. this._top = value;
  36792. this._owner._marginChanged();
  36793. },
  36794. enumerable: true,
  36795. configurable: true
  36796. });
  36797. Object.defineProperty(PrimitiveMargin.prototype, "left", {
  36798. get: function () {
  36799. return this._left;
  36800. },
  36801. set: function (value) {
  36802. if (value === this._left) {
  36803. return;
  36804. }
  36805. this._left = value;
  36806. this._owner._marginChanged();
  36807. },
  36808. enumerable: true,
  36809. configurable: true
  36810. });
  36811. Object.defineProperty(PrimitiveMargin.prototype, "right", {
  36812. get: function () {
  36813. return this._right;
  36814. },
  36815. set: function (value) {
  36816. if (value === this._right) {
  36817. return;
  36818. }
  36819. this._right = value;
  36820. this._owner._marginChanged();
  36821. },
  36822. enumerable: true,
  36823. configurable: true
  36824. });
  36825. Object.defineProperty(PrimitiveMargin.prototype, "bottom", {
  36826. get: function () {
  36827. return this._bottom;
  36828. },
  36829. set: function (value) {
  36830. if (value === this._bottom) {
  36831. return;
  36832. }
  36833. this._bottom = value;
  36834. this._owner._marginChanged();
  36835. },
  36836. enumerable: true,
  36837. configurable: true
  36838. });
  36839. PrimitiveMargin.Zero = function (owner) {
  36840. return new PrimitiveMargin(owner);
  36841. };
  36842. return PrimitiveMargin;
  36843. })();
  36844. BABYLON.PrimitiveMargin = PrimitiveMargin;
  36845. /**
  36846. * Main class used for the Primitive Intersection API
  36847. */
  36848. var IntersectInfo2D = (function () {
  36849. function IntersectInfo2D() {
  36850. this.findFirstOnly = false;
  36851. this.intersectHidden = false;
  36852. this.pickPosition = BABYLON.Vector2.Zero();
  36853. }
  36854. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  36855. /**
  36856. * true if at least one primitive intersected during the test
  36857. */
  36858. get: function () {
  36859. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  36860. },
  36861. enumerable: true,
  36862. configurable: true
  36863. });
  36864. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  36865. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  36866. var cur = _a[_i];
  36867. if (cur.prim === prim) {
  36868. return cur.intersectionLocation;
  36869. }
  36870. }
  36871. return null;
  36872. };
  36873. // Internals, don't use
  36874. IntersectInfo2D.prototype._exit = function (firstLevel) {
  36875. if (firstLevel) {
  36876. this._globalPickPosition = null;
  36877. }
  36878. };
  36879. return IntersectInfo2D;
  36880. })();
  36881. BABYLON.IntersectInfo2D = IntersectInfo2D;
  36882. var Prim2DBase = (function (_super) {
  36883. __extends(Prim2DBase, _super);
  36884. function Prim2DBase() {
  36885. _super.apply(this, arguments);
  36886. }
  36887. Object.defineProperty(Prim2DBase, "HAlignLeft", {
  36888. get: function () { return Prim2DBase._hAlignLeft; },
  36889. enumerable: true,
  36890. configurable: true
  36891. });
  36892. Object.defineProperty(Prim2DBase, "HAlignCenter", {
  36893. get: function () { return Prim2DBase._hAlignCenter; },
  36894. enumerable: true,
  36895. configurable: true
  36896. });
  36897. Object.defineProperty(Prim2DBase, "HAlignRight", {
  36898. get: function () { return Prim2DBase._hAlignRight; },
  36899. enumerable: true,
  36900. configurable: true
  36901. });
  36902. Object.defineProperty(Prim2DBase, "HAlignStretch", {
  36903. get: function () { return Prim2DBase._hAlignStretch; },
  36904. enumerable: true,
  36905. configurable: true
  36906. });
  36907. Object.defineProperty(Prim2DBase, "VAlignTop", {
  36908. get: function () { return Prim2DBase._vAlignTop; },
  36909. enumerable: true,
  36910. configurable: true
  36911. });
  36912. Object.defineProperty(Prim2DBase, "VAlignCenter", {
  36913. get: function () { return Prim2DBase._vAlignCenter; },
  36914. enumerable: true,
  36915. configurable: true
  36916. });
  36917. Object.defineProperty(Prim2DBase, "VAlignBottom", {
  36918. get: function () { return Prim2DBase._vAlignBottom; },
  36919. enumerable: true,
  36920. configurable: true
  36921. });
  36922. Object.defineProperty(Prim2DBase, "VAlignStretch", {
  36923. get: function () { return Prim2DBase._vAlignStretch; },
  36924. enumerable: true,
  36925. configurable: true
  36926. });
  36927. Prim2DBase.prototype.setupPrim2DBase = function (owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  36928. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && id !== null && id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  36929. 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");
  36930. }
  36931. var m = null;
  36932. if (marginTop || marginLeft || marginRight || marginBottom) {
  36933. m = new PrimitiveMargin(this);
  36934. m.top = marginTop || 0;
  36935. m.left = marginLeft || 0;
  36936. m.right = marginRight || 0;
  36937. m.bottom = marginBottom || 0;
  36938. }
  36939. this.setupSmartPropertyPrim();
  36940. this._pointerEventObservable = new BABYLON.Observable();
  36941. this._isPickable = true;
  36942. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  36943. this._boundingInfoDirty = true;
  36944. this._boundingInfo = new BABYLON.BoundingInfo2D();
  36945. this._owner = owner;
  36946. this._parent = parent;
  36947. this._id = id;
  36948. if (parent != null) {
  36949. this._hierarchyDepth = parent._hierarchyDepth + 1;
  36950. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  36951. parent.addChild(this);
  36952. }
  36953. else {
  36954. this._hierarchyDepth = 0;
  36955. this._renderGroup = null;
  36956. }
  36957. this.propertyChanged = new BABYLON.Observable();
  36958. this._children = new Array();
  36959. this._globalTransformProcessStep = 0;
  36960. this._globalTransformStep = 0;
  36961. if (this instanceof BABYLON.Group2D) {
  36962. var group = this;
  36963. group.detectGroupStates();
  36964. }
  36965. this.position = position;
  36966. this.rotation = 0;
  36967. this.scale = 1;
  36968. this.levelVisible = isVisible;
  36969. this.origin = origin || new BABYLON.Vector2(0.5, 0.5);
  36970. this.margin = m;
  36971. this.hAlignment = hAlignment;
  36972. this.vAlignment = vAlignment;
  36973. };
  36974. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  36975. get: function () {
  36976. if (!this._actionManager) {
  36977. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  36978. }
  36979. return this._actionManager;
  36980. },
  36981. enumerable: true,
  36982. configurable: true
  36983. });
  36984. /**
  36985. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  36986. * @param predicate the predicate to test on each parent
  36987. * @return the first primitive where the predicate was successful
  36988. */
  36989. Prim2DBase.prototype.traverseUp = function (predicate) {
  36990. var p = this;
  36991. while (p != null) {
  36992. if (predicate(p)) {
  36993. return p;
  36994. }
  36995. p = p._parent;
  36996. }
  36997. return null;
  36998. };
  36999. Object.defineProperty(Prim2DBase.prototype, "owner", {
  37000. /**
  37001. * Retrieve the owner Canvas2D
  37002. */
  37003. get: function () {
  37004. return this._owner;
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. Object.defineProperty(Prim2DBase.prototype, "parent", {
  37010. /**
  37011. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  37012. */
  37013. get: function () {
  37014. return this._parent;
  37015. },
  37016. enumerable: true,
  37017. configurable: true
  37018. });
  37019. Object.defineProperty(Prim2DBase.prototype, "children", {
  37020. /**
  37021. * The array of direct children primitives
  37022. */
  37023. get: function () {
  37024. return this._children;
  37025. },
  37026. enumerable: true,
  37027. configurable: true
  37028. });
  37029. Object.defineProperty(Prim2DBase.prototype, "id", {
  37030. /**
  37031. * The identifier of this primitive, may not be unique, it's for information purpose only
  37032. */
  37033. get: function () {
  37034. return this._id;
  37035. },
  37036. enumerable: true,
  37037. configurable: true
  37038. });
  37039. Object.defineProperty(Prim2DBase.prototype, "position", {
  37040. get: function () {
  37041. return this._position;
  37042. },
  37043. set: function (value) {
  37044. this._position = value;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  37050. get: function () {
  37051. return this._rotation;
  37052. },
  37053. set: function (value) {
  37054. this._rotation = value;
  37055. },
  37056. enumerable: true,
  37057. configurable: true
  37058. });
  37059. Object.defineProperty(Prim2DBase.prototype, "scale", {
  37060. get: function () {
  37061. return this._scale;
  37062. },
  37063. set: function (value) {
  37064. this._scale = value;
  37065. },
  37066. enumerable: true,
  37067. configurable: true
  37068. });
  37069. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  37070. /**
  37071. * this method must be implemented by the primitive type to return its size
  37072. * @returns The size of the primitive
  37073. */
  37074. get: function () {
  37075. return undefined;
  37076. },
  37077. enumerable: true,
  37078. configurable: true
  37079. });
  37080. Object.defineProperty(Prim2DBase.prototype, "origin", {
  37081. /**
  37082. * The origin defines the normalized coordinate of the center of the primitive, from the top/left corner.
  37083. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  37084. * For instance:
  37085. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  37086. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  37087. * 0,1 means the center is top/left
  37088. * @returns The normalized center.
  37089. */
  37090. get: function () {
  37091. return this._origin;
  37092. },
  37093. set: function (value) {
  37094. this._origin = value;
  37095. },
  37096. enumerable: true,
  37097. configurable: true
  37098. });
  37099. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  37100. get: function () {
  37101. return this._levelVisible;
  37102. },
  37103. set: function (value) {
  37104. this._levelVisible = value;
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  37110. get: function () {
  37111. return this._isVisible;
  37112. },
  37113. set: function (value) {
  37114. this._isVisible = value;
  37115. },
  37116. enumerable: true,
  37117. configurable: true
  37118. });
  37119. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  37120. get: function () {
  37121. return this._zOrder;
  37122. },
  37123. set: function (value) {
  37124. this._zOrder = value;
  37125. this.onZOrderChanged();
  37126. },
  37127. enumerable: true,
  37128. configurable: true
  37129. });
  37130. Object.defineProperty(Prim2DBase.prototype, "margin", {
  37131. get: function () {
  37132. if (!this._margin) {
  37133. this._margin = new PrimitiveMargin(this);
  37134. }
  37135. return this._margin;
  37136. },
  37137. set: function (value) {
  37138. this._margin = value;
  37139. },
  37140. enumerable: true,
  37141. configurable: true
  37142. });
  37143. Object.defineProperty(Prim2DBase.prototype, "hAlignment", {
  37144. get: function () {
  37145. return this._hAlignment;
  37146. },
  37147. set: function (value) {
  37148. this._hAlignment = value;
  37149. },
  37150. enumerable: true,
  37151. configurable: true
  37152. });
  37153. Object.defineProperty(Prim2DBase.prototype, "vAlignment", {
  37154. get: function () {
  37155. return this._vAlignment;
  37156. },
  37157. set: function (value) {
  37158. this._vAlignment = value;
  37159. },
  37160. enumerable: true,
  37161. configurable: true
  37162. });
  37163. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  37164. /**
  37165. * Define if the Primitive can be subject to intersection test or not (default is true)
  37166. */
  37167. get: function () {
  37168. return this._isPickable;
  37169. },
  37170. set: function (value) {
  37171. this._isPickable = value;
  37172. },
  37173. enumerable: true,
  37174. configurable: true
  37175. });
  37176. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  37177. /**
  37178. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  37179. * @returns {}
  37180. */
  37181. get: function () {
  37182. return this._hierarchyDepth;
  37183. },
  37184. enumerable: true,
  37185. configurable: true
  37186. });
  37187. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  37188. /**
  37189. * Retrieve the Group that is responsible to render this primitive
  37190. * @returns {}
  37191. */
  37192. get: function () {
  37193. return this._renderGroup;
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  37199. /**
  37200. * Get the global transformation matrix of the primitive
  37201. */
  37202. get: function () {
  37203. return this._globalTransform;
  37204. },
  37205. enumerable: true,
  37206. configurable: true
  37207. });
  37208. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  37209. /**
  37210. * Get invert of the global transformation matrix of the primitive
  37211. * @returns {}
  37212. */
  37213. get: function () {
  37214. return this._invGlobalTransform;
  37215. },
  37216. enumerable: true,
  37217. configurable: true
  37218. });
  37219. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  37220. /**
  37221. * Get the local transformation of the primitive
  37222. */
  37223. get: function () {
  37224. this._updateLocalTransform();
  37225. return this._localTransform;
  37226. },
  37227. enumerable: true,
  37228. configurable: true
  37229. });
  37230. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  37231. /**
  37232. * Get the boundingInfo associated to the primitive and its children.
  37233. * The value is supposed to be always up to date
  37234. */
  37235. get: function () {
  37236. if (this._boundingInfoDirty) {
  37237. this._boundingInfo = this.levelBoundingInfo.clone();
  37238. var bi = this._boundingInfo;
  37239. var tps = new BABYLON.BoundingInfo2D();
  37240. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  37241. var curChild = _a[_i];
  37242. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  37243. bi.unionToRef(tps, bi);
  37244. }
  37245. this._boundingInfoDirty = false;
  37246. }
  37247. return this._boundingInfo;
  37248. },
  37249. enumerable: true,
  37250. configurable: true
  37251. });
  37252. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  37253. /**
  37254. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  37255. */
  37256. get: function () {
  37257. return this._pointerEventObservable;
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. Prim2DBase.prototype.onZOrderChanged = function () {
  37263. };
  37264. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  37265. return false;
  37266. };
  37267. /**
  37268. * Capture all the Events of the given PointerId for this primitive.
  37269. * Don't forget to call releasePointerEventsCapture when done.
  37270. * @param pointerId the Id of the pointer to capture the events from.
  37271. */
  37272. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  37273. return this.owner._setPointerCapture(pointerId, this);
  37274. };
  37275. /**
  37276. * Release a captured pointer made with setPointerEventCapture.
  37277. * @param pointerId the Id of the pointer to release the capture from.
  37278. */
  37279. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  37280. return this.owner._releasePointerCapture(pointerId, this);
  37281. };
  37282. /**
  37283. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  37284. * @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.
  37285. */
  37286. Prim2DBase.prototype.intersect = function (intersectInfo) {
  37287. if (!intersectInfo) {
  37288. return false;
  37289. }
  37290. // If this is null it means this method is call for the first level, initialize stuffs
  37291. var firstLevel = !intersectInfo._globalPickPosition;
  37292. if (firstLevel) {
  37293. // 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).
  37294. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  37295. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  37296. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  37297. intersectInfo.intersectedPrimitives = new Array();
  37298. intersectInfo.topMostIntersectedPrimitive = null;
  37299. }
  37300. if (!intersectInfo.intersectHidden && !this.isVisible) {
  37301. return false;
  37302. }
  37303. // Fast rejection test with boundingInfo
  37304. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  37305. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  37306. intersectInfo._exit(firstLevel);
  37307. return false;
  37308. }
  37309. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  37310. var levelIntersectRes = false;
  37311. if (this.isPickable) {
  37312. levelIntersectRes = this.levelIntersect(intersectInfo);
  37313. if (levelIntersectRes) {
  37314. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  37315. intersectInfo.intersectedPrimitives.push(pii);
  37316. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.getActualZOffset() > pii.prim.getActualZOffset())) {
  37317. intersectInfo.topMostIntersectedPrimitive = pii;
  37318. }
  37319. // If we must stop at the first intersection, we're done, quit!
  37320. if (intersectInfo.findFirstOnly) {
  37321. intersectInfo._exit(firstLevel);
  37322. return true;
  37323. }
  37324. }
  37325. }
  37326. // Recurse to children if needed
  37327. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  37328. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  37329. var curChild = _a[_i];
  37330. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  37331. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  37332. continue;
  37333. }
  37334. // Must compute the localPickLocation for the children level
  37335. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  37336. // If we got an intersection with the child and we only need to find the first one, quit!
  37337. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  37338. intersectInfo._exit(firstLevel);
  37339. return true;
  37340. }
  37341. }
  37342. }
  37343. intersectInfo._exit(firstLevel);
  37344. return intersectInfo.isIntersected;
  37345. };
  37346. Prim2DBase.prototype.moveChild = function (child, previous) {
  37347. if (child.parent !== this) {
  37348. return false;
  37349. }
  37350. var prevOffset, nextOffset;
  37351. var childIndex = this._children.indexOf(child);
  37352. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  37353. // Move to first position
  37354. if (!previous) {
  37355. prevOffset = 1;
  37356. nextOffset = this._children[1]._siblingDepthOffset;
  37357. }
  37358. else {
  37359. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  37360. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  37361. }
  37362. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  37363. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  37364. };
  37365. Prim2DBase.prototype.addChild = function (child) {
  37366. child._hierarchyDepthOffset = this._hierarchyDepthOffset + ((this._children.length + 1) * this._siblingDepthOffset);
  37367. // console.log(`Node: ${child.id} has depth: ${child._hierarchyDepthOffset}`);
  37368. child._siblingDepthOffset = this._siblingDepthOffset / this.owner.hierarchyLevelMaxSiblingCount;
  37369. this._children.push(child);
  37370. };
  37371. Prim2DBase.prototype.dispose = function () {
  37372. if (!_super.prototype.dispose.call(this)) {
  37373. return false;
  37374. }
  37375. if (this._actionManager) {
  37376. this._actionManager.dispose();
  37377. this._actionManager = null;
  37378. }
  37379. // If there's a parent, remove this object from its parent list
  37380. if (this._parent) {
  37381. var i = this._parent._children.indexOf(this);
  37382. if (i !== undefined) {
  37383. this._parent._children.splice(i, 1);
  37384. }
  37385. this._parent = null;
  37386. }
  37387. // Recurse dispose to children
  37388. if (this._children) {
  37389. while (this._children.length > 0) {
  37390. this._children[this._children.length - 1].dispose();
  37391. }
  37392. }
  37393. return true;
  37394. };
  37395. Prim2DBase.prototype.getActualZOffset = function () {
  37396. return this._zOrder || (1 - this._hierarchyDepthOffset);
  37397. };
  37398. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  37399. if (this._renderGroup) {
  37400. this._renderGroup._addPrimToDirtyList(this);
  37401. }
  37402. };
  37403. Prim2DBase.prototype._marginChanged = function () {
  37404. };
  37405. Prim2DBase.prototype._needPrepare = function () {
  37406. return this._visibilityChanged || this._modelDirty || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  37407. };
  37408. Prim2DBase.prototype._prepareRender = function (context) {
  37409. this._prepareRenderPre(context);
  37410. this._prepareRenderPost(context);
  37411. };
  37412. Prim2DBase.prototype._prepareRenderPre = function (context) {
  37413. };
  37414. Prim2DBase.prototype._prepareRenderPost = function (context) {
  37415. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  37416. if (this instanceof BABYLON.Group2D) {
  37417. var self = this;
  37418. if (self.isRenderableGroup) {
  37419. return;
  37420. }
  37421. }
  37422. // Check if we need to recurse the prepare to children primitives
  37423. // - must have children
  37424. // - the global transform of this level have changed, or
  37425. // - the visible state of primitive has changed
  37426. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  37427. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  37428. this._children.forEach(function (c) {
  37429. // As usual stop the recursion if we meet a renderable group
  37430. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  37431. c._prepareRender(context);
  37432. }
  37433. });
  37434. }
  37435. // Finally reset the dirty flags as we've processed everything
  37436. this._modelDirty = false;
  37437. this._instanceDirtyFlags = 0;
  37438. };
  37439. Prim2DBase.CheckParent = function (parent) {
  37440. if (!parent) {
  37441. 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)");
  37442. }
  37443. };
  37444. Prim2DBase.prototype.updateGlobalTransVisOf = function (list, recurse) {
  37445. for (var _i = 0; _i < list.length; _i++) {
  37446. var cur = list[_i];
  37447. cur.updateGlobalTransVis(recurse);
  37448. }
  37449. };
  37450. Prim2DBase.prototype._updateLocalTransform = function () {
  37451. var tflags = Prim2DBase.positionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId;
  37452. if (this.checkPropertiesDirty(tflags)) {
  37453. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  37454. 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));
  37455. this._localTransform = local;
  37456. this.clearPropertiesDirty(tflags);
  37457. // 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
  37458. //var actualSize = this.actualSize;
  37459. //if (!actualSize) {
  37460. // throw new Error(`The primitive type: ${Tools.getClassName(this)} must implement the actualSize get property!`);
  37461. //}
  37462. //local.m[12] -= (actualSize.width * this.origin.x) * local.m[0] + (actualSize.height * this.origin.y) * local.m[4];
  37463. //local.m[13] -= (actualSize.width * this.origin.x) * local.m[1] + (actualSize.height * this.origin.y) * local.m[5];
  37464. return true;
  37465. }
  37466. return false;
  37467. };
  37468. Prim2DBase.prototype.updateGlobalTransVis = function (recurse) {
  37469. if (this.isDisposed) {
  37470. return;
  37471. }
  37472. // Check if the parent is synced
  37473. if (this._parent && this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  37474. this._parent.updateGlobalTransVis(false);
  37475. }
  37476. // Check if we must update this prim
  37477. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  37478. var curVisibleState = this.isVisible;
  37479. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  37480. // Detect a change of visibility
  37481. this._visibilityChanged = curVisibleState !== this.isVisible;
  37482. // Get/compute the localTransform
  37483. var localDirty = this._updateLocalTransform();
  37484. // Check if we have to update the globalTransform
  37485. if (!this._globalTransform || localDirty || (this._parent && this._parent._globalTransformStep !== this._parentTransformStep)) {
  37486. this._globalTransform = this._parent ? this._localTransform.multiply(this._parent._globalTransform) : this._localTransform;
  37487. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  37488. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  37489. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  37490. }
  37491. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  37492. }
  37493. if (recurse) {
  37494. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  37495. var child = _a[_i];
  37496. // Stop the recursion if we meet a renderable group
  37497. child.updateGlobalTransVis(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  37498. }
  37499. }
  37500. };
  37501. Prim2DBase.PRIM2DBASE_PROPCOUNT = 12;
  37502. Prim2DBase._hAlignLeft = 1;
  37503. Prim2DBase._hAlignCenter = 2;
  37504. Prim2DBase._hAlignRight = 3;
  37505. Prim2DBase._hAlignStretch = 4;
  37506. Prim2DBase._vAlignTop = 1;
  37507. Prim2DBase._vAlignCenter = 2;
  37508. Prim2DBase._vAlignBottom = 3;
  37509. Prim2DBase._vAlignStretch = 4;
  37510. __decorate([
  37511. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  37512. ], Prim2DBase.prototype, "position", null);
  37513. __decorate([
  37514. BABYLON.instanceLevelProperty(2, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  37515. ], Prim2DBase.prototype, "rotation", null);
  37516. __decorate([
  37517. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  37518. ], Prim2DBase.prototype, "scale", null);
  37519. __decorate([
  37520. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  37521. ], Prim2DBase.prototype, "origin", null);
  37522. __decorate([
  37523. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  37524. ], Prim2DBase.prototype, "levelVisible", null);
  37525. __decorate([
  37526. BABYLON.instanceLevelProperty(6, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  37527. ], Prim2DBase.prototype, "isVisible", null);
  37528. __decorate([
  37529. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  37530. ], Prim2DBase.prototype, "zOrder", null);
  37531. __decorate([
  37532. BABYLON.dynamicLevelProperty(8, function (pi) { return Prim2DBase.marginProperty = pi; })
  37533. ], Prim2DBase.prototype, "margin", null);
  37534. __decorate([
  37535. BABYLON.dynamicLevelProperty(9, function (pi) { return Prim2DBase.hAlignmentProperty = pi; })
  37536. ], Prim2DBase.prototype, "hAlignment", null);
  37537. __decorate([
  37538. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.vAlignmentProperty = pi; })
  37539. ], Prim2DBase.prototype, "vAlignment", null);
  37540. Prim2DBase = __decorate([
  37541. BABYLON.className("Prim2DBase")
  37542. ], Prim2DBase);
  37543. return Prim2DBase;
  37544. })(BABYLON.SmartPropertyPrim);
  37545. BABYLON.Prim2DBase = Prim2DBase;
  37546. })(BABYLON || (BABYLON = {}));
  37547. var BABYLON;
  37548. (function (BABYLON) {
  37549. var GroupInstanceInfo = (function () {
  37550. function GroupInstanceInfo(owner, mrc, partCount) {
  37551. this._partCount = partCount;
  37552. this.owner = owner;
  37553. this.modelRenderCache = mrc;
  37554. this.modelRenderCache.addRef();
  37555. this.partIndexFromId = new BABYLON.StringDictionary();
  37556. this._usedShaderCategories = new Array(partCount);
  37557. this._strides = new Array(partCount);
  37558. this._opaqueData = null;
  37559. this._alphaTestData = null;
  37560. this._transparentData = null;
  37561. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  37562. }
  37563. GroupInstanceInfo.prototype.dispose = function () {
  37564. if (this._isDisposed) {
  37565. return false;
  37566. }
  37567. if (this.modelRenderCache) {
  37568. this.modelRenderCache.dispose();
  37569. }
  37570. var engine = this.owner.owner.engine;
  37571. if (this.opaqueData) {
  37572. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  37573. this.opaqueData = null;
  37574. }
  37575. this.partIndexFromId = null;
  37576. this._isDisposed = true;
  37577. return true;
  37578. };
  37579. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  37580. get: function () {
  37581. return this._opaqueData != null;
  37582. },
  37583. enumerable: true,
  37584. configurable: true
  37585. });
  37586. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  37587. get: function () {
  37588. return this._alphaTestData != null;
  37589. },
  37590. enumerable: true,
  37591. configurable: true
  37592. });
  37593. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  37594. get: function () {
  37595. return this._transparentData != null;
  37596. },
  37597. enumerable: true,
  37598. configurable: true
  37599. });
  37600. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  37601. get: function () {
  37602. if (!this._opaqueData) {
  37603. this._opaqueData = new Array(this._partCount);
  37604. for (var i = 0; i < this._partCount; i++) {
  37605. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  37606. }
  37607. }
  37608. return this._opaqueData;
  37609. },
  37610. enumerable: true,
  37611. configurable: true
  37612. });
  37613. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  37614. get: function () {
  37615. if (!this._alphaTestData) {
  37616. this._alphaTestData = new Array(this._partCount);
  37617. for (var i = 0; i < this._partCount; i++) {
  37618. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  37619. }
  37620. }
  37621. return this._alphaTestData;
  37622. },
  37623. enumerable: true,
  37624. configurable: true
  37625. });
  37626. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  37627. get: function () {
  37628. if (!this._transparentData) {
  37629. this._transparentData = new Array(this._partCount);
  37630. for (var i = 0; i < this._partCount; i++) {
  37631. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  37632. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  37633. }
  37634. }
  37635. return this._transparentData;
  37636. },
  37637. enumerable: true,
  37638. configurable: true
  37639. });
  37640. GroupInstanceInfo.prototype.sortTransparentData = function () {
  37641. if (!this.transparentOrderDirty) {
  37642. return;
  37643. }
  37644. for (var i = 0; i < this._transparentData.length; i++) {
  37645. var td = this._transparentData[i];
  37646. td._partData.sort();
  37647. }
  37648. this.transparentOrderDirty = false;
  37649. };
  37650. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  37651. get: function () {
  37652. return this._usedShaderCategories;
  37653. },
  37654. enumerable: true,
  37655. configurable: true
  37656. });
  37657. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  37658. get: function () {
  37659. return this._strides;
  37660. },
  37661. enumerable: true,
  37662. configurable: true
  37663. });
  37664. return GroupInstanceInfo;
  37665. })();
  37666. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  37667. var TransparentSegment = (function () {
  37668. function TransparentSegment() {
  37669. }
  37670. return TransparentSegment;
  37671. })();
  37672. BABYLON.TransparentSegment = TransparentSegment;
  37673. var GroupInfoPartData = (function () {
  37674. function GroupInfoPartData(stride) {
  37675. this._partData = null;
  37676. this._partBuffer = null;
  37677. this._partBufferSize = 0;
  37678. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  37679. this._isDisposed = false;
  37680. }
  37681. GroupInfoPartData.prototype.dispose = function (engine) {
  37682. if (this._isDisposed) {
  37683. return false;
  37684. }
  37685. if (this._partBuffer) {
  37686. engine._releaseBuffer(this._partBuffer);
  37687. this._partBuffer = null;
  37688. }
  37689. this._partData = null;
  37690. this._isDisposed = true;
  37691. };
  37692. return GroupInfoPartData;
  37693. })();
  37694. BABYLON.GroupInfoPartData = GroupInfoPartData;
  37695. var TransparentGroupInfoPartData = (function (_super) {
  37696. __extends(TransparentGroupInfoPartData, _super);
  37697. function TransparentGroupInfoPartData(stride, zoff) {
  37698. _super.call(this, stride);
  37699. this._partData.compareValueOffset = zoff;
  37700. this._partData.sortingAscending = false;
  37701. }
  37702. return TransparentGroupInfoPartData;
  37703. })(GroupInfoPartData);
  37704. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  37705. var ModelRenderCache = (function () {
  37706. function ModelRenderCache(engine, modelKey) {
  37707. this._engine = engine;
  37708. this._modelKey = modelKey;
  37709. this._nextKey = 1;
  37710. this._refCounter = 1;
  37711. this._instancesData = new BABYLON.StringDictionary();
  37712. this._partData = null;
  37713. }
  37714. ModelRenderCache.prototype.dispose = function () {
  37715. if (--this._refCounter !== 0) {
  37716. return false;
  37717. }
  37718. // Remove the Model Render Cache from the global dictionary
  37719. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  37720. if (edata) {
  37721. edata.DisposeModelRenderCache(this);
  37722. }
  37723. return true;
  37724. };
  37725. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  37726. get: function () {
  37727. return this._refCounter <= 0;
  37728. },
  37729. enumerable: true,
  37730. configurable: true
  37731. });
  37732. ModelRenderCache.prototype.addRef = function () {
  37733. return ++this._refCounter;
  37734. };
  37735. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  37736. get: function () {
  37737. return this._modelKey;
  37738. },
  37739. enumerable: true,
  37740. configurable: true
  37741. });
  37742. /**
  37743. * Render the model instances
  37744. * @param instanceInfo
  37745. * @param context
  37746. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  37747. */
  37748. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  37749. return true;
  37750. };
  37751. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  37752. var key = this._nextKey.toString();
  37753. if (!this._instancesData.add(key, data)) {
  37754. throw Error("Key: " + key + " is already allocated");
  37755. }
  37756. ++this._nextKey;
  37757. return key;
  37758. };
  37759. ModelRenderCache.prototype.removeInstanceData = function (key) {
  37760. this._instancesData.remove(key);
  37761. };
  37762. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  37763. for (var i = 0; i < this._partData.length; i++) {
  37764. if (this._partData[i]._partId === partId) {
  37765. return i;
  37766. }
  37767. }
  37768. return null;
  37769. };
  37770. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  37771. var i = this.getPartIndexFromId(partId);
  37772. if (i === null) {
  37773. return null;
  37774. }
  37775. var ci = this._partsClassInfo[i];
  37776. var categories = this._partData[i]._partUsedCategories;
  37777. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  37778. return res;
  37779. };
  37780. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  37781. var pd = this._partData[partIndex];
  37782. var offset = (pd._partDataStride / 4) * elementCount;
  37783. var pci = this._partsClassInfo[partIndex];
  37784. var self = this;
  37785. pci.fullContent.forEach(function (k, v) {
  37786. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  37787. switch (v.dataType) {
  37788. case 4 /* float */:
  37789. {
  37790. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  37791. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  37792. break;
  37793. }
  37794. case 0 /* Vector2 */:
  37795. {
  37796. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  37797. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  37798. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  37799. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  37800. break;
  37801. }
  37802. case 5 /* Color3 */:
  37803. case 1 /* Vector3 */:
  37804. {
  37805. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  37806. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  37807. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  37808. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  37809. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  37810. break;
  37811. }
  37812. case 6 /* Color4 */:
  37813. case 2 /* Vector4 */:
  37814. {
  37815. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  37816. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  37817. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  37818. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  37819. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  37820. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  37821. break;
  37822. }
  37823. default:
  37824. }
  37825. }
  37826. });
  37827. };
  37828. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  37829. // let i = this.getPartIndexFromId(partId);
  37830. // if (i === null) {
  37831. // return null;
  37832. // }
  37833. // let pci = this._partsClassInfo[i];
  37834. // pci.fullContent.forEach((k, v) => {
  37835. // if (uniforms.indexOf(v.attributeName) !== -1) {
  37836. // v.uniformLocation = effect.getUniform(v.attributeName);
  37837. // }
  37838. // });
  37839. //}
  37840. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  37841. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  37842. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  37843. return ModelRenderCache;
  37844. })();
  37845. BABYLON.ModelRenderCache = ModelRenderCache;
  37846. var ModelRenderCachePartData = (function () {
  37847. function ModelRenderCachePartData() {
  37848. }
  37849. return ModelRenderCachePartData;
  37850. })();
  37851. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  37852. })(BABYLON || (BABYLON = {}));
  37853. var BABYLON;
  37854. (function (BABYLON) {
  37855. var InstanceClassInfo = (function () {
  37856. function InstanceClassInfo(base) {
  37857. this._baseInfo = base;
  37858. this._nextOffset = new BABYLON.StringDictionary();
  37859. this._attributes = new Array();
  37860. }
  37861. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  37862. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  37863. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  37864. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  37865. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  37866. if (push) {
  37867. this._attributes.push(propInfo);
  37868. }
  37869. };
  37870. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  37871. var catInline = ";" + categories.join(";") + ";";
  37872. var res = new Array();
  37873. var curInfo = this;
  37874. while (curInfo) {
  37875. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37876. var attrib = _a[_i];
  37877. // 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
  37878. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37879. var index = effect.getAttributeLocationByName(attrib.attributeName);
  37880. var iai = new BABYLON.InstancingAttributeInfo();
  37881. iai.index = index;
  37882. 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)
  37883. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  37884. iai.attributeName = attrib.attributeName;
  37885. res.push(iai);
  37886. }
  37887. }
  37888. curInfo = curInfo._baseInfo;
  37889. }
  37890. return res;
  37891. };
  37892. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  37893. var res = new Array();
  37894. var curInfo = this;
  37895. while (curInfo) {
  37896. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37897. var attrib = _a[_i];
  37898. // 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
  37899. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37900. res.push(attrib.attributeName);
  37901. }
  37902. }
  37903. curInfo = curInfo._baseInfo;
  37904. }
  37905. return res;
  37906. };
  37907. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  37908. var curOffset = 0;
  37909. var curBase = this._baseInfo;
  37910. while (curBase) {
  37911. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  37912. curBase = curBase._baseInfo;
  37913. }
  37914. return curOffset;
  37915. };
  37916. return InstanceClassInfo;
  37917. })();
  37918. BABYLON.InstanceClassInfo = InstanceClassInfo;
  37919. var InstancePropInfo = (function () {
  37920. function InstancePropInfo() {
  37921. this.instanceOffset = new BABYLON.StringDictionary();
  37922. }
  37923. InstancePropInfo.prototype.setSize = function (val) {
  37924. if (val instanceof BABYLON.Vector2) {
  37925. this.size = 8;
  37926. this.dataType = 0 /* Vector2 */;
  37927. return;
  37928. }
  37929. if (val instanceof BABYLON.Vector3) {
  37930. this.size = 12;
  37931. this.dataType = 1 /* Vector3 */;
  37932. return;
  37933. }
  37934. if (val instanceof BABYLON.Vector4) {
  37935. this.size = 16;
  37936. this.dataType = 2 /* Vector4 */;
  37937. return;
  37938. }
  37939. if (val instanceof BABYLON.Matrix) {
  37940. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  37941. }
  37942. if (typeof (val) === "number") {
  37943. this.size = 4;
  37944. this.dataType = 4 /* float */;
  37945. return;
  37946. }
  37947. if (val instanceof BABYLON.Color3) {
  37948. this.size = 12;
  37949. this.dataType = 5 /* Color3 */;
  37950. return;
  37951. }
  37952. if (val instanceof BABYLON.Color4) {
  37953. this.size = 16;
  37954. this.dataType = 6 /* Color4 */;
  37955. return;
  37956. }
  37957. if (val instanceof BABYLON.Size) {
  37958. this.size = 8;
  37959. this.dataType = 7 /* Size */;
  37960. return;
  37961. }
  37962. return;
  37963. };
  37964. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  37965. switch (this.dataType) {
  37966. case 0 /* Vector2 */:
  37967. {
  37968. var v = val;
  37969. array[offset + 0] = v.x;
  37970. array[offset + 1] = v.y;
  37971. break;
  37972. }
  37973. case 1 /* Vector3 */:
  37974. {
  37975. var v = val;
  37976. array[offset + 0] = v.x;
  37977. array[offset + 1] = v.y;
  37978. array[offset + 2] = v.z;
  37979. break;
  37980. }
  37981. case 2 /* Vector4 */:
  37982. {
  37983. var v = val;
  37984. array[offset + 0] = v.x;
  37985. array[offset + 1] = v.y;
  37986. array[offset + 2] = v.z;
  37987. array[offset + 3] = v.w;
  37988. break;
  37989. }
  37990. case 5 /* Color3 */:
  37991. {
  37992. var v = val;
  37993. array[offset + 0] = v.r;
  37994. array[offset + 1] = v.g;
  37995. array[offset + 2] = v.b;
  37996. break;
  37997. }
  37998. case 6 /* Color4 */:
  37999. {
  38000. var v = val;
  38001. array[offset + 0] = v.r;
  38002. array[offset + 1] = v.g;
  38003. array[offset + 2] = v.b;
  38004. array[offset + 3] = v.a;
  38005. break;
  38006. }
  38007. case 4 /* float */:
  38008. {
  38009. var v = val;
  38010. array[offset] = v;
  38011. break;
  38012. }
  38013. case 3 /* Matrix */:
  38014. {
  38015. var v = val;
  38016. for (var i = 0; i < 16; i++) {
  38017. array[offset + i] = v.m[i];
  38018. }
  38019. break;
  38020. }
  38021. case 7 /* Size */:
  38022. {
  38023. var s = val;
  38024. array[offset + 0] = s.width;
  38025. array[offset + 1] = s.height;
  38026. break;
  38027. }
  38028. }
  38029. };
  38030. return InstancePropInfo;
  38031. })();
  38032. BABYLON.InstancePropInfo = InstancePropInfo;
  38033. function instanceData(category, shaderAttributeName) {
  38034. return function (target, propName, descriptor) {
  38035. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  38036. var node = dic.getLevelOf(target);
  38037. var instanceDataName = propName;
  38038. shaderAttributeName = shaderAttributeName || instanceDataName;
  38039. var info = node.levelContent.get(instanceDataName);
  38040. if (info) {
  38041. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  38042. }
  38043. info = new InstancePropInfo();
  38044. info.attributeName = shaderAttributeName;
  38045. info.category = category || null;
  38046. if (info.category) {
  38047. info.delimitedCategory = ";" + info.category + ";";
  38048. }
  38049. node.levelContent.add(instanceDataName, info);
  38050. descriptor.get = function () {
  38051. return null;
  38052. };
  38053. descriptor.set = function (val) {
  38054. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  38055. // Quit if it's the case, otherwise we could overwrite data somewhere...
  38056. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  38057. return;
  38058. }
  38059. if (!info.size) {
  38060. info.setSize(val);
  38061. node.classContent.mapProperty(info, true);
  38062. }
  38063. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  38064. node.classContent.mapProperty(info, false);
  38065. }
  38066. var obj = this;
  38067. if (obj.dataBuffer && obj.dataElements) {
  38068. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  38069. info.writeData(obj.dataBuffer.buffer, offset, val);
  38070. }
  38071. };
  38072. };
  38073. }
  38074. BABYLON.instanceData = instanceData;
  38075. var InstanceDataBase = (function () {
  38076. function InstanceDataBase(partId, dataElementCount) {
  38077. this.id = partId;
  38078. this.curElement = 0;
  38079. this.dataElementCount = dataElementCount;
  38080. }
  38081. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  38082. get: function () {
  38083. return null;
  38084. },
  38085. enumerable: true,
  38086. configurable: true
  38087. });
  38088. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  38089. get: function () {
  38090. return null;
  38091. },
  38092. enumerable: true,
  38093. configurable: true
  38094. });
  38095. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  38096. get: function () {
  38097. return null;
  38098. },
  38099. enumerable: true,
  38100. configurable: true
  38101. });
  38102. Object.defineProperty(InstanceDataBase.prototype, "origin", {
  38103. get: function () {
  38104. return null;
  38105. },
  38106. enumerable: true,
  38107. configurable: true
  38108. });
  38109. InstanceDataBase.prototype.getClassTreeInfo = function () {
  38110. if (!this.typeInfo) {
  38111. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  38112. }
  38113. return this.typeInfo;
  38114. };
  38115. InstanceDataBase.prototype.allocElements = function () {
  38116. if (!this.dataBuffer) {
  38117. return;
  38118. }
  38119. var res = new Array(this.dataElementCount);
  38120. for (var i = 0; i < this.dataElementCount; i++) {
  38121. res[i] = this.dataBuffer.allocElement();
  38122. }
  38123. this.dataElements = res;
  38124. };
  38125. InstanceDataBase.prototype.freeElements = function () {
  38126. if (!this.dataElements) {
  38127. return;
  38128. }
  38129. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  38130. var ei = _a[_i];
  38131. this.dataBuffer.freeElement(ei);
  38132. }
  38133. this.dataElements = null;
  38134. };
  38135. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  38136. get: function () {
  38137. return this._dataElementCount;
  38138. },
  38139. set: function (value) {
  38140. if (value === this._dataElementCount) {
  38141. return;
  38142. }
  38143. this.freeElements();
  38144. this._dataElementCount = value;
  38145. this.allocElements();
  38146. },
  38147. enumerable: true,
  38148. configurable: true
  38149. });
  38150. __decorate([
  38151. instanceData()
  38152. ], InstanceDataBase.prototype, "zBias", null);
  38153. __decorate([
  38154. instanceData()
  38155. ], InstanceDataBase.prototype, "transformX", null);
  38156. __decorate([
  38157. instanceData()
  38158. ], InstanceDataBase.prototype, "transformY", null);
  38159. __decorate([
  38160. instanceData()
  38161. ], InstanceDataBase.prototype, "origin", null);
  38162. return InstanceDataBase;
  38163. })();
  38164. BABYLON.InstanceDataBase = InstanceDataBase;
  38165. var RenderablePrim2D = (function (_super) {
  38166. __extends(RenderablePrim2D, _super);
  38167. function RenderablePrim2D() {
  38168. _super.apply(this, arguments);
  38169. }
  38170. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  38171. get: function () {
  38172. return this._isAlphaTest;
  38173. },
  38174. set: function (value) {
  38175. this._isAlphaTest = value;
  38176. },
  38177. enumerable: true,
  38178. configurable: true
  38179. });
  38180. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  38181. get: function () {
  38182. return this._isTransparent;
  38183. },
  38184. set: function (value) {
  38185. this._isTransparent = value;
  38186. },
  38187. enumerable: true,
  38188. configurable: true
  38189. });
  38190. RenderablePrim2D.prototype.setupRenderablePrim2D = function (owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign) {
  38191. this.setupPrim2DBase(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign);
  38192. this._isTransparent = false;
  38193. this._isAlphaTest = false;
  38194. this._transparentPrimitiveInfo = null;
  38195. };
  38196. RenderablePrim2D.prototype.dispose = function () {
  38197. if (!_super.prototype.dispose.call(this)) {
  38198. return false;
  38199. }
  38200. if (this._modelRenderInstanceID) {
  38201. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  38202. this._modelRenderInstanceID = null;
  38203. }
  38204. if (this._modelRenderCache) {
  38205. this._modelRenderCache.dispose();
  38206. this._modelRenderCache = null;
  38207. }
  38208. if (this._instanceDataParts) {
  38209. this._instanceDataParts.forEach(function (p) {
  38210. p.freeElements();
  38211. });
  38212. this._instanceDataParts = null;
  38213. }
  38214. return true;
  38215. };
  38216. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  38217. _super.prototype._prepareRenderPre.call(this, context);
  38218. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  38219. if (this._modelDirty && this._modelRenderInstanceID) {
  38220. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  38221. this._modelRenderInstanceID = null;
  38222. }
  38223. // Need to create the model?
  38224. var setupModelRenderCache = false;
  38225. if (!this._modelRenderCache || this._modelDirty) {
  38226. setupModelRenderCache = this._createModelRenderCache();
  38227. }
  38228. var gii = null;
  38229. var newInstance = false;
  38230. // Need to create the instance data parts?
  38231. if (!this._modelRenderInstanceID) {
  38232. // Yes, flag it for later, more processing will have to be done
  38233. newInstance = true;
  38234. gii = this._createModelDataParts();
  38235. }
  38236. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  38237. if (setupModelRenderCache) {
  38238. this.setupModelRenderCache(this._modelRenderCache);
  38239. }
  38240. // 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.
  38241. // 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.
  38242. if (this._visibilityChanged || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  38243. this._updateInstanceDataParts(gii);
  38244. }
  38245. };
  38246. RenderablePrim2D.prototype._createModelRenderCache = function () {
  38247. var _this = this;
  38248. var setupModelRenderCache = false;
  38249. if (this._modelRenderCache) {
  38250. this._modelRenderCache.dispose();
  38251. }
  38252. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  38253. var mrc = _this.createModelRenderCache(key);
  38254. setupModelRenderCache = true;
  38255. return mrc;
  38256. });
  38257. this._modelDirty = false;
  38258. // if this is still false it means the MRC already exists, so we add a reference to it
  38259. if (!setupModelRenderCache) {
  38260. this._modelRenderCache.addRef();
  38261. }
  38262. return setupModelRenderCache;
  38263. };
  38264. RenderablePrim2D.prototype._createModelDataParts = function () {
  38265. var _this = this;
  38266. // Create the instance data parts of the primitive and store them
  38267. var parts = this.createInstanceDataParts();
  38268. this._instanceDataParts = parts;
  38269. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  38270. if (!this._modelRenderCache._partData) {
  38271. this._setupModelRenderCache(parts);
  38272. }
  38273. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  38274. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  38275. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  38276. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  38277. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  38278. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  38279. var part = _this._instanceDataParts[j];
  38280. res.partIndexFromId.add(part.id.toString(), j);
  38281. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  38282. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  38283. }
  38284. return res;
  38285. });
  38286. // Get the GroupInfoDataPart corresponding to the render category of the part
  38287. var gipd = null;
  38288. if (this.isTransparent) {
  38289. gipd = gii.transparentData;
  38290. }
  38291. else if (this.isAlphaTest) {
  38292. gipd = gii.alphaTestData;
  38293. }
  38294. else {
  38295. gipd = gii.opaqueData;
  38296. }
  38297. // For each instance data part of the primitive, allocate the instanced element it needs for render
  38298. for (var i = 0; i < parts.length; i++) {
  38299. var part = parts[i];
  38300. part.dataBuffer = gipd[i]._partData;
  38301. part.allocElements();
  38302. }
  38303. // 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
  38304. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  38305. return gii;
  38306. };
  38307. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  38308. var ctiArray = new Array();
  38309. this._modelRenderCache._partData = new Array();
  38310. for (var _i = 0; _i < parts.length; _i++) {
  38311. var dataPart = parts[_i];
  38312. var pd = new BABYLON.ModelRenderCachePartData();
  38313. this._modelRenderCache._partData.push(pd);
  38314. var cat = this.getUsedShaderCategories(dataPart);
  38315. var cti = dataPart.getClassTreeInfo();
  38316. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  38317. var curVisible = this.isVisible;
  38318. this.isVisible = true;
  38319. // 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.
  38320. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  38321. var joinCat = ";" + cat.join(";") + ";";
  38322. pd._partJoinedUsedCategories = joinCat;
  38323. InstanceClassInfo._CurCategories = joinCat;
  38324. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  38325. this.refreshInstanceDataPart(dataPart);
  38326. this.afterRefreshForLayoutConstruction(dataPart, obj);
  38327. this.isVisible = curVisible;
  38328. var size = 0;
  38329. cti.fullContent.forEach(function (k, v) {
  38330. if (!v.category || cat.indexOf(v.category) !== -1) {
  38331. if (v.attributeName === "zBias") {
  38332. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  38333. }
  38334. if (!v.size) {
  38335. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  38336. }
  38337. else {
  38338. size += v.size;
  38339. }
  38340. }
  38341. });
  38342. pd._partDataStride = size;
  38343. pd._partUsedCategories = cat;
  38344. pd._partId = dataPart.id;
  38345. ctiArray.push(cti);
  38346. }
  38347. this._modelRenderCache._partsClassInfo = ctiArray;
  38348. };
  38349. RenderablePrim2D.prototype.onZOrderChanged = function () {
  38350. if (this.isTransparent && this._transparentPrimitiveInfo) {
  38351. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  38352. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  38353. // Flag the transparentData dirty has will have to sort it again
  38354. gii.transparentOrderDirty = true;
  38355. }
  38356. };
  38357. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  38358. // Fetch the GroupInstanceInfo if we don't already have it
  38359. if (!gii) {
  38360. gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  38361. }
  38362. // Handle changes related to ZOffset
  38363. if (this.isTransparent) {
  38364. // Handle visibility change, which is also triggered when the primitive just got created
  38365. if (this._visibilityChanged) {
  38366. if (this.isVisible) {
  38367. if (!this._transparentPrimitiveInfo) {
  38368. // Add the primitive to the list of transparent ones in the group that render is
  38369. this._transparentPrimitiveInfo = this.renderGroup._renderableData.addNewTransparentPrimitiveInfo(this, gii);
  38370. }
  38371. }
  38372. else {
  38373. if (this._transparentPrimitiveInfo) {
  38374. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  38375. }
  38376. }
  38377. gii.transparentOrderDirty = true;
  38378. }
  38379. }
  38380. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  38381. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  38382. var part = _a[_i];
  38383. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  38384. if (this._visibilityChanged && !part.dataElements) {
  38385. part.allocElements();
  38386. }
  38387. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  38388. // Will return false if the instance should not be rendered (not visible or other any reasons)
  38389. if (!this.refreshInstanceDataPart(part)) {
  38390. // Free the data element
  38391. if (part.dataElements) {
  38392. part.freeElements();
  38393. }
  38394. }
  38395. }
  38396. this._instanceDirtyFlags = 0;
  38397. // Make the appropriate data dirty
  38398. if (this.isTransparent) {
  38399. gii.transparentDirty = true;
  38400. }
  38401. else if (this.isAlphaTest) {
  38402. gii.alphaTestDirty = true;
  38403. }
  38404. else {
  38405. gii.opaqueDirty = true;
  38406. }
  38407. this._visibilityChanged = false; // Reset the flag as we've handled the case
  38408. };
  38409. RenderablePrim2D.prototype._getFirstIndexInDataBuffer = function () {
  38410. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  38411. var part = _a[_i];
  38412. if (part) {
  38413. return part.dataElements[0].offset / part.dataBuffer.stride;
  38414. }
  38415. }
  38416. return null;
  38417. };
  38418. RenderablePrim2D.prototype._getLastIndexInDataBuffer = function () {
  38419. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  38420. var part = _a[_i];
  38421. if (part) {
  38422. return part.dataElements[part.dataElements.length - 1].offset / part.dataBuffer.stride;
  38423. }
  38424. }
  38425. return null;
  38426. };
  38427. // This internal method is mainly used for transparency processing
  38428. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  38429. var length = this._instanceDataParts.length;
  38430. for (var i = 0; i < length; i++) {
  38431. var part = this._instanceDataParts[i];
  38432. if (part) {
  38433. var stride = part.dataBuffer.stride;
  38434. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  38435. // check if it's the last in the DFA
  38436. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  38437. return null;
  38438. }
  38439. // Return the Z of the next primitive that lies in the DFA
  38440. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  38441. }
  38442. }
  38443. return null;
  38444. };
  38445. // This internal method is mainly used for transparency processing
  38446. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  38447. var length = this._instanceDataParts.length;
  38448. for (var i = 0; i < length; i++) {
  38449. var part = this._instanceDataParts[i];
  38450. if (part) {
  38451. var stride = part.dataBuffer.stride;
  38452. var firstElementOffset = part.dataElements[0].offset;
  38453. // check if it's the first in the DFA
  38454. if (firstElementOffset === 0) {
  38455. return null;
  38456. }
  38457. // Return the Z of the previous primitive that lies in the DFA
  38458. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  38459. }
  38460. }
  38461. return null;
  38462. };
  38463. /**
  38464. * Transform a given point using the Primitive's origin setting.
  38465. * This method requires the Primitive's actualSize to be accurate
  38466. * @param p the point to transform
  38467. * @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.
  38468. * @param res an allocated Vector2 that will receive the transformed content
  38469. */
  38470. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  38471. var actualSize = this.actualSize;
  38472. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  38473. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  38474. };
  38475. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  38476. this.transformPointWithOriginByRef(p, originOffset, res);
  38477. return res;
  38478. };
  38479. /**
  38480. * Get the info for a given effect based on the dataPart metadata
  38481. * @param dataPartId partId in part list to get the info
  38482. * @param vertexBufferAttributes vertex buffer attributes to manually add
  38483. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  38484. */
  38485. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  38486. if (useInstanced === void 0) { useInstanced = null; }
  38487. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  38488. if (!dataPart) {
  38489. return null;
  38490. }
  38491. var instancedArray = this.owner.supportInstancedArray;
  38492. if (useInstanced != null) {
  38493. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  38494. if (useInstanced && instancedArray === false) {
  38495. return null;
  38496. }
  38497. // Use the caller's setting
  38498. instancedArray = useInstanced;
  38499. }
  38500. var cti = dataPart.getClassTreeInfo();
  38501. var categories = this.getUsedShaderCategories(dataPart);
  38502. var att = cti.classContent.getShaderAttributes(categories);
  38503. var defines = "";
  38504. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  38505. if (instancedArray) {
  38506. defines += "#define Instanced\n";
  38507. }
  38508. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  38509. };
  38510. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  38511. get: function () {
  38512. return this._modelRenderCache;
  38513. },
  38514. enumerable: true,
  38515. configurable: true
  38516. });
  38517. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  38518. return null;
  38519. };
  38520. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38521. };
  38522. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  38523. return null;
  38524. };
  38525. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  38526. return [];
  38527. };
  38528. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  38529. };
  38530. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  38531. };
  38532. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  38533. if (!this.isVisible) {
  38534. return false;
  38535. }
  38536. part.isVisible = this.isVisible;
  38537. // 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)
  38538. if (part.dataElementCount === 1) {
  38539. part.curElement = 0;
  38540. this.updateInstanceDataPart(part);
  38541. }
  38542. return true;
  38543. };
  38544. /**
  38545. * Update the instanceDataBase level properties of a part
  38546. * @param part the part to update
  38547. * @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.
  38548. * @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.
  38549. */
  38550. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset, customSize) {
  38551. if (positionOffset === void 0) { positionOffset = null; }
  38552. if (customSize === void 0) { customSize = null; }
  38553. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  38554. var size = this.renderGroup.viewportSize;
  38555. var zBias = this.getActualZOffset();
  38556. var offX = 0;
  38557. var offY = 0;
  38558. // If there's an offset, apply the global transformation matrix on it to get a global offset
  38559. if (positionOffset && customSize) {
  38560. offX = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[0] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[4];
  38561. offY = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[1] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[5];
  38562. }
  38563. // 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
  38564. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  38565. // So for X:
  38566. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  38567. // - 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].
  38568. var w = size.width;
  38569. var h = size.height;
  38570. var invZBias = 1 / zBias;
  38571. 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) - 1);
  38572. 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) - 1);
  38573. part.transformX = tx;
  38574. part.transformY = ty;
  38575. part.origin = this.origin;
  38576. // 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)
  38577. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  38578. };
  38579. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  38580. __decorate([
  38581. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  38582. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  38583. __decorate([
  38584. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  38585. ], RenderablePrim2D.prototype, "isTransparent", null);
  38586. RenderablePrim2D = __decorate([
  38587. BABYLON.className("RenderablePrim2D")
  38588. ], RenderablePrim2D);
  38589. return RenderablePrim2D;
  38590. })(BABYLON.Prim2DBase);
  38591. BABYLON.RenderablePrim2D = RenderablePrim2D;
  38592. })(BABYLON || (BABYLON = {}));
  38593. var BABYLON;
  38594. (function (BABYLON) {
  38595. var Shape2D = (function (_super) {
  38596. __extends(Shape2D, _super);
  38597. function Shape2D() {
  38598. _super.apply(this, arguments);
  38599. }
  38600. Object.defineProperty(Shape2D.prototype, "border", {
  38601. get: function () {
  38602. return this._border;
  38603. },
  38604. set: function (value) {
  38605. this._border = value;
  38606. this._updateTransparencyStatus();
  38607. },
  38608. enumerable: true,
  38609. configurable: true
  38610. });
  38611. Object.defineProperty(Shape2D.prototype, "fill", {
  38612. get: function () {
  38613. return this._fill;
  38614. },
  38615. set: function (value) {
  38616. this._fill = value;
  38617. this._updateTransparencyStatus();
  38618. },
  38619. enumerable: true,
  38620. configurable: true
  38621. });
  38622. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  38623. get: function () {
  38624. return this._borderThickness;
  38625. },
  38626. set: function (value) {
  38627. this._borderThickness = value;
  38628. },
  38629. enumerable: true,
  38630. configurable: true
  38631. });
  38632. Shape2D.prototype.setupShape2D = function (owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  38633. this.setupRenderablePrim2D(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlignment || BABYLON.Prim2DBase.HAlignLeft, vAlignment || BABYLON.Prim2DBase.VAlignTop);
  38634. this.border = border;
  38635. this.fill = fill;
  38636. this.borderThickness = borderThickness;
  38637. };
  38638. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  38639. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  38640. // Fill Part
  38641. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  38642. var fill = this.fill;
  38643. if (fill instanceof BABYLON.SolidColorBrush2D) {
  38644. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  38645. }
  38646. if (fill instanceof BABYLON.GradientColorBrush2D) {
  38647. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  38648. }
  38649. }
  38650. // Border Part
  38651. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  38652. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  38653. var border = this.border;
  38654. if (border instanceof BABYLON.SolidColorBrush2D) {
  38655. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  38656. }
  38657. if (border instanceof BABYLON.GradientColorBrush2D) {
  38658. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  38659. }
  38660. }
  38661. return cat;
  38662. };
  38663. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  38664. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38665. return false;
  38666. }
  38667. // Fill Part
  38668. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  38669. var d = part;
  38670. if (this.fill) {
  38671. var fill = this.fill;
  38672. if (fill instanceof BABYLON.SolidColorBrush2D) {
  38673. d.fillSolidColor = fill.color;
  38674. }
  38675. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  38676. d.fillGradientColor1 = fill.color1;
  38677. d.fillGradientColor2 = fill.color2;
  38678. 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));
  38679. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  38680. d.fillGradientTY = ty;
  38681. }
  38682. }
  38683. }
  38684. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  38685. var d = part;
  38686. if (this.border) {
  38687. d.borderThickness = this.borderThickness;
  38688. var border = this.border;
  38689. if (border instanceof BABYLON.SolidColorBrush2D) {
  38690. d.borderSolidColor = border.color;
  38691. }
  38692. else if (border instanceof BABYLON.GradientColorBrush2D) {
  38693. d.borderGradientColor1 = border.color1;
  38694. d.borderGradientColor2 = border.color2;
  38695. 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));
  38696. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  38697. d.borderGradientTY = ty;
  38698. }
  38699. }
  38700. }
  38701. return true;
  38702. };
  38703. Shape2D.prototype._updateTransparencyStatus = function () {
  38704. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  38705. };
  38706. Shape2D.SHAPE2D_BORDERPARTID = 1;
  38707. Shape2D.SHAPE2D_FILLPARTID = 2;
  38708. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  38709. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  38710. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  38711. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  38712. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  38713. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  38714. __decorate([
  38715. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  38716. ], Shape2D.prototype, "border", null);
  38717. __decorate([
  38718. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  38719. ], Shape2D.prototype, "fill", null);
  38720. __decorate([
  38721. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  38722. ], Shape2D.prototype, "borderThickness", null);
  38723. Shape2D = __decorate([
  38724. BABYLON.className("Shape2D")
  38725. ], Shape2D);
  38726. return Shape2D;
  38727. })(BABYLON.RenderablePrim2D);
  38728. BABYLON.Shape2D = Shape2D;
  38729. var Shape2DInstanceData = (function (_super) {
  38730. __extends(Shape2DInstanceData, _super);
  38731. function Shape2DInstanceData() {
  38732. _super.apply(this, arguments);
  38733. }
  38734. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  38735. // FILL ATTRIBUTES
  38736. get: function () {
  38737. return null;
  38738. },
  38739. enumerable: true,
  38740. configurable: true
  38741. });
  38742. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  38743. get: function () {
  38744. return null;
  38745. },
  38746. enumerable: true,
  38747. configurable: true
  38748. });
  38749. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  38750. get: function () {
  38751. return null;
  38752. },
  38753. enumerable: true,
  38754. configurable: true
  38755. });
  38756. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  38757. get: function () {
  38758. return null;
  38759. },
  38760. enumerable: true,
  38761. configurable: true
  38762. });
  38763. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  38764. // BORDER ATTRIBUTES
  38765. get: function () {
  38766. return null;
  38767. },
  38768. enumerable: true,
  38769. configurable: true
  38770. });
  38771. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  38772. get: function () {
  38773. return null;
  38774. },
  38775. enumerable: true,
  38776. configurable: true
  38777. });
  38778. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  38779. get: function () {
  38780. return null;
  38781. },
  38782. enumerable: true,
  38783. configurable: true
  38784. });
  38785. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  38786. get: function () {
  38787. return null;
  38788. },
  38789. enumerable: true,
  38790. configurable: true
  38791. });
  38792. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  38793. get: function () {
  38794. return null;
  38795. },
  38796. enumerable: true,
  38797. configurable: true
  38798. });
  38799. __decorate([
  38800. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  38801. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  38802. __decorate([
  38803. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38804. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  38805. __decorate([
  38806. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38807. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  38808. __decorate([
  38809. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38810. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  38811. __decorate([
  38812. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  38813. ], Shape2DInstanceData.prototype, "borderThickness", null);
  38814. __decorate([
  38815. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  38816. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  38817. __decorate([
  38818. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38819. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  38820. __decorate([
  38821. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38822. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  38823. __decorate([
  38824. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38825. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  38826. return Shape2DInstanceData;
  38827. })(BABYLON.InstanceDataBase);
  38828. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  38829. })(BABYLON || (BABYLON = {}));
  38830. var BABYLON;
  38831. (function (BABYLON) {
  38832. var Group2D = (function (_super) {
  38833. __extends(Group2D, _super);
  38834. /**
  38835. * Don't invoke directly, rely on Group2D.CreateXXX methods
  38836. */
  38837. function Group2D() {
  38838. _super.call(this);
  38839. }
  38840. /**
  38841. * Create an Logical or Renderable Group.
  38842. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  38843. * options:
  38844. * - id a text identifier, for information purpose
  38845. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  38846. * - origin: define the normalized origin point location, default [0.5;0.5]
  38847. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  38848. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  38849. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  38850. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  38851. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  38852. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  38853. */
  38854. Group2D.CreateGroup2D = function (parent, options) {
  38855. BABYLON.Prim2DBase.CheckParent(parent);
  38856. var g = new Group2D();
  38857. if (!options) {
  38858. g.setupGroup2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, null, true, Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY, null, null, null, null, null, null);
  38859. }
  38860. else {
  38861. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  38862. var size = (!options.size && !options.width && !options.height) ? null : (options.size || (new BABYLON.Size(options.width || 0, options.height || 0)));
  38863. g.setupGroup2D(parent.owner, parent, options.id || null, pos, options.origin || null, size, (options.isVisible == null) ? true : options.isVisible, (options.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : options.cacheBehavior, options.marginTop, options.marginLeft, options.marginRight, options.marginBottom, options.hAlignment || BABYLON.Prim2DBase.HAlignLeft, options.vAlignment || BABYLON.Prim2DBase.VAlignTop);
  38864. }
  38865. return g;
  38866. };
  38867. Group2D._createCachedCanvasGroup = function (owner) {
  38868. var g = new Group2D();
  38869. g.setupGroup2D(owner, null, "__cachedCanvasGroup__", BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), null, true, Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY, null, null, null, null, null, null);
  38870. g.origin = BABYLON.Vector2.Zero();
  38871. return g;
  38872. };
  38873. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  38874. this._bindCacheTarget();
  38875. var uv = vertexData.uvs;
  38876. var nodeuv = this._renderableData._cacheNode.UVs;
  38877. for (var i = 0; i < 4; i++) {
  38878. uv[i * 2 + 0] = nodeuv[i].x;
  38879. uv[i * 2 + 1] = nodeuv[i].y;
  38880. }
  38881. material.diffuseTexture = this._renderableData._cacheTexture;
  38882. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  38883. this._renderableData._cacheTexture.hasAlpha = true;
  38884. this._unbindCacheTarget();
  38885. };
  38886. Object.defineProperty(Group2D.prototype, "cachedRect", {
  38887. /**
  38888. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  38889. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you must use the cachedRect.UVs property to get the UV coordinates to use for your quad that will display the Canvas.
  38890. */
  38891. get: function () {
  38892. if (!this._renderableData) {
  38893. return null;
  38894. }
  38895. return this._renderableData._cacheNode;
  38896. },
  38897. enumerable: true,
  38898. configurable: true
  38899. });
  38900. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  38901. /**
  38902. * Access the texture that maintains a cached version of the Group2D.
  38903. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  38904. */
  38905. get: function () {
  38906. if (!this._renderableData) {
  38907. return null;
  38908. }
  38909. return this._renderableData._cacheTexture;
  38910. },
  38911. enumerable: true,
  38912. configurable: true
  38913. });
  38914. /**
  38915. * Call this method to remove this Group and its children from the Canvas
  38916. */
  38917. Group2D.prototype.dispose = function () {
  38918. if (!_super.prototype.dispose.call(this)) {
  38919. return false;
  38920. }
  38921. if (this._renderableData) {
  38922. this._renderableData.dispose();
  38923. this._renderableData = null;
  38924. }
  38925. return true;
  38926. };
  38927. Group2D.prototype.setupGroup2D = function (owner, parent, id, position, origin, size, isVisible, cacheBehavior, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign) {
  38928. this._cacheBehavior = cacheBehavior;
  38929. this.setupPrim2DBase(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign);
  38930. this.size = size;
  38931. this._viewportPosition = BABYLON.Vector2.Zero();
  38932. };
  38933. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  38934. /**
  38935. * @returns Returns true if the Group render content, false if it's a logical group only
  38936. */
  38937. get: function () {
  38938. return this._isRenderableGroup;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  38944. /**
  38945. * @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
  38946. */
  38947. get: function () {
  38948. return this._isCachedGroup;
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. Object.defineProperty(Group2D.prototype, "size", {
  38954. get: function () {
  38955. return this._size;
  38956. },
  38957. /**
  38958. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  38959. * 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.
  38960. */
  38961. set: function (val) {
  38962. this._size = val;
  38963. },
  38964. enumerable: true,
  38965. configurable: true
  38966. });
  38967. Object.defineProperty(Group2D.prototype, "viewportSize", {
  38968. get: function () {
  38969. return this._viewportSize;
  38970. },
  38971. enumerable: true,
  38972. configurable: true
  38973. });
  38974. Object.defineProperty(Group2D.prototype, "actualSize", {
  38975. get: function () {
  38976. // The computed size will be floor on both width and height
  38977. var actualSize;
  38978. // Return the size if set by the user
  38979. if (this._size) {
  38980. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  38981. }
  38982. else {
  38983. var m = this.boundingInfo.max();
  38984. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  38985. }
  38986. // 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)
  38987. if (!actualSize.equals(this._actualSize)) {
  38988. this._instanceDirtyFlags |= Group2D.actualSizeProperty.flagId;
  38989. this._actualSize = actualSize;
  38990. this.handleGroupChanged(Group2D.actualSizeProperty);
  38991. }
  38992. return actualSize;
  38993. },
  38994. enumerable: true,
  38995. configurable: true
  38996. });
  38997. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  38998. /**
  38999. * 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.
  39000. * 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.
  39001. */
  39002. get: function () {
  39003. return this._cacheBehavior;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. Group2D.prototype._addPrimToDirtyList = function (prim) {
  39009. this._renderableData._primDirtyList.push(prim);
  39010. };
  39011. Group2D.prototype._renderCachedCanvas = function () {
  39012. this.updateGlobalTransVis(true);
  39013. var context = new BABYLON.PrepareRender2DContext();
  39014. this._prepareGroupRender(context);
  39015. this._groupRender();
  39016. };
  39017. Group2D.prototype.levelIntersect = function (intersectInfo) {
  39018. // 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
  39019. return true;
  39020. };
  39021. Group2D.prototype.updateLevelBoundingInfo = function () {
  39022. var size;
  39023. // If the size is set by the user, the boundingInfo is computed from this value
  39024. if (this.size) {
  39025. size = this.size;
  39026. }
  39027. else {
  39028. size = new BABYLON.Size(0, 0);
  39029. }
  39030. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  39031. };
  39032. // Method called only on renderable groups to prepare the rendering
  39033. Group2D.prototype._prepareGroupRender = function (context) {
  39034. var sortedDirtyList = null;
  39035. // Update the Global Transformation and visibility status of the changed primitives
  39036. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  39037. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  39038. this.updateGlobalTransVisOf(sortedDirtyList, true);
  39039. }
  39040. // Setup the size of the rendering viewport
  39041. // 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
  39042. if (!this._isCachedGroup) {
  39043. // Compute the WebGL viewport's location/size
  39044. var t = this._globalTransform.getTranslation();
  39045. var s = this.actualSize.clone();
  39046. var rs = this.owner._renderingSize;
  39047. s.height = Math.min(s.height, rs.height - t.y);
  39048. s.width = Math.min(s.width, rs.width - t.x);
  39049. var x = t.x;
  39050. var y = t.y;
  39051. // 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
  39052. this._viewportPosition.x = x;
  39053. this._viewportPosition.y = y;
  39054. var vw = s.width;
  39055. var vh = s.height;
  39056. if (!this._viewportSize) {
  39057. this._viewportSize = new BABYLON.Size(vw, vh);
  39058. }
  39059. else {
  39060. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  39061. context.forceRefreshPrimitive = true;
  39062. }
  39063. this._viewportSize.width = vw;
  39064. this._viewportSize.height = vh;
  39065. }
  39066. }
  39067. else {
  39068. var newSize = this.actualSize.clone();
  39069. if (!newSize.equals(this._viewportSize)) {
  39070. context.forceRefreshPrimitive = true;
  39071. }
  39072. this._viewportSize = newSize;
  39073. }
  39074. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  39075. // If the group is cached, set the dirty flag to true because of the incoming changes
  39076. this._cacheGroupDirty = this._isCachedGroup;
  39077. // If it's a force refresh, prepare all the children
  39078. if (context.forceRefreshPrimitive) {
  39079. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39080. var p = _a[_i];
  39081. p._prepareRender(context);
  39082. }
  39083. }
  39084. else {
  39085. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  39086. // the hierarchyDepth in order to prepare primitives from top to bottom
  39087. if (!sortedDirtyList) {
  39088. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  39089. }
  39090. sortedDirtyList.forEach(function (p) {
  39091. // 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.
  39092. // 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.
  39093. if (!p.isDisposed && p._needPrepare()) {
  39094. p._prepareRender(context);
  39095. }
  39096. });
  39097. // Everything is updated, clear the dirty list
  39098. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  39099. this._renderableData._primDirtyList.splice(0);
  39100. }
  39101. }
  39102. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  39103. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  39104. g._prepareGroupRender(context);
  39105. });
  39106. };
  39107. Group2D.prototype._groupRender = function () {
  39108. var _this = this;
  39109. var engine = this.owner.engine;
  39110. var failedCount = 0;
  39111. // First recurse to children render group to render them (in their cache or on screen)
  39112. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  39113. var childGroup = _a[_i];
  39114. childGroup._groupRender();
  39115. }
  39116. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  39117. if (!this.isCachedGroup || this._cacheGroupDirty) {
  39118. if (this.isCachedGroup) {
  39119. this._bindCacheTarget();
  39120. }
  39121. else {
  39122. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  39123. }
  39124. // ===================================================================
  39125. // First pass, update the InstancedArray and render Opaque primitives
  39126. // Disable Culling, Alpha Testing, Enable Depth Write
  39127. engine.setState(false);
  39128. engine.setAlphaTesting(false);
  39129. engine.setDepthWrite(true);
  39130. // For each different model of primitive to render
  39131. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  39132. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  39133. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  39134. var renderCount = _this._prepareContext(engine, context, v);
  39135. // If null is returned, there's no opaque data to render
  39136. if (renderCount === null) {
  39137. return;
  39138. }
  39139. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  39140. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  39141. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  39142. var renderFailed = !v.modelRenderCache.render(v, context);
  39143. // Update dirty flag/related
  39144. v.opaqueDirty = renderFailed;
  39145. failedCount += renderFailed ? 1 : 0;
  39146. }
  39147. });
  39148. // =======================================================================
  39149. // Second pass, update the InstancedArray and render AlphaTest primitives
  39150. // Enable Alpha Testing, Enable Depth Write
  39151. engine.setAlphaTesting(true);
  39152. engine.setDepthWrite(true);
  39153. // For each different model of primitive to render
  39154. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  39155. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  39156. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  39157. var renderCount = _this._prepareContext(engine, context, v);
  39158. // If null is returned, there's no opaque data to render
  39159. if (renderCount === null) {
  39160. return;
  39161. }
  39162. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  39163. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  39164. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  39165. var renderFailed = !v.modelRenderCache.render(v, context);
  39166. // Update dirty flag/related
  39167. v.opaqueDirty = renderFailed;
  39168. failedCount += renderFailed ? 1 : 0;
  39169. }
  39170. });
  39171. // =======================================================================
  39172. // Third pass, transparent primitive rendering
  39173. // Enable Alpha Testing, Disable Depth Write
  39174. engine.setAlphaTesting(true);
  39175. engine.setDepthWrite(false);
  39176. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  39177. if (this._renderableData._transparentListChanged) {
  39178. this._updateTransparentData();
  39179. }
  39180. // From this point on we have up to date data to render, so let's go
  39181. failedCount += this._renderTransparentData();
  39182. // =======================================================================
  39183. // Unbind target/restore viewport setting, clear dirty flag, and quit
  39184. // The group's content is no longer dirty
  39185. this._cacheGroupDirty = failedCount !== 0;
  39186. if (this.isCachedGroup) {
  39187. this._unbindCacheTarget();
  39188. }
  39189. else {
  39190. if (curVP) {
  39191. engine.setViewport(curVP);
  39192. }
  39193. }
  39194. }
  39195. };
  39196. Group2D.prototype._updateTransparentData = function () {
  39197. var rd = this._renderableData;
  39198. // If null, there was no change of ZOrder, we have nothing to do
  39199. if (rd._firstChangedPrim === null) {
  39200. return;
  39201. }
  39202. // Sort all the primitive from their depth, max (bottom) to min (top)
  39203. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.getActualZOffset() - a._primitive.getActualZOffset(); });
  39204. var checkAndAddPrimInSegment = function (seg, tpiI) {
  39205. var tpi = rd._transparentPrimitives[tpiI];
  39206. // Fast rejection: if gii are different
  39207. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  39208. return false;
  39209. }
  39210. var tpiZ = tpi._primitive.getActualZOffset();
  39211. // We've made it so far, the tpi can be part of the segment, add it
  39212. tpi._transparentSegment = seg;
  39213. // Check if we have to update endZ, a smaller value means one above the current one
  39214. if (tpiZ < seg.endZ) {
  39215. seg.endZ = tpiZ;
  39216. seg.endDataIndex = tpi._primitive._getLastIndexInDataBuffer() + 1; // Still exclusive
  39217. }
  39218. return true;
  39219. };
  39220. rd._transparentSegments.splice(0);
  39221. var prevSeg = null;
  39222. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  39223. var tpi = rd._transparentPrimitives[tpiI];
  39224. // Check if the Data in which the primitive is stored is not sorted properly
  39225. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  39226. tpi._groupInstanceInfo.sortTransparentData();
  39227. }
  39228. // Reset the segment, we have to create/rebuild it
  39229. tpi._transparentSegment = null;
  39230. // If there's a previous valid segment, check if this prim can be part of it
  39231. if (prevSeg) {
  39232. checkAndAddPrimInSegment(prevSeg, tpiI);
  39233. }
  39234. // If we couldn't insert in the adjacent segments, he have to create one
  39235. if (!tpi._transparentSegment) {
  39236. var ts = new BABYLON.TransparentSegment();
  39237. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  39238. var prim = tpi._primitive;
  39239. ts.startZ = prim.getActualZOffset();
  39240. ts.startDataIndex = prim._getFirstIndexInDataBuffer();
  39241. ts.endDataIndex = prim._getLastIndexInDataBuffer() + 1; // Make it exclusive, more natural to use in a for loop
  39242. ts.endZ = ts.startZ;
  39243. tpi._transparentSegment = ts;
  39244. rd._transparentSegments.push(ts);
  39245. }
  39246. // Update prevSeg
  39247. prevSeg = tpi._transparentSegment;
  39248. }
  39249. rd._firstChangedPrim = null;
  39250. rd._transparentListChanged = false;
  39251. };
  39252. Group2D.prototype._renderTransparentData = function () {
  39253. var failedCount = 0;
  39254. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  39255. var rd = this._renderableData;
  39256. var length = rd._transparentSegments.length;
  39257. for (var i = 0; i < length; i++) {
  39258. var ts = rd._transparentSegments[i];
  39259. var gii = ts.groupInsanceInfo;
  39260. var mrc = gii.modelRenderCache;
  39261. context.useInstancing = false;
  39262. context.partDataStartIndex = ts.startDataIndex;
  39263. context.partDataEndIndex = ts.endDataIndex;
  39264. context.groupInfoPartData = gii.transparentData;
  39265. var renderFailed = !mrc.render(gii, context);
  39266. failedCount += renderFailed ? 1 : 0;
  39267. }
  39268. return failedCount;
  39269. };
  39270. Group2D.prototype._prepareContext = function (engine, context, gii) {
  39271. var gipd = null;
  39272. var setDirty;
  39273. var getDirty;
  39274. // Render Mode specifics
  39275. switch (context.renderMode) {
  39276. case BABYLON.Render2DContext.RenderModeOpaque:
  39277. {
  39278. if (!gii.hasOpaqueData) {
  39279. return null;
  39280. }
  39281. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  39282. getDirty = function () { return gii.opaqueDirty; };
  39283. context.groupInfoPartData = gii.opaqueData;
  39284. gipd = gii.opaqueData;
  39285. break;
  39286. }
  39287. case BABYLON.Render2DContext.RenderModeAlphaTest:
  39288. {
  39289. if (!gii.hasAlphaTestData) {
  39290. return null;
  39291. }
  39292. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  39293. getDirty = function () { return gii.alphaTestDirty; };
  39294. context.groupInfoPartData = gii.alphaTestData;
  39295. gipd = gii.alphaTestData;
  39296. break;
  39297. }
  39298. default:
  39299. throw new Error("_prepareContext is only for opaque or alphaTest");
  39300. }
  39301. var renderCount = 0;
  39302. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  39303. // Skip it if instanced arrays are not supported
  39304. if (this.owner.supportInstancedArray) {
  39305. // Flag for instancing
  39306. context.useInstancing = true;
  39307. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  39308. for (var i = 0; i < gipd.length; i++) {
  39309. var pid = gipd[i];
  39310. // If the instances of the model was changed, pack the data
  39311. var array = pid._partData;
  39312. var instanceData_1 = array.pack();
  39313. renderCount += array.usedElementCount;
  39314. // Compute the size the instance buffer should have
  39315. var neededSize = array.usedElementCount * array.stride * 4;
  39316. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  39317. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  39318. if (pid._partBuffer) {
  39319. engine.deleteInstancesBuffer(pid._partBuffer);
  39320. }
  39321. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  39322. pid._partBufferSize = neededSize;
  39323. setDirty(false);
  39324. // Update the WebGL buffer to match the new content of the instances data
  39325. engine.updateArrayBuffer(instanceData_1);
  39326. }
  39327. else if (getDirty()) {
  39328. // Update the WebGL buffer to match the new content of the instances data
  39329. engine.bindArrayBuffer(pid._partBuffer);
  39330. engine.updateArrayBuffer(instanceData_1);
  39331. }
  39332. }
  39333. setDirty(false);
  39334. }
  39335. else {
  39336. context.partDataStartIndex = 0;
  39337. // Find the first valid object to get the count
  39338. var i = 0;
  39339. while (!context.groupInfoPartData[i]) {
  39340. i++;
  39341. }
  39342. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  39343. }
  39344. return renderCount;
  39345. };
  39346. Group2D.prototype._bindCacheTarget = function () {
  39347. var curWidth;
  39348. var curHeight;
  39349. var rd = this._renderableData;
  39350. if (rd._cacheNode) {
  39351. var size = rd._cacheNode.contentSize;
  39352. var groupWidth = Math.ceil(this.actualSize.width);
  39353. var groupHeight = Math.ceil(this.actualSize.height);
  39354. if ((size.width < groupWidth) || (size.height < groupHeight)) {
  39355. curWidth = Math.floor(size.width * 1.07); // Grow 5% more to avoid frequent resizing for few pixels...
  39356. curHeight = Math.floor(size.height * 1.07);
  39357. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  39358. rd._cacheTexture.freeRect(rd._cacheNode);
  39359. rd._cacheNode = null;
  39360. }
  39361. }
  39362. if (!rd._cacheNode) {
  39363. // Check if we have to allocate a rendering zone in the global cache texture
  39364. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null);
  39365. rd._cacheNode = res.node;
  39366. rd._cacheTexture = res.texture;
  39367. rd._cacheRenderSprite = res.sprite;
  39368. var size = rd._cacheNode.contentSize;
  39369. }
  39370. var n = rd._cacheNode;
  39371. rd._cacheTexture.bindTextureForPosSize(n.pos, this.actualSize, true);
  39372. };
  39373. Group2D.prototype._unbindCacheTarget = function () {
  39374. if (this._renderableData._cacheTexture) {
  39375. this._renderableData._cacheTexture.unbindTexture();
  39376. }
  39377. };
  39378. Group2D.prototype.handleGroupChanged = function (prop) {
  39379. // This method is only for cachedGroup
  39380. var rd = this._renderableData;
  39381. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  39382. return;
  39383. }
  39384. // For now we only support these property changes
  39385. // TODO: add more! :)
  39386. if (prop.id === BABYLON.Prim2DBase.positionProperty.id) {
  39387. rd._cacheRenderSprite.position = this.position.clone();
  39388. }
  39389. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  39390. rd._cacheRenderSprite.rotation = this.rotation;
  39391. }
  39392. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  39393. rd._cacheRenderSprite.scale = this.scale;
  39394. }
  39395. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  39396. rd._cacheRenderSprite.origin = this.origin.clone();
  39397. }
  39398. else if (prop.id === Group2D.actualSizeProperty.id) {
  39399. rd._cacheRenderSprite.spriteSize = this.actualSize.clone();
  39400. }
  39401. };
  39402. Group2D.prototype.detectGroupStates = function () {
  39403. var isCanvas = this instanceof BABYLON.Canvas2D;
  39404. var canvasStrat = this.owner.cachingStrategy;
  39405. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  39406. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  39407. this._isRenderableGroup = isCanvas;
  39408. this._isCachedGroup = false;
  39409. }
  39410. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  39411. if (isCanvas) {
  39412. this._isRenderableGroup = true;
  39413. this._isCachedGroup = true;
  39414. }
  39415. else {
  39416. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  39417. this._isCachedGroup = false;
  39418. }
  39419. }
  39420. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  39421. if (isCanvas) {
  39422. this._isRenderableGroup = true;
  39423. this._isCachedGroup = false;
  39424. }
  39425. else {
  39426. if (this.hierarchyDepth === 1) {
  39427. this._isRenderableGroup = true;
  39428. this._isCachedGroup = true;
  39429. }
  39430. else {
  39431. this._isRenderableGroup = false;
  39432. this._isCachedGroup = false;
  39433. }
  39434. }
  39435. }
  39436. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  39437. var gcb = this.cacheBehavior;
  39438. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  39439. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  39440. this._isCachedGroup = false;
  39441. }
  39442. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  39443. this._isRenderableGroup = true;
  39444. this._isCachedGroup = true;
  39445. }
  39446. }
  39447. if (this._isRenderableGroup) {
  39448. this._renderableData = new RenderableGroupData();
  39449. }
  39450. // If the group is tagged as renderable we add it to the renderable tree
  39451. if (this._isCachedGroup) {
  39452. var cur = this.parent;
  39453. while (cur) {
  39454. if (cur instanceof Group2D && cur._isRenderableGroup) {
  39455. cur._renderableData._childrenRenderableGroups.push(this);
  39456. break;
  39457. }
  39458. cur = cur.parent;
  39459. }
  39460. }
  39461. };
  39462. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  39463. /**
  39464. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  39465. */
  39466. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  39467. /**
  39468. * When used, this group's content won't be cached, no matter which strategy used.
  39469. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  39470. */
  39471. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  39472. /**
  39473. * When used, the group's content will be cached in the nearest cached parent group/canvas
  39474. */
  39475. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  39476. __decorate([
  39477. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  39478. ], Group2D.prototype, "size", null);
  39479. __decorate([
  39480. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  39481. ], Group2D.prototype, "actualSize", null);
  39482. Group2D = __decorate([
  39483. BABYLON.className("Group2D")
  39484. ], Group2D);
  39485. return Group2D;
  39486. })(BABYLON.Prim2DBase);
  39487. BABYLON.Group2D = Group2D;
  39488. var RenderableGroupData = (function () {
  39489. function RenderableGroupData() {
  39490. this._primDirtyList = new Array();
  39491. this._childrenRenderableGroups = new Array();
  39492. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  39493. this._transparentPrimitives = new Array();
  39494. this._transparentSegments = new Array();
  39495. this._firstChangedPrim = null;
  39496. this._transparentListChanged = false;
  39497. }
  39498. RenderableGroupData.prototype.dispose = function () {
  39499. if (this._cacheRenderSprite) {
  39500. this._cacheRenderSprite.dispose();
  39501. this._cacheRenderSprite = null;
  39502. }
  39503. if (this._cacheTexture && this._cacheNode) {
  39504. this._cacheTexture.freeRect(this._cacheNode);
  39505. this._cacheTexture = null;
  39506. this._cacheNode = null;
  39507. }
  39508. if (this._primDirtyList) {
  39509. this._primDirtyList.splice(0);
  39510. this._primDirtyList = null;
  39511. }
  39512. if (this._renderGroupInstancesInfo) {
  39513. this._renderGroupInstancesInfo.forEach(function (k, v) {
  39514. v.dispose();
  39515. });
  39516. this._renderGroupInstancesInfo = null;
  39517. }
  39518. };
  39519. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  39520. var tpi = new TransparentPrimitiveInfo();
  39521. tpi._primitive = prim;
  39522. tpi._groupInstanceInfo = gii;
  39523. tpi._transparentSegment = null;
  39524. this._transparentPrimitives.push(tpi);
  39525. this._transparentListChanged = true;
  39526. this.updateSmallestZChangedPrim(tpi);
  39527. return tpi;
  39528. };
  39529. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  39530. var index = this._transparentPrimitives.indexOf(tpi);
  39531. if (index !== -1) {
  39532. this._transparentPrimitives.splice(index, 1);
  39533. this._transparentListChanged = true;
  39534. this.updateSmallestZChangedPrim(tpi);
  39535. }
  39536. };
  39537. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  39538. this._transparentListChanged = true;
  39539. this.updateSmallestZChangedPrim(tpi);
  39540. };
  39541. RenderableGroupData.prototype.updateSmallestZChangedPrim = function (tpi) {
  39542. if (tpi._primitive) {
  39543. var newZ = tpi._primitive.getActualZOffset();
  39544. var curZ = this._firstChangedPrim ? this._firstChangedPrim._primitive.getActualZOffset() : Number.MIN_VALUE;
  39545. if (newZ > curZ) {
  39546. this._firstChangedPrim = tpi;
  39547. }
  39548. }
  39549. };
  39550. return RenderableGroupData;
  39551. })();
  39552. BABYLON.RenderableGroupData = RenderableGroupData;
  39553. var TransparentPrimitiveInfo = (function () {
  39554. function TransparentPrimitiveInfo() {
  39555. }
  39556. return TransparentPrimitiveInfo;
  39557. })();
  39558. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  39559. })(BABYLON || (BABYLON = {}));
  39560. var BABYLON;
  39561. (function (BABYLON) {
  39562. var Rectangle2DRenderCache = (function (_super) {
  39563. __extends(Rectangle2DRenderCache, _super);
  39564. function Rectangle2DRenderCache(engine, modelKey) {
  39565. _super.call(this, engine, modelKey);
  39566. this.effectsReady = false;
  39567. this.fillVB = null;
  39568. this.fillIB = null;
  39569. this.fillIndicesCount = 0;
  39570. this.instancingFillAttributes = null;
  39571. this.effectFill = null;
  39572. this.effectFillInstanced = null;
  39573. this.borderVB = null;
  39574. this.borderIB = null;
  39575. this.borderIndicesCount = 0;
  39576. this.instancingBorderAttributes = null;
  39577. this.effectBorder = null;
  39578. this.effectBorderInstanced = null;
  39579. }
  39580. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  39581. // Do nothing if the shader is still loading/preparing
  39582. if (!this.effectsReady) {
  39583. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  39584. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  39585. return false;
  39586. }
  39587. this.effectsReady = true;
  39588. }
  39589. var engine = instanceInfo.owner.owner.engine;
  39590. var depthFunction = 0;
  39591. if (this.effectFill && this.effectBorder) {
  39592. depthFunction = engine.getDepthFunction();
  39593. engine.setDepthFunctionToLessOrEqual();
  39594. }
  39595. var curAlphaMode = engine.getAlphaMode();
  39596. if (this.effectFill) {
  39597. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  39598. var pid = context.groupInfoPartData[partIndex];
  39599. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  39600. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39601. }
  39602. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  39603. engine.enableEffect(effect);
  39604. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  39605. if (context.useInstancing) {
  39606. if (!this.instancingFillAttributes) {
  39607. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  39608. }
  39609. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  39610. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  39611. engine.unbindInstanceAttributes();
  39612. }
  39613. else {
  39614. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  39615. this.setupUniforms(effect, partIndex, pid._partData, i);
  39616. engine.draw(true, 0, this.fillIndicesCount);
  39617. }
  39618. }
  39619. }
  39620. if (this.effectBorder) {
  39621. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  39622. var pid = context.groupInfoPartData[partIndex];
  39623. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  39624. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39625. }
  39626. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  39627. engine.enableEffect(effect);
  39628. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  39629. if (context.useInstancing) {
  39630. if (!this.instancingBorderAttributes) {
  39631. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  39632. }
  39633. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  39634. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  39635. engine.unbindInstanceAttributes();
  39636. }
  39637. else {
  39638. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  39639. this.setupUniforms(effect, partIndex, pid._partData, i);
  39640. engine.draw(true, 0, this.borderIndicesCount);
  39641. }
  39642. }
  39643. }
  39644. engine.setAlphaMode(curAlphaMode);
  39645. if (this.effectFill && this.effectBorder) {
  39646. engine.setDepthFunction(depthFunction);
  39647. }
  39648. return true;
  39649. };
  39650. Rectangle2DRenderCache.prototype.dispose = function () {
  39651. if (!_super.prototype.dispose.call(this)) {
  39652. return false;
  39653. }
  39654. if (this.fillVB) {
  39655. this._engine._releaseBuffer(this.fillVB);
  39656. this.fillVB = null;
  39657. }
  39658. if (this.fillIB) {
  39659. this._engine._releaseBuffer(this.fillIB);
  39660. this.fillIB = null;
  39661. }
  39662. if (this.effectFill) {
  39663. this._engine._releaseEffect(this.effectFill);
  39664. this.effectFill = null;
  39665. }
  39666. if (this.effectFillInstanced) {
  39667. this._engine._releaseEffect(this.effectFillInstanced);
  39668. this.effectFillInstanced = null;
  39669. }
  39670. if (this.borderVB) {
  39671. this._engine._releaseBuffer(this.borderVB);
  39672. this.borderVB = null;
  39673. }
  39674. if (this.borderIB) {
  39675. this._engine._releaseBuffer(this.borderIB);
  39676. this.borderIB = null;
  39677. }
  39678. if (this.effectBorder) {
  39679. this._engine._releaseEffect(this.effectBorder);
  39680. this.effectBorder = null;
  39681. }
  39682. if (this.effectBorderInstanced) {
  39683. this._engine._releaseEffect(this.effectBorderInstanced);
  39684. this.effectBorderInstanced = null;
  39685. }
  39686. return true;
  39687. };
  39688. return Rectangle2DRenderCache;
  39689. })(BABYLON.ModelRenderCache);
  39690. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  39691. var Rectangle2DInstanceData = (function (_super) {
  39692. __extends(Rectangle2DInstanceData, _super);
  39693. function Rectangle2DInstanceData(partId) {
  39694. _super.call(this, partId, 1);
  39695. }
  39696. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  39697. get: function () {
  39698. return null;
  39699. },
  39700. enumerable: true,
  39701. configurable: true
  39702. });
  39703. __decorate([
  39704. BABYLON.instanceData()
  39705. ], Rectangle2DInstanceData.prototype, "properties", null);
  39706. return Rectangle2DInstanceData;
  39707. })(BABYLON.Shape2DInstanceData);
  39708. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  39709. var Rectangle2D = (function (_super) {
  39710. __extends(Rectangle2D, _super);
  39711. function Rectangle2D() {
  39712. _super.apply(this, arguments);
  39713. }
  39714. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  39715. get: function () {
  39716. return this.size;
  39717. },
  39718. enumerable: true,
  39719. configurable: true
  39720. });
  39721. Object.defineProperty(Rectangle2D.prototype, "size", {
  39722. get: function () {
  39723. return this._size;
  39724. },
  39725. set: function (value) {
  39726. this._size = value;
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  39732. get: function () {
  39733. return this._notRounded;
  39734. },
  39735. set: function (value) {
  39736. this._notRounded = value;
  39737. },
  39738. enumerable: true,
  39739. configurable: true
  39740. });
  39741. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  39742. get: function () {
  39743. return this._roundRadius;
  39744. },
  39745. set: function (value) {
  39746. this._roundRadius = value;
  39747. this.notRounded = value === 0;
  39748. },
  39749. enumerable: true,
  39750. configurable: true
  39751. });
  39752. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  39753. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  39754. if (this.notRounded) {
  39755. return true;
  39756. }
  39757. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  39758. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  39759. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  39760. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  39761. var o = this.origin;
  39762. var size = this.size;
  39763. Rectangle2D._i0.x = intersectInfo._localPickPosition.x + (size.width * o.x);
  39764. Rectangle2D._i0.y = intersectInfo._localPickPosition.y + (size.height * o.y);
  39765. var rr = this.roundRadius;
  39766. var rrs = rr * rr;
  39767. // Check if the point is in the bottom/left quarter area
  39768. Rectangle2D._i1.x = rr;
  39769. Rectangle2D._i1.y = rr;
  39770. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  39771. // Compute the intersection point in the quarter local space
  39772. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  39773. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  39774. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  39775. return Rectangle2D._i2.lengthSquared() <= rrs;
  39776. }
  39777. // Check if the point is in the top/left quarter area
  39778. Rectangle2D._i1.x = rr;
  39779. Rectangle2D._i1.y = size.height - rr;
  39780. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  39781. // Compute the intersection point in the quarter local space
  39782. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  39783. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  39784. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  39785. return Rectangle2D._i2.lengthSquared() <= rrs;
  39786. }
  39787. // Check if the point is in the top/right quarter area
  39788. Rectangle2D._i1.x = size.width - rr;
  39789. Rectangle2D._i1.y = size.height - rr;
  39790. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  39791. // Compute the intersection point in the quarter local space
  39792. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  39793. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  39794. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  39795. return Rectangle2D._i2.lengthSquared() <= rrs;
  39796. }
  39797. // Check if the point is in the bottom/right quarter area
  39798. Rectangle2D._i1.x = size.width - rr;
  39799. Rectangle2D._i1.y = rr;
  39800. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  39801. // Compute the intersection point in the quarter local space
  39802. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  39803. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  39804. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  39805. return Rectangle2D._i2.lengthSquared() <= rrs;
  39806. }
  39807. // At any other locations the point is guarantied to be inside
  39808. return true;
  39809. };
  39810. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  39811. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  39812. };
  39813. Rectangle2D.prototype.setupRectangle2D = function (owner, parent, id, position, origin, size, roundRadius, fill, border, borderThickness, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  39814. this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
  39815. this.size = size;
  39816. this.notRounded = !roundRadius;
  39817. this.roundRadius = roundRadius;
  39818. };
  39819. /**
  39820. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  39821. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  39822. * options:
  39823. * - id a text identifier, for information purpose
  39824. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  39825. * - origin: define the normalized origin point location, default [0.5;0.5]
  39826. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  39827. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp rectangle).
  39828. * - 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.
  39829. * - 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.
  39830. * - borderThickness: the thickness of the drawn border, default is 1.
  39831. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  39832. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  39833. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  39834. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  39835. */
  39836. Rectangle2D.Create = function (parent, options) {
  39837. BABYLON.Prim2DBase.CheckParent(parent);
  39838. var rect = new Rectangle2D();
  39839. if (!options) {
  39840. rect.setupRectangle2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, new BABYLON.Size(10, 10), 0, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"), null, 1, true, null, null, null, null, null, null);
  39841. }
  39842. else {
  39843. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  39844. var size = options.size || (new BABYLON.Size(options.width || 10, options.height || 10));
  39845. var fill = options.fill === undefined ? BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF") : options.fill;
  39846. rect.setupRectangle2D(parent.owner, parent, options.id || null, pos, options.origin || null, size, (options.roundRadius == null) ? 0 : options.roundRadius, fill, options.border || null, (options.borderThickness == null) ? 1 : options.borderThickness, options.isVisible || true, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
  39847. }
  39848. return rect;
  39849. };
  39850. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  39851. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  39852. return renderCache;
  39853. };
  39854. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  39855. var renderCache = modelRenderCache;
  39856. var engine = this.owner.engine;
  39857. // Need to create WebGL resources for fill part?
  39858. if (this.fill) {
  39859. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  39860. var vb = new Float32Array(vbSize);
  39861. for (var i = 0; i < vbSize; i++) {
  39862. vb[i] = i;
  39863. }
  39864. renderCache.fillVB = engine.createVertexBuffer(vb);
  39865. var triCount = vbSize - 1;
  39866. var ib = new Float32Array(triCount * 3);
  39867. for (var i = 0; i < triCount; i++) {
  39868. ib[i * 3 + 0] = 0;
  39869. ib[i * 3 + 2] = i + 1;
  39870. ib[i * 3 + 1] = i + 2;
  39871. }
  39872. ib[triCount * 3 - 2] = 1;
  39873. renderCache.fillIB = engine.createIndexBuffer(ib);
  39874. renderCache.fillIndicesCount = triCount * 3;
  39875. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  39876. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  39877. if (ei) {
  39878. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  39879. }
  39880. // Get the non instanced version
  39881. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  39882. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  39883. }
  39884. // Need to create WebGL resource for border part?
  39885. if (this.border) {
  39886. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  39887. var vb = new Float32Array(vbSize);
  39888. for (var i = 0; i < vbSize; i++) {
  39889. vb[i] = i;
  39890. }
  39891. renderCache.borderVB = engine.createVertexBuffer(vb);
  39892. var triCount = vbSize;
  39893. var rs = triCount / 2;
  39894. var ib = new Float32Array(triCount * 3);
  39895. for (var i = 0; i < rs; i++) {
  39896. var r0 = i;
  39897. var r1 = (i + 1) % rs;
  39898. ib[i * 6 + 0] = rs + r1;
  39899. ib[i * 6 + 1] = rs + r0;
  39900. ib[i * 6 + 2] = r0;
  39901. ib[i * 6 + 3] = r1;
  39902. ib[i * 6 + 4] = rs + r1;
  39903. ib[i * 6 + 5] = r0;
  39904. }
  39905. renderCache.borderIB = engine.createIndexBuffer(ib);
  39906. renderCache.borderIndicesCount = triCount * 3;
  39907. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  39908. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  39909. if (ei) {
  39910. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  39911. }
  39912. // Get the non instanced version
  39913. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  39914. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  39915. }
  39916. return renderCache;
  39917. };
  39918. Rectangle2D.prototype.createInstanceDataParts = function () {
  39919. var res = new Array();
  39920. if (this.border) {
  39921. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  39922. }
  39923. if (this.fill) {
  39924. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  39925. }
  39926. return res;
  39927. };
  39928. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  39929. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  39930. return false;
  39931. }
  39932. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  39933. var d = part;
  39934. var size = this.size;
  39935. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  39936. }
  39937. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  39938. var d = part;
  39939. var size = this.size;
  39940. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  39941. }
  39942. return true;
  39943. };
  39944. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  39945. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  39946. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  39947. Rectangle2D.roundSubdivisions = 16;
  39948. __decorate([
  39949. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.sizeProperty = pi; }, false, true)
  39950. ], Rectangle2D.prototype, "size", null);
  39951. __decorate([
  39952. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  39953. ], Rectangle2D.prototype, "notRounded", null);
  39954. __decorate([
  39955. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  39956. ], Rectangle2D.prototype, "roundRadius", null);
  39957. Rectangle2D = __decorate([
  39958. BABYLON.className("Rectangle2D")
  39959. ], Rectangle2D);
  39960. return Rectangle2D;
  39961. })(BABYLON.Shape2D);
  39962. BABYLON.Rectangle2D = Rectangle2D;
  39963. })(BABYLON || (BABYLON = {}));
  39964. var BABYLON;
  39965. (function (BABYLON) {
  39966. var Ellipse2DRenderCache = (function (_super) {
  39967. __extends(Ellipse2DRenderCache, _super);
  39968. function Ellipse2DRenderCache(engine, modelKey) {
  39969. _super.call(this, engine, modelKey);
  39970. this.effectsReady = false;
  39971. this.fillVB = null;
  39972. this.fillIB = null;
  39973. this.fillIndicesCount = 0;
  39974. this.instancingFillAttributes = null;
  39975. this.effectFillInstanced = null;
  39976. this.effectFill = null;
  39977. this.borderVB = null;
  39978. this.borderIB = null;
  39979. this.borderIndicesCount = 0;
  39980. this.instancingBorderAttributes = null;
  39981. this.effectBorderInstanced = null;
  39982. this.effectBorder = null;
  39983. }
  39984. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  39985. // Do nothing if the shader is still loading/preparing
  39986. if (!this.effectsReady) {
  39987. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  39988. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  39989. return false;
  39990. }
  39991. this.effectsReady = true;
  39992. }
  39993. var engine = instanceInfo.owner.owner.engine;
  39994. var depthFunction = 0;
  39995. if (this.effectFill && this.effectBorder) {
  39996. depthFunction = engine.getDepthFunction();
  39997. engine.setDepthFunctionToLessOrEqual();
  39998. }
  39999. var curAlphaMode = engine.getAlphaMode();
  40000. if (this.effectFill) {
  40001. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  40002. var pid = context.groupInfoPartData[partIndex];
  40003. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  40004. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40005. }
  40006. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  40007. engine.enableEffect(effect);
  40008. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  40009. if (context.useInstancing) {
  40010. if (!this.instancingFillAttributes) {
  40011. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  40012. }
  40013. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  40014. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  40015. engine.unbindInstanceAttributes();
  40016. }
  40017. else {
  40018. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  40019. this.setupUniforms(effect, partIndex, pid._partData, i);
  40020. engine.draw(true, 0, this.fillIndicesCount);
  40021. }
  40022. }
  40023. }
  40024. if (this.effectBorder) {
  40025. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  40026. var pid = context.groupInfoPartData[partIndex];
  40027. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  40028. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40029. }
  40030. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  40031. engine.enableEffect(effect);
  40032. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  40033. if (context.useInstancing) {
  40034. if (!this.instancingBorderAttributes) {
  40035. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  40036. }
  40037. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  40038. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  40039. engine.unbindInstanceAttributes();
  40040. }
  40041. else {
  40042. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  40043. this.setupUniforms(effect, partIndex, pid._partData, i);
  40044. engine.draw(true, 0, this.borderIndicesCount);
  40045. }
  40046. }
  40047. }
  40048. engine.setAlphaMode(curAlphaMode);
  40049. if (this.effectFill && this.effectBorder) {
  40050. engine.setDepthFunction(depthFunction);
  40051. }
  40052. return true;
  40053. };
  40054. Ellipse2DRenderCache.prototype.dispose = function () {
  40055. if (!_super.prototype.dispose.call(this)) {
  40056. return false;
  40057. }
  40058. if (this.fillVB) {
  40059. this._engine._releaseBuffer(this.fillVB);
  40060. this.fillVB = null;
  40061. }
  40062. if (this.fillIB) {
  40063. this._engine._releaseBuffer(this.fillIB);
  40064. this.fillIB = null;
  40065. }
  40066. if (this.effectFill) {
  40067. this._engine._releaseEffect(this.effectFill);
  40068. this.effectFill = null;
  40069. }
  40070. if (this.effectFillInstanced) {
  40071. this._engine._releaseEffect(this.effectFillInstanced);
  40072. this.effectFillInstanced = null;
  40073. }
  40074. if (this.borderVB) {
  40075. this._engine._releaseBuffer(this.borderVB);
  40076. this.borderVB = null;
  40077. }
  40078. if (this.borderIB) {
  40079. this._engine._releaseBuffer(this.borderIB);
  40080. this.borderIB = null;
  40081. }
  40082. if (this.effectBorder) {
  40083. this._engine._releaseEffect(this.effectBorder);
  40084. this.effectBorder = null;
  40085. }
  40086. if (this.effectBorderInstanced) {
  40087. this._engine._releaseEffect(this.effectBorderInstanced);
  40088. this.effectBorderInstanced = null;
  40089. }
  40090. return true;
  40091. };
  40092. return Ellipse2DRenderCache;
  40093. })(BABYLON.ModelRenderCache);
  40094. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  40095. var Ellipse2DInstanceData = (function (_super) {
  40096. __extends(Ellipse2DInstanceData, _super);
  40097. function Ellipse2DInstanceData(partId) {
  40098. _super.call(this, partId, 1);
  40099. }
  40100. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  40101. get: function () {
  40102. return null;
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. __decorate([
  40108. BABYLON.instanceData()
  40109. ], Ellipse2DInstanceData.prototype, "properties", null);
  40110. return Ellipse2DInstanceData;
  40111. })(BABYLON.Shape2DInstanceData);
  40112. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  40113. var Ellipse2D = (function (_super) {
  40114. __extends(Ellipse2D, _super);
  40115. function Ellipse2D() {
  40116. _super.apply(this, arguments);
  40117. }
  40118. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  40119. get: function () {
  40120. return this.size;
  40121. },
  40122. enumerable: true,
  40123. configurable: true
  40124. });
  40125. Object.defineProperty(Ellipse2D.prototype, "size", {
  40126. get: function () {
  40127. return this._size;
  40128. },
  40129. set: function (value) {
  40130. this._size = value;
  40131. },
  40132. enumerable: true,
  40133. configurable: true
  40134. });
  40135. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  40136. get: function () {
  40137. return this._subdivisions;
  40138. },
  40139. set: function (value) {
  40140. this._subdivisions = value;
  40141. },
  40142. enumerable: true,
  40143. configurable: true
  40144. });
  40145. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  40146. var x = intersectInfo._localPickPosition.x;
  40147. var y = intersectInfo._localPickPosition.y;
  40148. var w = this.size.width / 2;
  40149. var h = this.size.height / 2;
  40150. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  40151. };
  40152. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  40153. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  40154. };
  40155. Ellipse2D.prototype.setupEllipse2D = function (owner, parent, id, position, origin, size, subdivisions, fill, border, borderThickness, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  40156. this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
  40157. this.size = size;
  40158. this.subdivisions = subdivisions;
  40159. };
  40160. /**
  40161. * Create an Ellipse 2D Shape primitive
  40162. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  40163. * options:
  40164. * - id: a text identifier, for information purpose
  40165. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  40166. * - origin: define the normalized origin point location, default [0.5;0.5]
  40167. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  40168. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  40169. * - 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.
  40170. * - 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.
  40171. * - borderThickness: the thickness of the drawn border, default is 1.
  40172. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  40173. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  40174. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40175. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40176. */
  40177. Ellipse2D.Create = function (parent, options) {
  40178. BABYLON.Prim2DBase.CheckParent(parent);
  40179. var ellipse = new Ellipse2D();
  40180. if (!options) {
  40181. ellipse.setupEllipse2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, new BABYLON.Size(10, 10), 64, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"), null, 1, true, null, null, null, null, null, null);
  40182. }
  40183. else {
  40184. var fill;
  40185. if (options.fill === undefined) {
  40186. fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  40187. }
  40188. else {
  40189. fill = options.fill;
  40190. }
  40191. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  40192. var size = options.size || (new BABYLON.Size(options.width || 10, options.height || 10));
  40193. ellipse.setupEllipse2D(parent.owner, parent, options.id || null, pos, options.origin || null, size, (options.subdivisions == null) ? 64 : options.subdivisions, fill, options.border || null, (options.borderThickness == null) ? 1 : options.borderThickness, (options.isVisible == null) ? true : options.isVisible, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
  40194. }
  40195. return ellipse;
  40196. };
  40197. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  40198. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  40199. return renderCache;
  40200. };
  40201. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40202. var renderCache = modelRenderCache;
  40203. var engine = this.owner.engine;
  40204. // Need to create WebGL resources for fill part?
  40205. if (this.fill) {
  40206. var vbSize = this.subdivisions + 1;
  40207. var vb = new Float32Array(vbSize);
  40208. for (var i = 0; i < vbSize; i++) {
  40209. vb[i] = i;
  40210. }
  40211. renderCache.fillVB = engine.createVertexBuffer(vb);
  40212. var triCount = vbSize - 1;
  40213. var ib = new Float32Array(triCount * 3);
  40214. for (var i = 0; i < triCount; i++) {
  40215. ib[i * 3 + 0] = 0;
  40216. ib[i * 3 + 2] = i + 1;
  40217. ib[i * 3 + 1] = i + 2;
  40218. }
  40219. ib[triCount * 3 - 2] = 1;
  40220. renderCache.fillIB = engine.createIndexBuffer(ib);
  40221. renderCache.fillIndicesCount = triCount * 3;
  40222. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  40223. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  40224. if (ei) {
  40225. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  40226. }
  40227. // Get the non instanced version
  40228. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  40229. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  40230. }
  40231. // Need to create WebGL resource for border part?
  40232. if (this.border) {
  40233. var vbSize = this.subdivisions * 2;
  40234. var vb = new Float32Array(vbSize);
  40235. for (var i = 0; i < vbSize; i++) {
  40236. vb[i] = i;
  40237. }
  40238. renderCache.borderVB = engine.createVertexBuffer(vb);
  40239. var triCount = vbSize;
  40240. var rs = triCount / 2;
  40241. var ib = new Float32Array(triCount * 3);
  40242. for (var i = 0; i < rs; i++) {
  40243. var r0 = i;
  40244. var r1 = (i + 1) % rs;
  40245. ib[i * 6 + 0] = rs + r1;
  40246. ib[i * 6 + 1] = rs + r0;
  40247. ib[i * 6 + 2] = r0;
  40248. ib[i * 6 + 3] = r1;
  40249. ib[i * 6 + 4] = rs + r1;
  40250. ib[i * 6 + 5] = r0;
  40251. }
  40252. renderCache.borderIB = engine.createIndexBuffer(ib);
  40253. renderCache.borderIndicesCount = (triCount * 3);
  40254. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  40255. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  40256. if (ei) {
  40257. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  40258. }
  40259. // Get the non instanced version
  40260. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  40261. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  40262. }
  40263. return renderCache;
  40264. };
  40265. Ellipse2D.prototype.createInstanceDataParts = function () {
  40266. var res = new Array();
  40267. if (this.border) {
  40268. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  40269. }
  40270. if (this.fill) {
  40271. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  40272. }
  40273. return res;
  40274. };
  40275. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  40276. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40277. return false;
  40278. }
  40279. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  40280. var d = part;
  40281. var size = this.size;
  40282. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  40283. }
  40284. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  40285. var d = part;
  40286. var size = this.size;
  40287. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  40288. }
  40289. return true;
  40290. };
  40291. __decorate([
  40292. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.sizeProperty = pi; }, false, true)
  40293. ], Ellipse2D.prototype, "size", null);
  40294. __decorate([
  40295. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  40296. ], Ellipse2D.prototype, "subdivisions", null);
  40297. Ellipse2D = __decorate([
  40298. BABYLON.className("Ellipse2D")
  40299. ], Ellipse2D);
  40300. return Ellipse2D;
  40301. })(BABYLON.Shape2D);
  40302. BABYLON.Ellipse2D = Ellipse2D;
  40303. })(BABYLON || (BABYLON = {}));
  40304. var BABYLON;
  40305. (function (BABYLON) {
  40306. var Sprite2DRenderCache = (function (_super) {
  40307. __extends(Sprite2DRenderCache, _super);
  40308. function Sprite2DRenderCache() {
  40309. _super.apply(this, arguments);
  40310. this.effectsReady = false;
  40311. this.vb = null;
  40312. this.ib = null;
  40313. this.instancingAttributes = null;
  40314. this.texture = null;
  40315. this.effect = null;
  40316. this.effectInstanced = null;
  40317. }
  40318. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  40319. // Do nothing if the shader is still loading/preparing
  40320. if (!this.effectsReady) {
  40321. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  40322. return false;
  40323. }
  40324. this.effectsReady = true;
  40325. }
  40326. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  40327. var engine = instanceInfo.owner.owner.engine;
  40328. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  40329. engine.enableEffect(effect);
  40330. effect.setTexture("diffuseSampler", this.texture);
  40331. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  40332. var cur = engine.getAlphaMode();
  40333. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  40334. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40335. }
  40336. var pid = context.groupInfoPartData[0];
  40337. if (context.useInstancing) {
  40338. if (!this.instancingAttributes) {
  40339. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  40340. }
  40341. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  40342. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  40343. engine.unbindInstanceAttributes();
  40344. }
  40345. else {
  40346. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  40347. this.setupUniforms(effect, 0, pid._partData, i);
  40348. engine.draw(true, 0, 6);
  40349. }
  40350. }
  40351. engine.setAlphaMode(cur);
  40352. return true;
  40353. };
  40354. Sprite2DRenderCache.prototype.dispose = function () {
  40355. if (!_super.prototype.dispose.call(this)) {
  40356. return false;
  40357. }
  40358. if (this.vb) {
  40359. this._engine._releaseBuffer(this.vb);
  40360. this.vb = null;
  40361. }
  40362. if (this.ib) {
  40363. this._engine._releaseBuffer(this.ib);
  40364. this.ib = null;
  40365. }
  40366. if (this.texture) {
  40367. this.texture.dispose();
  40368. this.texture = null;
  40369. }
  40370. if (this.effect) {
  40371. this._engine._releaseEffect(this.effect);
  40372. this.effect = null;
  40373. }
  40374. if (this.effectInstanced) {
  40375. this._engine._releaseEffect(this.effectInstanced);
  40376. this.effectInstanced = null;
  40377. }
  40378. return true;
  40379. };
  40380. return Sprite2DRenderCache;
  40381. })(BABYLON.ModelRenderCache);
  40382. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  40383. var Sprite2DInstanceData = (function (_super) {
  40384. __extends(Sprite2DInstanceData, _super);
  40385. function Sprite2DInstanceData(partId) {
  40386. _super.call(this, partId, 1);
  40387. }
  40388. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  40389. get: function () {
  40390. return null;
  40391. },
  40392. enumerable: true,
  40393. configurable: true
  40394. });
  40395. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  40396. get: function () {
  40397. return null;
  40398. },
  40399. enumerable: true,
  40400. configurable: true
  40401. });
  40402. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  40403. get: function () {
  40404. return null;
  40405. },
  40406. enumerable: true,
  40407. configurable: true
  40408. });
  40409. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  40410. // 3 floats being:
  40411. // - x: frame number to display
  40412. // - y: invertY setting
  40413. // - z: alignToPixel setting
  40414. get: function () {
  40415. return null;
  40416. },
  40417. enumerable: true,
  40418. configurable: true
  40419. });
  40420. __decorate([
  40421. BABYLON.instanceData()
  40422. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  40423. __decorate([
  40424. BABYLON.instanceData()
  40425. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  40426. __decorate([
  40427. BABYLON.instanceData()
  40428. ], Sprite2DInstanceData.prototype, "textureSize", null);
  40429. __decorate([
  40430. BABYLON.instanceData()
  40431. ], Sprite2DInstanceData.prototype, "properties", null);
  40432. return Sprite2DInstanceData;
  40433. })(BABYLON.InstanceDataBase);
  40434. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  40435. var Sprite2D = (function (_super) {
  40436. __extends(Sprite2D, _super);
  40437. function Sprite2D() {
  40438. _super.apply(this, arguments);
  40439. }
  40440. Object.defineProperty(Sprite2D.prototype, "texture", {
  40441. get: function () {
  40442. return this._texture;
  40443. },
  40444. set: function (value) {
  40445. this._texture = value;
  40446. },
  40447. enumerable: true,
  40448. configurable: true
  40449. });
  40450. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  40451. get: function () {
  40452. return this.spriteSize;
  40453. },
  40454. enumerable: true,
  40455. configurable: true
  40456. });
  40457. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  40458. get: function () {
  40459. return this._size;
  40460. },
  40461. set: function (value) {
  40462. this._size = value;
  40463. },
  40464. enumerable: true,
  40465. configurable: true
  40466. });
  40467. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  40468. get: function () {
  40469. return this._location;
  40470. },
  40471. set: function (value) {
  40472. this._location = value;
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  40478. get: function () {
  40479. return this._spriteFrame;
  40480. },
  40481. set: function (value) {
  40482. this._spriteFrame = value;
  40483. },
  40484. enumerable: true,
  40485. configurable: true
  40486. });
  40487. Object.defineProperty(Sprite2D.prototype, "invertY", {
  40488. get: function () {
  40489. return this._invertY;
  40490. },
  40491. set: function (value) {
  40492. this._invertY = value;
  40493. },
  40494. enumerable: true,
  40495. configurable: true
  40496. });
  40497. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  40498. get: function () {
  40499. return this._alignToPixel;
  40500. },
  40501. set: function (value) {
  40502. this._alignToPixel = value;
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  40508. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.spriteSize, this._levelBoundingInfo, this.origin);
  40509. };
  40510. Sprite2D.prototype.getAnimatables = function () {
  40511. var res = new Array();
  40512. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  40513. res.push(this.texture);
  40514. }
  40515. return res;
  40516. };
  40517. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  40518. // 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
  40519. return true;
  40520. };
  40521. Sprite2D.prototype.setupSprite2D = function (owner, parent, id, position, origin, texture, spriteSize, spriteLocation, invertY, alignToPixel, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  40522. this.setupRenderablePrim2D(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
  40523. this.texture = texture;
  40524. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40525. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40526. this.spriteSize = spriteSize || null;
  40527. this.spriteLocation = spriteLocation || new BABYLON.Vector2(0, 0);
  40528. this.spriteFrame = 0;
  40529. this.invertY = invertY;
  40530. this.alignToPixel = alignToPixel;
  40531. this._isTransparent = true;
  40532. if (!this.spriteSize) {
  40533. var s = texture.getSize();
  40534. this.spriteSize = new BABYLON.Size(s.width, s.height);
  40535. }
  40536. };
  40537. /**
  40538. * Create an 2D Sprite primitive
  40539. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  40540. * @param texture the texture that stores the sprite to render
  40541. * options:
  40542. * - id a text identifier, for information purpose
  40543. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  40544. * - origin: define the normalized origin point location, default [0.5;0.5]
  40545. * - spriteSize: the size of the sprite, if null the size of the given texture will be used, default is null.
  40546. * - spriteLocation: the location in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  40547. * - invertY: if true the texture Y will be inverted, default is false.
  40548. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  40549. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  40550. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  40551. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40552. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40553. */
  40554. Sprite2D.Create = function (parent, texture, options) {
  40555. BABYLON.Prim2DBase.CheckParent(parent);
  40556. var sprite = new Sprite2D();
  40557. if (!options) {
  40558. sprite.setupSprite2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, texture, null, null, false, true, true, null, null, null, null, null, null);
  40559. }
  40560. else {
  40561. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  40562. sprite.setupSprite2D(parent.owner, parent, options.id || null, pos, options.origin || null, texture, options.spriteSize || null, options.spriteLocation || null, (options.invertY == null) ? false : options.invertY, (options.alignToPixel == null) ? true : options.alignToPixel, (options.isVisible == null) ? true : options.isVisible, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
  40563. }
  40564. return sprite;
  40565. };
  40566. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  40567. var sprite = new Sprite2D();
  40568. sprite.setupSprite2D(owner, null, "__cachedCanvasSprite__", new BABYLON.Vector2(0, 0), null, texture, size, pos, false, true, true, null, null, null, null, null, null);
  40569. return sprite;
  40570. };
  40571. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  40572. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  40573. return renderCache;
  40574. };
  40575. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40576. var renderCache = modelRenderCache;
  40577. var engine = this.owner.engine;
  40578. var vb = new Float32Array(4);
  40579. for (var i = 0; i < 4; i++) {
  40580. vb[i] = i;
  40581. }
  40582. renderCache.vb = engine.createVertexBuffer(vb);
  40583. var ib = new Float32Array(6);
  40584. ib[0] = 0;
  40585. ib[1] = 2;
  40586. ib[2] = 1;
  40587. ib[3] = 0;
  40588. ib[4] = 3;
  40589. ib[5] = 2;
  40590. renderCache.ib = engine.createIndexBuffer(ib);
  40591. renderCache.texture = this.texture;
  40592. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  40593. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  40594. if (ei) {
  40595. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  40596. }
  40597. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  40598. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  40599. return renderCache;
  40600. };
  40601. Sprite2D.prototype.createInstanceDataParts = function () {
  40602. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  40603. };
  40604. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  40605. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40606. return false;
  40607. }
  40608. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  40609. var d = this._instanceDataParts[0];
  40610. var ts = this.texture.getBaseSize();
  40611. var sl = this.spriteLocation;
  40612. var ss = this.spriteSize;
  40613. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  40614. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  40615. d.sizeUV = suv;
  40616. Sprite2D._prop.x = this.spriteFrame;
  40617. Sprite2D._prop.y = this.invertY ? 1 : 0;
  40618. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  40619. d.properties = Sprite2D._prop;
  40620. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  40621. }
  40622. return true;
  40623. };
  40624. Sprite2D.SPRITE2D_MAINPARTID = 1;
  40625. Sprite2D._prop = BABYLON.Vector3.Zero();
  40626. __decorate([
  40627. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  40628. ], Sprite2D.prototype, "texture", null);
  40629. __decorate([
  40630. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.spriteSizeProperty = pi; }, false, true)
  40631. ], Sprite2D.prototype, "spriteSize", null);
  40632. __decorate([
  40633. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  40634. ], Sprite2D.prototype, "spriteLocation", null);
  40635. __decorate([
  40636. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  40637. ], Sprite2D.prototype, "spriteFrame", null);
  40638. __decorate([
  40639. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  40640. ], Sprite2D.prototype, "invertY", null);
  40641. Sprite2D = __decorate([
  40642. BABYLON.className("Sprite2D")
  40643. ], Sprite2D);
  40644. return Sprite2D;
  40645. })(BABYLON.RenderablePrim2D);
  40646. BABYLON.Sprite2D = Sprite2D;
  40647. })(BABYLON || (BABYLON = {}));
  40648. var BABYLON;
  40649. (function (BABYLON) {
  40650. var Text2DRenderCache = (function (_super) {
  40651. __extends(Text2DRenderCache, _super);
  40652. function Text2DRenderCache() {
  40653. _super.apply(this, arguments);
  40654. this.effectsReady = false;
  40655. this.vb = null;
  40656. this.ib = null;
  40657. this.instancingAttributes = null;
  40658. this.fontTexture = null;
  40659. this.effect = null;
  40660. this.effectInstanced = null;
  40661. }
  40662. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  40663. // Do nothing if the shader is still loading/preparing
  40664. if (!this.effectsReady) {
  40665. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  40666. return false;
  40667. }
  40668. this.effectsReady = true;
  40669. }
  40670. var engine = instanceInfo.owner.owner.engine;
  40671. this.fontTexture.update();
  40672. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  40673. engine.enableEffect(effect);
  40674. effect.setTexture("diffuseSampler", this.fontTexture);
  40675. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  40676. var curAlphaMode = engine.getAlphaMode();
  40677. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  40678. var pid = context.groupInfoPartData[0];
  40679. if (context.useInstancing) {
  40680. if (!this.instancingAttributes) {
  40681. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  40682. }
  40683. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingAttributes);
  40684. engine.draw(true, 0, 6, pid._partData.usedElementCount);
  40685. engine.unbindInstanceAttributes();
  40686. }
  40687. else {
  40688. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  40689. this.setupUniforms(effect, 0, pid._partData, i);
  40690. engine.draw(true, 0, 6);
  40691. }
  40692. }
  40693. engine.setAlphaMode(curAlphaMode);
  40694. return true;
  40695. };
  40696. Text2DRenderCache.prototype.dispose = function () {
  40697. if (!_super.prototype.dispose.call(this)) {
  40698. return false;
  40699. }
  40700. if (this.vb) {
  40701. this._engine._releaseBuffer(this.vb);
  40702. this.vb = null;
  40703. }
  40704. if (this.ib) {
  40705. this._engine._releaseBuffer(this.ib);
  40706. this.ib = null;
  40707. }
  40708. if (this.fontTexture) {
  40709. this.fontTexture.dispose();
  40710. this.fontTexture = null;
  40711. }
  40712. if (this.effect) {
  40713. this._engine._releaseEffect(this.effect);
  40714. this.effect = null;
  40715. }
  40716. if (this.effectInstanced) {
  40717. this._engine._releaseEffect(this.effectInstanced);
  40718. this.effectInstanced = null;
  40719. }
  40720. return true;
  40721. };
  40722. return Text2DRenderCache;
  40723. })(BABYLON.ModelRenderCache);
  40724. BABYLON.Text2DRenderCache = Text2DRenderCache;
  40725. var Text2DInstanceData = (function (_super) {
  40726. __extends(Text2DInstanceData, _super);
  40727. function Text2DInstanceData(partId, dataElementCount) {
  40728. _super.call(this, partId, dataElementCount);
  40729. }
  40730. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  40731. get: function () {
  40732. return null;
  40733. },
  40734. enumerable: true,
  40735. configurable: true
  40736. });
  40737. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  40738. get: function () {
  40739. return null;
  40740. },
  40741. enumerable: true,
  40742. configurable: true
  40743. });
  40744. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  40745. get: function () {
  40746. return null;
  40747. },
  40748. enumerable: true,
  40749. configurable: true
  40750. });
  40751. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  40752. get: function () {
  40753. return null;
  40754. },
  40755. enumerable: true,
  40756. configurable: true
  40757. });
  40758. __decorate([
  40759. BABYLON.instanceData()
  40760. ], Text2DInstanceData.prototype, "topLeftUV", null);
  40761. __decorate([
  40762. BABYLON.instanceData()
  40763. ], Text2DInstanceData.prototype, "sizeUV", null);
  40764. __decorate([
  40765. BABYLON.instanceData()
  40766. ], Text2DInstanceData.prototype, "textureSize", null);
  40767. __decorate([
  40768. BABYLON.instanceData()
  40769. ], Text2DInstanceData.prototype, "color", null);
  40770. return Text2DInstanceData;
  40771. })(BABYLON.InstanceDataBase);
  40772. BABYLON.Text2DInstanceData = Text2DInstanceData;
  40773. var Text2D = (function (_super) {
  40774. __extends(Text2D, _super);
  40775. function Text2D() {
  40776. _super.apply(this, arguments);
  40777. }
  40778. Object.defineProperty(Text2D.prototype, "fontName", {
  40779. get: function () {
  40780. return this._fontName;
  40781. },
  40782. set: function (value) {
  40783. if (this._fontName) {
  40784. throw new Error("Font Name change is not supported right now.");
  40785. }
  40786. this._fontName = value;
  40787. },
  40788. enumerable: true,
  40789. configurable: true
  40790. });
  40791. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  40792. get: function () {
  40793. return this._defaultFontColor;
  40794. },
  40795. set: function (value) {
  40796. this._defaultFontColor = value;
  40797. },
  40798. enumerable: true,
  40799. configurable: true
  40800. });
  40801. Object.defineProperty(Text2D.prototype, "text", {
  40802. get: function () {
  40803. return this._text;
  40804. },
  40805. set: function (value) {
  40806. this._text = value;
  40807. this._actualSize = null; // A change of text will reset the Actual Area Size which will be recomputed next time it's used
  40808. this._updateCharCount();
  40809. },
  40810. enumerable: true,
  40811. configurable: true
  40812. });
  40813. Object.defineProperty(Text2D.prototype, "areaSize", {
  40814. get: function () {
  40815. return this._areaSize;
  40816. },
  40817. set: function (value) {
  40818. this._areaSize = value;
  40819. },
  40820. enumerable: true,
  40821. configurable: true
  40822. });
  40823. Object.defineProperty(Text2D.prototype, "actualSize", {
  40824. get: function () {
  40825. if (this.areaSize) {
  40826. return this.areaSize;
  40827. }
  40828. if (this._actualSize) {
  40829. return this._actualSize;
  40830. }
  40831. this._actualSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  40832. return this._actualSize;
  40833. },
  40834. enumerable: true,
  40835. configurable: true
  40836. });
  40837. Object.defineProperty(Text2D.prototype, "fontTexture", {
  40838. get: function () {
  40839. if (this._fontTexture) {
  40840. return this._fontTexture;
  40841. }
  40842. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName);
  40843. return this._fontTexture;
  40844. },
  40845. enumerable: true,
  40846. configurable: true
  40847. });
  40848. Text2D.prototype.dispose = function () {
  40849. if (!_super.prototype.dispose.call(this)) {
  40850. return false;
  40851. }
  40852. if (this._fontTexture) {
  40853. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName);
  40854. this._fontTexture = null;
  40855. }
  40856. return true;
  40857. };
  40858. Text2D.prototype.updateLevelBoundingInfo = function () {
  40859. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo, this.origin);
  40860. };
  40861. Text2D.prototype.setupText2D = function (owner, parent, id, position, origin, fontName, text, areaSize, defaultFontColor, tabulationSize, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  40862. this.setupRenderablePrim2D(owner, parent, id, position, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
  40863. this.fontName = fontName;
  40864. this.defaultFontColor = defaultFontColor;
  40865. this.text = text;
  40866. this.areaSize = areaSize;
  40867. this._tabulationSize = tabulationSize;
  40868. this.isAlphaTest = true;
  40869. };
  40870. /**
  40871. * Create a Text primitive
  40872. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  40873. * @param text the text to display
  40874. * Options:
  40875. * - id a text identifier, for information purpose
  40876. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  40877. * - origin: define the normalized origin point location, default [0.5;0.5]
  40878. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  40879. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  40880. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  40881. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  40882. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  40883. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  40884. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40885. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  40886. */
  40887. Text2D.Create = function (parent, text, options) {
  40888. BABYLON.Prim2DBase.CheckParent(parent);
  40889. var text2d = new Text2D();
  40890. if (!options) {
  40891. text2d.setupText2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, "12pt Arial", text, null, new BABYLON.Color4(1, 1, 1, 1), 4, true, null, null, null, null, null, null);
  40892. }
  40893. else {
  40894. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  40895. text2d.setupText2D(parent.owner, parent, options.id || null, pos, options.origin || null, options.fontName || "12pt Arial", text, options.areaSize, options.defaultFontColor || new BABYLON.Color4(1, 1, 1, 1), (options.tabulationSize == null) ? 4 : options.tabulationSize, (options.isVisible == null) ? true : options.isVisible, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
  40896. }
  40897. return text2d;
  40898. };
  40899. Text2D.prototype.levelIntersect = function (intersectInfo) {
  40900. // 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...
  40901. return true;
  40902. };
  40903. Text2D.prototype.createModelRenderCache = function (modelKey) {
  40904. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  40905. return renderCache;
  40906. };
  40907. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40908. var renderCache = modelRenderCache;
  40909. var engine = this.owner.engine;
  40910. renderCache.fontTexture = this.fontTexture;
  40911. var vb = new Float32Array(4);
  40912. for (var i = 0; i < 4; i++) {
  40913. vb[i] = i;
  40914. }
  40915. renderCache.vb = engine.createVertexBuffer(vb);
  40916. var ib = new Float32Array(6);
  40917. ib[0] = 0;
  40918. ib[1] = 2;
  40919. ib[2] = 1;
  40920. ib[3] = 0;
  40921. ib[4] = 3;
  40922. ib[5] = 2;
  40923. renderCache.ib = engine.createIndexBuffer(ib);
  40924. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  40925. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  40926. if (ei) {
  40927. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  40928. }
  40929. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  40930. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  40931. return renderCache;
  40932. };
  40933. Text2D.prototype.createInstanceDataParts = function () {
  40934. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  40935. };
  40936. // Looks like a hack!? Yes! Because that's what it is!
  40937. // 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
  40938. // 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)
  40939. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  40940. if (!this._charCount) {
  40941. var curText = this._text;
  40942. this.text = "A";
  40943. return curText;
  40944. }
  40945. };
  40946. // if obj contains something, we restore the _text property
  40947. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  40948. if (obj !== undefined) {
  40949. this.text = obj;
  40950. }
  40951. };
  40952. Text2D.prototype.refreshInstanceDataPart = function (part) {
  40953. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40954. return false;
  40955. }
  40956. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  40957. var d = part;
  40958. var texture = this.fontTexture;
  40959. var ts = texture.getSize();
  40960. var textSize = texture.measureText(this.text, this._tabulationSize);
  40961. var offset = BABYLON.Vector2.Zero();
  40962. var charxpos = 0;
  40963. d.dataElementCount = this._charCount;
  40964. d.curElement = 0;
  40965. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  40966. var char = _a[_i];
  40967. // Line feed
  40968. if (char === "\n") {
  40969. offset.x = 0;
  40970. offset.y -= texture.lineHeight;
  40971. }
  40972. // Tabulation ?
  40973. if (char === "\t") {
  40974. var nextPos = charxpos + this._tabulationSize;
  40975. nextPos = nextPos - (nextPos % this._tabulationSize);
  40976. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  40977. charxpos = nextPos;
  40978. continue;
  40979. }
  40980. if (char < " ") {
  40981. continue;
  40982. }
  40983. this.updateInstanceDataPart(d, offset, textSize);
  40984. var ci = texture.getChar(char);
  40985. offset.x += ci.charWidth;
  40986. d.topLeftUV = ci.topLeftUV;
  40987. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  40988. d.sizeUV = suv;
  40989. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  40990. d.color = this.defaultFontColor;
  40991. ++d.curElement;
  40992. }
  40993. }
  40994. return true;
  40995. };
  40996. Text2D.prototype._updateCharCount = function () {
  40997. var count = 0;
  40998. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  40999. var char = _a[_i];
  41000. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  41001. continue;
  41002. }
  41003. ++count;
  41004. }
  41005. this._charCount = count;
  41006. };
  41007. Text2D.TEXT2D_MAINPARTID = 1;
  41008. __decorate([
  41009. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  41010. ], Text2D.prototype, "fontName", null);
  41011. __decorate([
  41012. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  41013. ], Text2D.prototype, "defaultFontColor", null);
  41014. __decorate([
  41015. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  41016. ], Text2D.prototype, "text", null);
  41017. __decorate([
  41018. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.areaSizeProperty = pi; })
  41019. ], Text2D.prototype, "areaSize", null);
  41020. Text2D = __decorate([
  41021. BABYLON.className("Text2D")
  41022. ], Text2D);
  41023. return Text2D;
  41024. })(BABYLON.RenderablePrim2D);
  41025. BABYLON.Text2D = Text2D;
  41026. })(BABYLON || (BABYLON = {}));
  41027. var BABYLON;
  41028. (function (BABYLON) {
  41029. var Lines2DRenderCache = (function (_super) {
  41030. __extends(Lines2DRenderCache, _super);
  41031. function Lines2DRenderCache(engine, modelKey) {
  41032. _super.call(this, engine, modelKey);
  41033. this.effectsReady = false;
  41034. this.fillVB = null;
  41035. this.fillIB = null;
  41036. this.fillIndicesCount = 0;
  41037. this.instancingFillAttributes = null;
  41038. this.effectFill = null;
  41039. this.effectFillInstanced = null;
  41040. this.borderVB = null;
  41041. this.borderIB = null;
  41042. this.borderIndicesCount = 0;
  41043. this.instancingBorderAttributes = null;
  41044. this.effectBorder = null;
  41045. this.effectBorderInstanced = null;
  41046. }
  41047. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  41048. // Do nothing if the shader is still loading/preparing
  41049. if (!this.effectsReady) {
  41050. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  41051. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  41052. return false;
  41053. }
  41054. this.effectsReady = true;
  41055. }
  41056. var engine = instanceInfo.owner.owner.engine;
  41057. var depthFunction = 0;
  41058. if (this.effectFill && this.effectBorder) {
  41059. depthFunction = engine.getDepthFunction();
  41060. engine.setDepthFunctionToLessOrEqual();
  41061. }
  41062. var curAlphaMode = engine.getAlphaMode();
  41063. if (this.effectFill) {
  41064. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  41065. var pid = context.groupInfoPartData[partIndex];
  41066. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41067. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41068. }
  41069. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  41070. engine.enableEffect(effect);
  41071. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  41072. if (context.useInstancing) {
  41073. if (!this.instancingFillAttributes) {
  41074. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  41075. }
  41076. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingFillAttributes);
  41077. engine.draw(true, 0, this.fillIndicesCount, pid._partData.usedElementCount);
  41078. engine.unbindInstanceAttributes();
  41079. }
  41080. else {
  41081. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41082. this.setupUniforms(effect, partIndex, pid._partData, i);
  41083. engine.draw(true, 0, this.fillIndicesCount);
  41084. }
  41085. }
  41086. }
  41087. if (this.effectBorder) {
  41088. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  41089. var pid = context.groupInfoPartData[partIndex];
  41090. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  41091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41092. }
  41093. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  41094. engine.enableEffect(effect);
  41095. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  41096. if (context.useInstancing) {
  41097. if (!this.instancingBorderAttributes) {
  41098. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  41099. }
  41100. engine.updateAndBindInstancesBuffer(pid._partBuffer, null, this.instancingBorderAttributes);
  41101. engine.draw(true, 0, this.borderIndicesCount, pid._partData.usedElementCount);
  41102. engine.unbindInstanceAttributes();
  41103. }
  41104. else {
  41105. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  41106. this.setupUniforms(effect, partIndex, pid._partData, i);
  41107. engine.draw(true, 0, this.borderIndicesCount);
  41108. }
  41109. }
  41110. }
  41111. engine.setAlphaMode(curAlphaMode);
  41112. if (this.effectFill && this.effectBorder) {
  41113. engine.setDepthFunction(depthFunction);
  41114. }
  41115. return true;
  41116. };
  41117. Lines2DRenderCache.prototype.dispose = function () {
  41118. if (!_super.prototype.dispose.call(this)) {
  41119. return false;
  41120. }
  41121. if (this.fillVB) {
  41122. this._engine._releaseBuffer(this.fillVB);
  41123. this.fillVB = null;
  41124. }
  41125. if (this.fillIB) {
  41126. this._engine._releaseBuffer(this.fillIB);
  41127. this.fillIB = null;
  41128. }
  41129. if (this.effectFill) {
  41130. this._engine._releaseEffect(this.effectFill);
  41131. this.effectFill = null;
  41132. }
  41133. if (this.effectFillInstanced) {
  41134. this._engine._releaseEffect(this.effectFillInstanced);
  41135. this.effectFillInstanced = null;
  41136. }
  41137. if (this.borderVB) {
  41138. this._engine._releaseBuffer(this.borderVB);
  41139. this.borderVB = null;
  41140. }
  41141. if (this.borderIB) {
  41142. this._engine._releaseBuffer(this.borderIB);
  41143. this.borderIB = null;
  41144. }
  41145. if (this.effectBorder) {
  41146. this._engine._releaseEffect(this.effectBorder);
  41147. this.effectBorder = null;
  41148. }
  41149. if (this.effectBorderInstanced) {
  41150. this._engine._releaseEffect(this.effectBorderInstanced);
  41151. this.effectBorderInstanced = null;
  41152. }
  41153. return true;
  41154. };
  41155. return Lines2DRenderCache;
  41156. })(BABYLON.ModelRenderCache);
  41157. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  41158. var Lines2DInstanceData = (function (_super) {
  41159. __extends(Lines2DInstanceData, _super);
  41160. function Lines2DInstanceData(partId) {
  41161. _super.call(this, partId, 1);
  41162. }
  41163. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  41164. get: function () {
  41165. return null;
  41166. },
  41167. enumerable: true,
  41168. configurable: true
  41169. });
  41170. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  41171. get: function () {
  41172. return null;
  41173. },
  41174. enumerable: true,
  41175. configurable: true
  41176. });
  41177. __decorate([
  41178. BABYLON.instanceData()
  41179. ], Lines2DInstanceData.prototype, "boundingMin", null);
  41180. __decorate([
  41181. BABYLON.instanceData()
  41182. ], Lines2DInstanceData.prototype, "boundingMax", null);
  41183. return Lines2DInstanceData;
  41184. })(BABYLON.Shape2DInstanceData);
  41185. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  41186. var Lines2D = (function (_super) {
  41187. __extends(Lines2D, _super);
  41188. function Lines2D() {
  41189. _super.apply(this, arguments);
  41190. }
  41191. Object.defineProperty(Lines2D, "NoCap", {
  41192. get: function () { return Lines2D._noCap; },
  41193. enumerable: true,
  41194. configurable: true
  41195. });
  41196. Object.defineProperty(Lines2D, "RoundCap", {
  41197. get: function () { return Lines2D._roundCap; },
  41198. enumerable: true,
  41199. configurable: true
  41200. });
  41201. Object.defineProperty(Lines2D, "TriangleCap", {
  41202. get: function () { return Lines2D._triangleCap; },
  41203. enumerable: true,
  41204. configurable: true
  41205. });
  41206. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  41207. get: function () { return Lines2D._squareAnchorCap; },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  41212. get: function () { return Lines2D._roundAnchorCap; },
  41213. enumerable: true,
  41214. configurable: true
  41215. });
  41216. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  41217. get: function () { return Lines2D._diamondAnchorCap; },
  41218. enumerable: true,
  41219. configurable: true
  41220. });
  41221. Object.defineProperty(Lines2D, "ArrowCap", {
  41222. get: function () { return Lines2D._arrowCap; },
  41223. enumerable: true,
  41224. configurable: true
  41225. });
  41226. Object.defineProperty(Lines2D.prototype, "actualSize", {
  41227. get: function () {
  41228. return this.size;
  41229. },
  41230. enumerable: true,
  41231. configurable: true
  41232. });
  41233. Object.defineProperty(Lines2D.prototype, "points", {
  41234. get: function () {
  41235. return this._points;
  41236. },
  41237. set: function (value) {
  41238. this._points = value;
  41239. this._levelBoundingInfoDirty = true;
  41240. },
  41241. enumerable: true,
  41242. configurable: true
  41243. });
  41244. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  41245. get: function () {
  41246. return this._fillThickness;
  41247. },
  41248. set: function (value) {
  41249. this._fillThickness = value;
  41250. },
  41251. enumerable: true,
  41252. configurable: true
  41253. });
  41254. Object.defineProperty(Lines2D.prototype, "closed", {
  41255. get: function () {
  41256. return this._closed;
  41257. },
  41258. set: function (value) {
  41259. this._closed = value;
  41260. },
  41261. enumerable: true,
  41262. configurable: true
  41263. });
  41264. Object.defineProperty(Lines2D.prototype, "startCap", {
  41265. get: function () {
  41266. return this._startCap;
  41267. },
  41268. set: function (value) {
  41269. this._startCap = value;
  41270. },
  41271. enumerable: true,
  41272. configurable: true
  41273. });
  41274. Object.defineProperty(Lines2D.prototype, "endCap", {
  41275. get: function () {
  41276. return this._endCap;
  41277. },
  41278. set: function (value) {
  41279. this._endCap = value;
  41280. },
  41281. enumerable: true,
  41282. configurable: true
  41283. });
  41284. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  41285. var _this = this;
  41286. var pl = this.points.length;
  41287. var l = this.closed ? pl + 1 : pl;
  41288. var p = intersectInfo._localPickPosition;
  41289. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  41290. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  41291. for (var i = 1; i < l; i++) {
  41292. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  41293. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  41294. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  41295. return true;
  41296. }
  41297. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  41298. return true;
  41299. }
  41300. Lines2D._prevA.x = Lines2D._curA.x;
  41301. Lines2D._prevA.y = Lines2D._curA.y;
  41302. Lines2D._prevB.x = Lines2D._curB.x;
  41303. Lines2D._prevB.y = Lines2D._curB.y;
  41304. }
  41305. var capIntersect = function (tri, points) {
  41306. var l = tri.length;
  41307. for (var i = 0; i < l; i += 3) {
  41308. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  41309. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  41310. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  41311. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  41312. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  41313. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  41314. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  41315. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  41316. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  41317. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  41318. return true;
  41319. }
  41320. }
  41321. return false;
  41322. };
  41323. if (this._startCapTriIndices) {
  41324. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  41325. return true;
  41326. }
  41327. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  41328. return true;
  41329. }
  41330. }
  41331. return false;
  41332. };
  41333. Object.defineProperty(Lines2D.prototype, "size", {
  41334. get: function () {
  41335. return this._size;
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  41341. get: function () {
  41342. return this._boundingMin;
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  41348. get: function () {
  41349. return this._boundingMax;
  41350. },
  41351. enumerable: true,
  41352. configurable: true
  41353. });
  41354. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  41355. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  41356. // Remove the BORDER category, we don't use it in the VertexShader
  41357. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  41358. if (i !== -1) {
  41359. res.splice(i, 1);
  41360. }
  41361. return res;
  41362. };
  41363. Lines2D.prototype.updateLevelBoundingInfo = function () {
  41364. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo, this.origin);
  41365. };
  41366. Lines2D.prototype.setupLines2D = function (owner, parent, id, position, origin, points, fillThickness, startCap, endCap, fill, border, borderThickness, closed, isVisible, marginTop, marginLeft, marginRight, marginBottom, vAlignment, hAlignment) {
  41367. this.setupShape2D(owner, parent, id, position, origin, isVisible, fill, border, borderThickness, marginTop, marginLeft, marginRight, marginBottom, hAlignment, vAlignment);
  41368. this.fillThickness = fillThickness;
  41369. this.startCap = startCap;
  41370. this.endCap = endCap;
  41371. this.points = points;
  41372. this.closed = closed;
  41373. this._size = BABYLON.Size.Zero();
  41374. this._boundingMin = BABYLON.Vector2.Zero();
  41375. this._boundingMax = BABYLON.Vector2.Zero();
  41376. };
  41377. /**
  41378. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  41379. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  41380. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  41381. * options:
  41382. * - id a text identifier, for information purpose
  41383. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41384. * - origin: define the normalized origin point location, default [0.5;0.5]
  41385. * - 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.
  41386. * - 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.
  41387. * - 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.
  41388. * - 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.
  41389. * - 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.
  41390. * - 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.
  41391. * - borderThickness: the thickness of the drawn border, default is 1.
  41392. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  41393. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  41394. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  41395. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  41396. */
  41397. Lines2D.Create = function (parent, points, options) {
  41398. BABYLON.Prim2DBase.CheckParent(parent);
  41399. var lines = new Lines2D();
  41400. if (!options) {
  41401. lines.setupLines2D(parent.owner, parent, null, BABYLON.Vector2.Zero(), null, points, 1, 0, 0, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"), null, 1, false, true, null, null, null, null, null, null);
  41402. }
  41403. else {
  41404. var fill;
  41405. if (options.fill === undefined) {
  41406. fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  41407. }
  41408. else {
  41409. fill = options.fill;
  41410. }
  41411. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  41412. lines.setupLines2D(parent.owner, parent, options.id || null, pos, options.origin || null, points, (options.fillThickness == null) ? 1 : options.fillThickness, (options.startCap == null) ? 0 : options.startCap, (options.endCap == null) ? 0 : options.endCap, fill, options.border || null, (options.borderThickness == null) ? 1 : options.borderThickness, (options.closed == null) ? false : options.closed, (options.isVisible == null) ? true : options.isVisible, options.marginTop || null, options.marginLeft || null, options.marginRight || null, options.marginBottom || null, options.vAlignment || null, options.hAlignment || null);
  41413. }
  41414. return lines;
  41415. };
  41416. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  41417. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  41418. return renderCache;
  41419. };
  41420. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41421. var _this = this;
  41422. var renderCache = modelRenderCache;
  41423. var engine = this.owner.engine;
  41424. // Init min/max because their being computed here
  41425. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  41426. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  41427. var perp = function (v, res) {
  41428. res.x = v.y;
  41429. res.y = -v.x;
  41430. };
  41431. var direction = function (a, b, res) {
  41432. a.subtractToRef(b, res);
  41433. res.normalize();
  41434. };
  41435. var tps = BABYLON.Vector2.Zero();
  41436. var computeMiter = function (tangent, miter, a, b) {
  41437. a.addToRef(b, tangent);
  41438. tangent.normalize();
  41439. miter.x = -tangent.y;
  41440. miter.y = tangent.x;
  41441. tps.x = -a.y;
  41442. tps.y = a.x;
  41443. return 1 / BABYLON.Vector2.Dot(miter, tps);
  41444. };
  41445. var intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  41446. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  41447. if (d === 0)
  41448. return false;
  41449. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  41450. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  41451. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  41452. return false;
  41453. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  41454. return false;
  41455. return true;
  41456. };
  41457. var startDir = BABYLON.Vector2.Zero();
  41458. var endDir = BABYLON.Vector2.Zero();
  41459. var updateMinMax = function (array, offset) {
  41460. if (offset >= array.length) {
  41461. return;
  41462. }
  41463. _this._boundingMin.x = Math.min(_this._boundingMin.x, array[offset]);
  41464. _this._boundingMax.x = Math.max(_this._boundingMax.x, array[offset]);
  41465. _this._boundingMin.y = Math.min(_this._boundingMin.y, array[offset + 1]);
  41466. _this._boundingMax.y = Math.max(_this._boundingMax.y, array[offset + 1]);
  41467. };
  41468. var store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  41469. var borderMode = borderThickness != null && !isNaN(borderThickness);
  41470. var off = index * (borderMode ? 8 : 4);
  41471. // 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)
  41472. if (off >= array.length) {
  41473. return;
  41474. }
  41475. // Store start/end normal, we need it for the cap construction
  41476. if (index === 0) {
  41477. perp(n, startDir);
  41478. }
  41479. else if (index === max - 1) {
  41480. perp(n, endDir);
  41481. endDir.x *= -1;
  41482. endDir.y *= -1;
  41483. }
  41484. var swap = false;
  41485. array[off + 0] = p.x + n.x * halfThickness;
  41486. array[off + 1] = p.y + n.y * halfThickness;
  41487. array[off + 2] = p.x + n.x * -halfThickness;
  41488. array[off + 3] = p.y + n.y * -halfThickness;
  41489. updateMinMax(array, off);
  41490. updateMinMax(array, off + 2);
  41491. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  41492. // 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
  41493. if (detectFlip !== undefined) {
  41494. // Flip if intersect
  41495. var flipOff = detectFlip * (borderMode ? 8 : 4);
  41496. 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])) {
  41497. swap = true;
  41498. var tps_1 = array[off + 0];
  41499. array[off + 0] = array[off + 2];
  41500. array[off + 2] = tps_1;
  41501. tps_1 = array[off + 1];
  41502. array[off + 1] = array[off + 3];
  41503. array[off + 3] = tps_1;
  41504. }
  41505. }
  41506. if (borderMode) {
  41507. var t = halfThickness + borderThickness;
  41508. array[off + 4] = p.x + n.x * (swap ? -t : t);
  41509. array[off + 5] = p.y + n.y * (swap ? -t : t);
  41510. array[off + 6] = p.x + n.x * (swap ? t : -t);
  41511. array[off + 7] = p.y + n.y * (swap ? t : -t);
  41512. updateMinMax(array, off + 4);
  41513. updateMinMax(array, off + 6);
  41514. }
  41515. if (contour) {
  41516. off += borderMode ? 4 : 0;
  41517. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  41518. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  41519. }
  41520. };
  41521. var sd = Lines2D._roundCapSubDiv;
  41522. var getCapSize = function (type, border) {
  41523. if (border === void 0) { border = false; }
  41524. // If no array given, we call this to get the size
  41525. var vbsize = 0, ibsize = 0;
  41526. switch (type) {
  41527. case Lines2D.NoCap:
  41528. // If the line is not close and we're computing border, we add the size to generate the edge border
  41529. if (!_this.closed && border) {
  41530. vbsize = 4;
  41531. ibsize = 6;
  41532. }
  41533. else {
  41534. vbsize = ibsize = 0;
  41535. }
  41536. break;
  41537. case Lines2D.RoundCap:
  41538. if (border) {
  41539. vbsize = sd;
  41540. ibsize = (sd - 2) * 3;
  41541. }
  41542. else {
  41543. vbsize = (sd / 2) + 1;
  41544. ibsize = (sd / 2) * 3;
  41545. }
  41546. break;
  41547. case Lines2D.ArrowCap:
  41548. if (border) {
  41549. vbsize = 12;
  41550. ibsize = 24;
  41551. }
  41552. else {
  41553. vbsize = 3;
  41554. ibsize = 3;
  41555. }
  41556. break;
  41557. case Lines2D.TriangleCap:
  41558. if (border) {
  41559. vbsize = 6;
  41560. ibsize = 12;
  41561. }
  41562. else {
  41563. vbsize = 3;
  41564. ibsize = 3;
  41565. }
  41566. break;
  41567. case Lines2D.DiamondAnchorCap:
  41568. if (border) {
  41569. vbsize = 10;
  41570. ibsize = 24;
  41571. }
  41572. else {
  41573. vbsize = 5;
  41574. ibsize = 9;
  41575. }
  41576. break;
  41577. case Lines2D.SquareAnchorCap:
  41578. if (border) {
  41579. vbsize = 12;
  41580. ibsize = 30;
  41581. }
  41582. else {
  41583. vbsize = 4;
  41584. ibsize = 6;
  41585. }
  41586. break;
  41587. case Lines2D.RoundAnchorCap:
  41588. if (border) {
  41589. vbsize = sd * 2;
  41590. ibsize = (sd - 1) * 6;
  41591. }
  41592. else {
  41593. vbsize = sd + 1;
  41594. ibsize = (sd + 1) * 3;
  41595. }
  41596. break;
  41597. }
  41598. return { vbsize: vbsize * 2, ibsize: ibsize };
  41599. };
  41600. var v = BABYLON.Vector2.Zero();
  41601. var storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  41602. var c = Math.cos(rotation);
  41603. var s = Math.sin(rotation);
  41604. v.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  41605. v.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  41606. var offset = baseOffset + (index * 2);
  41607. vb[offset + 0] = v.x;
  41608. vb[offset + 1] = v.y;
  41609. if (contour) {
  41610. contour.push(v.x);
  41611. contour.push(v.y);
  41612. }
  41613. updateMinMax(vb, offset);
  41614. return (baseOffset + index * 2) / 2;
  41615. };
  41616. var storeIndex = function (ib, baseOffset, index, vertexIndex) {
  41617. ib[baseOffset + index] = vertexIndex;
  41618. };
  41619. var buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  41620. // 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
  41621. var dir = new BABYLON.Vector2(1, 0);
  41622. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  41623. var ht = thickness / 2;
  41624. var t = thickness;
  41625. var borderMode = borderThickness != null;
  41626. var bt = borderThickness;
  41627. switch (type) {
  41628. case Lines2D.NoCap:
  41629. if (borderMode && !_this.closed) {
  41630. var vi = 0;
  41631. var ii = 0;
  41632. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  41633. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  41634. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  41635. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  41636. storeIndex(ib, ibi, ii++, v1);
  41637. storeIndex(ib, ibi, ii++, v2);
  41638. storeIndex(ib, ibi, ii++, v3);
  41639. storeIndex(ib, ibi, ii++, v1);
  41640. storeIndex(ib, ibi, ii++, v3);
  41641. storeIndex(ib, ibi, ii++, v4);
  41642. }
  41643. break;
  41644. case Lines2D.ArrowCap:
  41645. ht *= 2;
  41646. case Lines2D.TriangleCap:
  41647. {
  41648. if (borderMode) {
  41649. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  41650. var v1 = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  41651. var v2 = storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  41652. var v3 = storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  41653. var v4 = storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  41654. var v5 = storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  41655. var v6 = storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  41656. var ii = 0;
  41657. storeIndex(ib, ibi, ii++, v1);
  41658. storeIndex(ib, ibi, ii++, v4);
  41659. storeIndex(ib, ibi, ii++, v5);
  41660. storeIndex(ib, ibi, ii++, v1);
  41661. storeIndex(ib, ibi, ii++, v5);
  41662. storeIndex(ib, ibi, ii++, v2);
  41663. storeIndex(ib, ibi, ii++, v6);
  41664. storeIndex(ib, ibi, ii++, v3);
  41665. storeIndex(ib, ibi, ii++, v2);
  41666. storeIndex(ib, ibi, ii++, v6);
  41667. storeIndex(ib, ibi, ii++, v2);
  41668. storeIndex(ib, ibi, ii++, v5);
  41669. if (type === Lines2D.ArrowCap) {
  41670. var rht = thickness / 2;
  41671. var v10 = storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  41672. var v12 = storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  41673. var v11 = storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  41674. var v7 = storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  41675. var v8 = storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  41676. var v9 = storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  41677. storeIndex(ib, ibi, ii++, v7);
  41678. storeIndex(ib, ibi, ii++, v8);
  41679. storeIndex(ib, ibi, ii++, v9);
  41680. storeIndex(ib, ibi, ii++, v7);
  41681. storeIndex(ib, ibi, ii++, v9);
  41682. storeIndex(ib, ibi, ii++, v4);
  41683. storeIndex(ib, ibi, ii++, v10);
  41684. storeIndex(ib, ibi, ii++, v12);
  41685. storeIndex(ib, ibi, ii++, v11);
  41686. storeIndex(ib, ibi, ii++, v10);
  41687. storeIndex(ib, ibi, ii++, v6);
  41688. storeIndex(ib, ibi, ii++, v12);
  41689. }
  41690. }
  41691. else {
  41692. var v1 = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  41693. var v2 = storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  41694. var v3 = storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  41695. storeIndex(ib, ibi, 0, v1);
  41696. storeIndex(ib, ibi, 1, v2);
  41697. storeIndex(ib, ibi, 2, v3);
  41698. }
  41699. break;
  41700. }
  41701. case Lines2D.RoundCap:
  41702. {
  41703. if (borderMode) {
  41704. var curA = -Math.PI / 2;
  41705. var incA = Math.PI / (sd / 2 - 1);
  41706. var ii = 0;
  41707. for (var i = 0; i < (sd / 2); i++) {
  41708. var v1 = storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  41709. var v2 = storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  41710. if (i > 0) {
  41711. storeIndex(ib, ibi, ii++, v1 - 2);
  41712. storeIndex(ib, ibi, ii++, v2 - 2);
  41713. storeIndex(ib, ibi, ii++, v2);
  41714. storeIndex(ib, ibi, ii++, v1 - 2);
  41715. storeIndex(ib, ibi, ii++, v2);
  41716. storeIndex(ib, ibi, ii++, v1);
  41717. }
  41718. curA += incA;
  41719. }
  41720. }
  41721. else {
  41722. var c = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  41723. var curA = -Math.PI / 2;
  41724. var incA = Math.PI / (sd / 2 - 1);
  41725. storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  41726. curA += incA;
  41727. for (var i = 1; i < (sd / 2); i++) {
  41728. var v2 = storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  41729. storeIndex(ib, ibi, i * 3 + 0, c);
  41730. storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  41731. storeIndex(ib, ibi, i * 3 + 2, v2);
  41732. curA += incA;
  41733. }
  41734. }
  41735. break;
  41736. }
  41737. case Lines2D.SquareAnchorCap:
  41738. {
  41739. var vi = 0;
  41740. var c = borderMode ? null : contour;
  41741. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  41742. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  41743. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  41744. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  41745. if (borderMode) {
  41746. var v5 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  41747. var v6 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  41748. var v7 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  41749. var v8 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  41750. var v9 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  41751. var v10 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  41752. var v11 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  41753. var v12 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  41754. var ii = 0;
  41755. storeIndex(ib, ibi, ii++, v6);
  41756. storeIndex(ib, ibi, ii++, v1);
  41757. storeIndex(ib, ibi, ii++, v5);
  41758. storeIndex(ib, ibi, ii++, v6);
  41759. storeIndex(ib, ibi, ii++, v7);
  41760. storeIndex(ib, ibi, ii++, v1);
  41761. storeIndex(ib, ibi, ii++, v1);
  41762. storeIndex(ib, ibi, ii++, v7);
  41763. storeIndex(ib, ibi, ii++, v8);
  41764. storeIndex(ib, ibi, ii++, v1);
  41765. storeIndex(ib, ibi, ii++, v8);
  41766. storeIndex(ib, ibi, ii++, v2);
  41767. storeIndex(ib, ibi, ii++, v2);
  41768. storeIndex(ib, ibi, ii++, v8);
  41769. storeIndex(ib, ibi, ii++, v9);
  41770. storeIndex(ib, ibi, ii++, v2);
  41771. storeIndex(ib, ibi, ii++, v9);
  41772. storeIndex(ib, ibi, ii++, v3);
  41773. storeIndex(ib, ibi, ii++, v3);
  41774. storeIndex(ib, ibi, ii++, v9);
  41775. storeIndex(ib, ibi, ii++, v10);
  41776. storeIndex(ib, ibi, ii++, v3);
  41777. storeIndex(ib, ibi, ii++, v10);
  41778. storeIndex(ib, ibi, ii++, v4);
  41779. storeIndex(ib, ibi, ii++, v10);
  41780. storeIndex(ib, ibi, ii++, v11);
  41781. storeIndex(ib, ibi, ii++, v4);
  41782. storeIndex(ib, ibi, ii++, v11);
  41783. storeIndex(ib, ibi, ii++, v12);
  41784. storeIndex(ib, ibi, ii++, v4);
  41785. }
  41786. else {
  41787. storeIndex(ib, ibi, 0, v1);
  41788. storeIndex(ib, ibi, 1, v2);
  41789. storeIndex(ib, ibi, 2, v3);
  41790. storeIndex(ib, ibi, 3, v1);
  41791. storeIndex(ib, ibi, 4, v3);
  41792. storeIndex(ib, ibi, 5, v4);
  41793. }
  41794. break;
  41795. }
  41796. case Lines2D.RoundAnchorCap:
  41797. {
  41798. var cpos = Math.sqrt(t * t - ht * ht);
  41799. var center = new BABYLON.Vector2(cpos, 0);
  41800. var curA = BABYLON.Tools.ToRadians(-150);
  41801. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  41802. if (borderMode) {
  41803. var ii = 0;
  41804. for (var i = 0; i < sd; i++) {
  41805. var v1 = storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  41806. var v2 = storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  41807. if (i > 0) {
  41808. storeIndex(ib, ibi, ii++, v1 - 2);
  41809. storeIndex(ib, ibi, ii++, v2 - 2);
  41810. storeIndex(ib, ibi, ii++, v2);
  41811. storeIndex(ib, ibi, ii++, v1 - 2);
  41812. storeIndex(ib, ibi, ii++, v2);
  41813. storeIndex(ib, ibi, ii++, v1);
  41814. }
  41815. curA += incA;
  41816. }
  41817. }
  41818. else {
  41819. var c = storeVertex(vb, vbi, 0, pos, angle, center, null);
  41820. storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null); // contour maybe TODO
  41821. curA += incA;
  41822. for (var i = 1; i < sd; i++) {
  41823. var v2 = storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  41824. storeIndex(ib, ibi, i * 3 + 0, c);
  41825. storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  41826. storeIndex(ib, ibi, i * 3 + 2, v2);
  41827. curA += incA;
  41828. }
  41829. storeIndex(ib, ibi, sd * 3 + 0, c);
  41830. storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  41831. storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  41832. }
  41833. break;
  41834. }
  41835. case Lines2D.DiamondAnchorCap:
  41836. {
  41837. var vi = 0;
  41838. var c = borderMode ? null : contour;
  41839. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  41840. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  41841. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  41842. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  41843. var v5 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  41844. if (borderMode) {
  41845. var f = Math.sqrt(bt * bt * 2);
  41846. var v6 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  41847. var v7 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  41848. var v8 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  41849. var v9 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  41850. var v10 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  41851. var ii = 0;
  41852. storeIndex(ib, ibi, ii++, v6);
  41853. storeIndex(ib, ibi, ii++, v7);
  41854. storeIndex(ib, ibi, ii++, v1);
  41855. storeIndex(ib, ibi, ii++, v1);
  41856. storeIndex(ib, ibi, ii++, v7);
  41857. storeIndex(ib, ibi, ii++, v2);
  41858. storeIndex(ib, ibi, ii++, v2);
  41859. storeIndex(ib, ibi, ii++, v7);
  41860. storeIndex(ib, ibi, ii++, v8);
  41861. storeIndex(ib, ibi, ii++, v2);
  41862. storeIndex(ib, ibi, ii++, v8);
  41863. storeIndex(ib, ibi, ii++, v3);
  41864. storeIndex(ib, ibi, ii++, v3);
  41865. storeIndex(ib, ibi, ii++, v8);
  41866. storeIndex(ib, ibi, ii++, v9);
  41867. storeIndex(ib, ibi, ii++, v3);
  41868. storeIndex(ib, ibi, ii++, v9);
  41869. storeIndex(ib, ibi, ii++, v4);
  41870. storeIndex(ib, ibi, ii++, v4);
  41871. storeIndex(ib, ibi, ii++, v9);
  41872. storeIndex(ib, ibi, ii++, v10);
  41873. storeIndex(ib, ibi, ii++, v4);
  41874. storeIndex(ib, ibi, ii++, v10);
  41875. storeIndex(ib, ibi, ii++, v5);
  41876. }
  41877. else {
  41878. storeIndex(ib, ibi, 0, v1);
  41879. storeIndex(ib, ibi, 1, v2);
  41880. storeIndex(ib, ibi, 2, v3);
  41881. storeIndex(ib, ibi, 3, v1);
  41882. storeIndex(ib, ibi, 4, v3);
  41883. storeIndex(ib, ibi, 5, v5);
  41884. storeIndex(ib, ibi, 6, v5);
  41885. storeIndex(ib, ibi, 7, v3);
  41886. storeIndex(ib, ibi, 8, v4);
  41887. }
  41888. break;
  41889. }
  41890. }
  41891. return null;
  41892. };
  41893. var buildLine = function (vb, contour, ht, bt) {
  41894. var lineA = BABYLON.Vector2.Zero();
  41895. var lineB = BABYLON.Vector2.Zero();
  41896. var tangent = BABYLON.Vector2.Zero();
  41897. var miter = BABYLON.Vector2.Zero();
  41898. var curNormal = null;
  41899. if (_this.closed) {
  41900. _this.points.push(_this.points[0]);
  41901. }
  41902. var total = _this.points.length;
  41903. for (var i = 1; i < total; i++) {
  41904. var last = _this.points[i - 1];
  41905. var cur = _this.points[i];
  41906. var next = (i < (_this.points.length - 1)) ? _this.points[i + 1] : null;
  41907. direction(cur, last, lineA);
  41908. if (!curNormal) {
  41909. curNormal = BABYLON.Vector2.Zero();
  41910. perp(lineA, curNormal);
  41911. }
  41912. if (i === 1) {
  41913. store(vb, contour, 0, total, _this.points[0], curNormal, ht, bt);
  41914. }
  41915. if (!next) {
  41916. perp(lineA, curNormal);
  41917. store(vb, contour, i, total, _this.points[i], curNormal, ht, bt, i - 1);
  41918. }
  41919. else {
  41920. direction(next, cur, lineB);
  41921. var miterLen = computeMiter(tangent, miter, lineA, lineB);
  41922. store(vb, contour, i, total, _this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  41923. }
  41924. }
  41925. if (_this.points.length > 2 && _this.closed) {
  41926. var last2 = _this.points[total - 2];
  41927. var cur2 = _this.points[0];
  41928. var next2 = _this.points[1];
  41929. direction(cur2, last2, lineA);
  41930. direction(next2, cur2, lineB);
  41931. perp(lineA, curNormal);
  41932. var miterLen2 = computeMiter(tangent, miter, lineA, lineB);
  41933. store(vb, null, 0, total, _this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  41934. // Patch contour
  41935. if (contour) {
  41936. var off = (bt == null) ? 0 : 4;
  41937. contour[0].x = vb[off + 0];
  41938. contour[0].y = vb[off + 1];
  41939. contour[1].x = vb[off + 2];
  41940. contour[1].y = vb[off + 3];
  41941. }
  41942. }
  41943. // Remove the point we added at the beginning
  41944. if (_this.closed) {
  41945. _this.points.splice(total - 1);
  41946. }
  41947. };
  41948. var contour = new Array();
  41949. var startCapContour = new Array();
  41950. var endCapContour = new Array();
  41951. // Need to create WebGL resources for fill part?
  41952. if (this.fill) {
  41953. var startCapInfo = getCapSize(this.startCap);
  41954. var endCapInfo = getCapSize(this.endCap);
  41955. var count = this.points.length;
  41956. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  41957. var vb = new Float32Array(vbSize);
  41958. var ht = this.fillThickness / 2;
  41959. var total = this.points.length;
  41960. buildLine(vb, this.border ? null : contour, ht);
  41961. var max = total * 2;
  41962. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  41963. var ib = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  41964. for (var i = 0; i < triCount; i += 2) {
  41965. ib[i * 3 + 0] = i + 0;
  41966. ib[i * 3 + 1] = i + 1;
  41967. ib[i * 3 + 2] = (i + 2) % max;
  41968. ib[i * 3 + 3] = i + 1;
  41969. ib[i * 3 + 4] = (i + 3) % max;
  41970. ib[i * 3 + 5] = (i + 2) % max;
  41971. }
  41972. buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, startDir, this.border ? null : startCapContour);
  41973. buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, endDir, this.border ? null : startCapContour);
  41974. renderCache.fillVB = engine.createVertexBuffer(vb);
  41975. renderCache.fillIB = engine.createIndexBuffer(ib);
  41976. renderCache.fillIndicesCount = ib.length;
  41977. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  41978. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  41979. if (ei) {
  41980. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41981. }
  41982. // Get the non instanced version
  41983. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  41984. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  41985. }
  41986. // Need to create WebGL resources for border part?
  41987. if (this.border) {
  41988. var startCapInfo = getCapSize(this.startCap, true);
  41989. var endCapInfo = getCapSize(this.endCap, true);
  41990. var count = this.points.length;
  41991. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  41992. var vb = new Float32Array(vbSize);
  41993. var ht = this.fillThickness / 2;
  41994. var bt = this.borderThickness;
  41995. var total = this.points.length;
  41996. buildLine(vb, contour, ht, bt);
  41997. var max = total * 2 * 2;
  41998. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  41999. var ib = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  42000. for (var i = 0; i < triCount; i += 4) {
  42001. ib[i * 3 + 0] = i + 0;
  42002. ib[i * 3 + 1] = i + 2;
  42003. ib[i * 3 + 2] = (i + 6) % max;
  42004. ib[i * 3 + 3] = i + 0;
  42005. ib[i * 3 + 4] = (i + 6) % max;
  42006. ib[i * 3 + 5] = (i + 4) % max;
  42007. ib[i * 3 + 6] = i + 3;
  42008. ib[i * 3 + 7] = i + 1;
  42009. ib[i * 3 + 8] = (i + 5) % max;
  42010. ib[i * 3 + 9] = i + 3;
  42011. ib[i * 3 + 10] = (i + 5) % max;
  42012. ib[i * 3 + 11] = (i + 7) % max;
  42013. }
  42014. buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, startDir, startCapContour);
  42015. buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, endDir, endCapContour);
  42016. renderCache.borderVB = engine.createVertexBuffer(vb);
  42017. renderCache.borderIB = engine.createIndexBuffer(ib);
  42018. renderCache.borderIndicesCount = ib.length;
  42019. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  42020. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  42021. if (ei) {
  42022. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  42023. }
  42024. // Get the non instanced version
  42025. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  42026. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  42027. }
  42028. this._contour = contour;
  42029. if (startCapContour.length > 0) {
  42030. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  42031. this._startCapTriIndices = startCapTri;
  42032. this._startCapContour = startCapContour;
  42033. }
  42034. if (endCapContour.length > 0) {
  42035. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  42036. this._endCapContour = endCapContour;
  42037. this._endCapTriIndices = endCapTri;
  42038. }
  42039. var bs = this._boundingMax.subtract(this._boundingMin);
  42040. this._size.width = bs.x;
  42041. this._size.height = bs.y;
  42042. return renderCache;
  42043. };
  42044. Lines2D.prototype.createInstanceDataParts = function () {
  42045. var res = new Array();
  42046. if (this.border) {
  42047. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42048. }
  42049. if (this.fill) {
  42050. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42051. }
  42052. return res;
  42053. };
  42054. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  42055. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42056. return false;
  42057. }
  42058. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42059. var d = part;
  42060. d.boundingMin = this.boundingMin;
  42061. d.boundingMax = this.boundingMax;
  42062. }
  42063. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  42064. var d = part;
  42065. d.boundingMin = this.boundingMin;
  42066. d.boundingMax = this.boundingMax;
  42067. }
  42068. return true;
  42069. };
  42070. Lines2D._prevA = BABYLON.Vector2.Zero();
  42071. Lines2D._prevB = BABYLON.Vector2.Zero();
  42072. Lines2D._curA = BABYLON.Vector2.Zero();
  42073. Lines2D._curB = BABYLON.Vector2.Zero();
  42074. Lines2D._noCap = 0;
  42075. Lines2D._roundCap = 1;
  42076. Lines2D._triangleCap = 2;
  42077. Lines2D._squareAnchorCap = 3;
  42078. Lines2D._roundAnchorCap = 4;
  42079. Lines2D._diamondAnchorCap = 5;
  42080. Lines2D._arrowCap = 6;
  42081. Lines2D._roundCapSubDiv = 36;
  42082. __decorate([
  42083. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  42084. ], Lines2D.prototype, "points", null);
  42085. __decorate([
  42086. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  42087. ], Lines2D.prototype, "fillThickness", null);
  42088. __decorate([
  42089. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  42090. ], Lines2D.prototype, "closed", null);
  42091. __decorate([
  42092. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  42093. ], Lines2D.prototype, "startCap", null);
  42094. __decorate([
  42095. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  42096. ], Lines2D.prototype, "endCap", null);
  42097. Lines2D = __decorate([
  42098. BABYLON.className("Lines2D")
  42099. ], Lines2D);
  42100. return Lines2D;
  42101. })(BABYLON.Shape2D);
  42102. BABYLON.Lines2D = Lines2D;
  42103. })(BABYLON || (BABYLON = {}));
  42104. var BABYLON;
  42105. (function (BABYLON) {
  42106. var Canvas2DEngineBoundData = (function () {
  42107. function Canvas2DEngineBoundData() {
  42108. this._modelCache = new BABYLON.StringDictionary();
  42109. }
  42110. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  42111. return this._modelCache.getOrAddWithFactory(key, factory);
  42112. };
  42113. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  42114. if (!modelRenderCache.isDisposed) {
  42115. return false;
  42116. }
  42117. this._modelCache.remove(modelRenderCache.modelKey);
  42118. return true;
  42119. };
  42120. return Canvas2DEngineBoundData;
  42121. })();
  42122. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  42123. var Canvas2D = (function (_super) {
  42124. __extends(Canvas2D, _super);
  42125. function Canvas2D() {
  42126. var _this = this;
  42127. _super.apply(this, arguments);
  42128. /**
  42129. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  42130. * Beware that you have to take under consideration the origin and the renderScaleFactor in your calculations! Good luck!
  42131. */
  42132. this.worldSpaceToNodeLocal = function (worldPos) {
  42133. var node = _this._worldSpaceNode;
  42134. if (!node) {
  42135. return;
  42136. }
  42137. var mtx = node.getWorldMatrix().clone();
  42138. mtx.invert();
  42139. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  42140. var rsf = _this._renderScaleFactor;
  42141. var res = new BABYLON.Vector2(v.x * rsf, v.y * rsf);
  42142. var size = _this.actualSize;
  42143. var o = _this.origin;
  42144. res.x += size.width * o.x;
  42145. res.y += size.width * o.y;
  42146. return res;
  42147. };
  42148. this._notifDebugMode = false;
  42149. this._mapCounter = 0;
  42150. }
  42151. /**
  42152. * 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.
  42153. * 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.
  42154. * All caching strategies will be available.
  42155. * 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]
  42156. * @param scene the Scene that owns the Canvas
  42157. * Options:
  42158. * - id: a text identifier, for information purpose only
  42159. * - pos: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  42160. * - size: the Size of the canvas. Alternatively the width and height properties can be set. 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
  42161. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  42162. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  42163. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  42164. * - marginTop/Left/Right/Bottom: define the margin for the corresponding edge, if all of them are null, margin is not used in layout computing. Default Value is null for each.
  42165. * - hAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  42166. * - vAlighment: define horizontal alignment of the Canvas, alignment is optional, default value null: no alignment.
  42167. */
  42168. Canvas2D.CreateScreenSpace = function (scene, options) {
  42169. var c = new Canvas2D();
  42170. if (!options) {
  42171. c.setupCanvas(scene, null, null, 1, true, Canvas2D.CACHESTRATEGY_DONTCACHE, true, BABYLON.Vector2.Zero(), true, null, null, null, null, null, null);
  42172. c.position = BABYLON.Vector2.Zero();
  42173. }
  42174. else {
  42175. var pos = options.position || new BABYLON.Vector2(options.x || 0, options.y || 0);
  42176. var size = (!options.size && !options.width && !options.height) ? null : (options.size || (new BABYLON.Size(options.width || 0, options.height || 0)));
  42177. c.setupCanvas(scene, options.id || null, size, 1, true, options.cachingStrategy || Canvas2D.CACHESTRATEGY_DONTCACHE, options.enableInteraction || true, options.origin || BABYLON.Vector2.Zero(), options.isVisible || true, options.marginTop, options.marginLeft, options.marginRight, options.marginBottom, options.hAlignment || BABYLON.Prim2DBase.HAlignLeft, options.vAlignment || BABYLON.Prim2DBase.VAlignTop);
  42178. c.position = pos;
  42179. }
  42180. return c;
  42181. };
  42182. /**
  42183. * 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.
  42184. * 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.
  42185. * @param scene the Scene that owns the Canvas
  42186. * @param size the dimension of the Canvas in World Space
  42187. * Options:
  42188. * - id: a text identifier, for information purpose only, default is null.
  42189. * - position the position of the Canvas in World Space, default is [0,0,0]
  42190. * - rotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  42191. * - 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.
  42192. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  42193. * 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.
  42194. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  42195. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  42196. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  42197. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  42198. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  42199. */
  42200. Canvas2D.CreateWorldSpace = function (scene, size, options) {
  42201. var cs = options && options.cachingStrategy || Canvas2D.CACHESTRATEGY_CANVAS;
  42202. if (cs !== Canvas2D.CACHESTRATEGY_CANVAS) {
  42203. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  42204. }
  42205. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  42206. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  42207. //}
  42208. var enableInteraction = options ? options.enableInteraction : true;
  42209. var createWorldSpaceNode = !options || (options.customWorldSpaceNode == null);
  42210. var isVisible = options ? options.isVisible || true : true;
  42211. var id = options ? options.id || null : null;
  42212. var rsf = options ? options.renderScaleFactor || 1 : 1;
  42213. var c = new Canvas2D();
  42214. c.setupCanvas(scene, id, new BABYLON.Size(size.width, size.height), rsf, false, cs, enableInteraction, new BABYLON.Vector2(0.5, 0.5), isVisible, null, null, null, null, null, null);
  42215. if (createWorldSpaceNode) {
  42216. var plane = new BABYLON.WorldSpaceCanvas2D(id, scene, c);
  42217. var vertexData = BABYLON.VertexData.CreatePlane({
  42218. width: size.width,
  42219. height: size.height,
  42220. sideOrientation: options && options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  42221. });
  42222. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  42223. c.applyCachedTexture(vertexData, mtl);
  42224. vertexData.applyToMesh(plane, false);
  42225. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  42226. mtl.disableLighting = true;
  42227. mtl.useAlphaFromDiffuseTexture = true;
  42228. plane.position = options && options.position || BABYLON.Vector3.Zero();
  42229. plane.rotationQuaternion = options && options.rotation || BABYLON.Quaternion.Identity();
  42230. plane.material = mtl;
  42231. c._worldSpaceNode = plane;
  42232. }
  42233. else {
  42234. c._worldSpaceNode = options.customWorldSpaceNode;
  42235. }
  42236. return c;
  42237. };
  42238. Canvas2D.prototype.setupCanvas = function (scene, name, size, renderScaleFactor, isScreenSpace, cachingstrategy, enableInteraction, origin, isVisible, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign) {
  42239. var _this = this;
  42240. var engine = scene.getEngine();
  42241. this._fitRenderingDevice = !size;
  42242. if (!size) {
  42243. size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  42244. }
  42245. else {
  42246. size.height *= renderScaleFactor;
  42247. size.width *= renderScaleFactor;
  42248. }
  42249. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  42250. this._renderScaleFactor = renderScaleFactor;
  42251. this._cachingStrategy = cachingstrategy;
  42252. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  42253. this._capturedPointers = new BABYLON.StringDictionary();
  42254. this._pickStartingPosition = BABYLON.Vector2.Zero();
  42255. this.setupGroup2D(this, null, name, BABYLON.Vector2.Zero(), origin, size, isVisible, this._cachingStrategy === Canvas2D.CACHESTRATEGY_ALLGROUPS ? BABYLON.Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE : BABYLON.Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY, marginTop, marginLeft, marginRight, marginBottom, hAlign, vAlign);
  42256. this._hierarchyLevelMaxSiblingCount = 10;
  42257. this._hierarchyDepthOffset = 0;
  42258. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  42259. this._scene = scene;
  42260. this._engine = engine;
  42261. this._renderingSize = new BABYLON.Size(0, 0);
  42262. // Register scene dispose to also dispose the canvas when it'll happens
  42263. scene.onDisposeObservable.add(function (d, s) {
  42264. _this.dispose();
  42265. });
  42266. if (cachingstrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42267. this._background = BABYLON.Rectangle2D.Create(this, { id: "###CANVAS BACKGROUND###", width: size.width, height: size.height });
  42268. this._background.isPickable = false;
  42269. this._background.origin = BABYLON.Vector2.Zero();
  42270. this._background.levelVisible = false;
  42271. }
  42272. this._isScreeSpace = isScreenSpace;
  42273. if (this._isScreeSpace) {
  42274. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  42275. _this._engine.clear(null, false, true);
  42276. _this._render();
  42277. });
  42278. }
  42279. else {
  42280. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  42281. _this._render();
  42282. });
  42283. }
  42284. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  42285. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  42286. this._setupInteraction(enableInteraction);
  42287. };
  42288. Object.defineProperty(Canvas2D.prototype, "hierarchyLevelMaxSiblingCount", {
  42289. get: function () {
  42290. return this._hierarchyLevelMaxSiblingCount;
  42291. },
  42292. enumerable: true,
  42293. configurable: true
  42294. });
  42295. Canvas2D.prototype._setupInteraction = function (enable) {
  42296. var _this = this;
  42297. // No change detection
  42298. if (enable === this._interactionEnabled) {
  42299. return;
  42300. }
  42301. // Set the new state
  42302. this._interactionEnabled = enable;
  42303. // ScreenSpace mode
  42304. if (this._isScreeSpace) {
  42305. // Disable interaction
  42306. if (!enable) {
  42307. if (this._scenePrePointerObserver) {
  42308. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  42309. this._scenePrePointerObserver = null;
  42310. }
  42311. return;
  42312. }
  42313. // Enable Interaction
  42314. // Register the observable
  42315. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  42316. var hs = 1 / _this.engine.getHardwareScalingLevel();
  42317. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  42318. _this._handlePointerEventForInteraction(e, localPos, s);
  42319. });
  42320. }
  42321. else {
  42322. var scene = this.scene;
  42323. if (enable) {
  42324. scene.constantlyUpdateMeshUnderPointer = true;
  42325. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  42326. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  42327. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  42328. _this._handlePointerEventForInteraction(e, localPos, s);
  42329. }
  42330. });
  42331. }
  42332. else {
  42333. if (this._scenePointerObserver) {
  42334. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  42335. this._scenePointerObserver = null;
  42336. }
  42337. }
  42338. }
  42339. };
  42340. /**
  42341. * Internal method, you should use the Prim2DBase version instead
  42342. */
  42343. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  42344. if (this.isPointerCaptured(pointerId)) {
  42345. return false;
  42346. }
  42347. // Try to capture the pointer on the HTML side
  42348. try {
  42349. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  42350. }
  42351. catch (e) {
  42352. }
  42353. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  42354. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  42355. this._capturedPointers.add(pointerId.toString(), primitive);
  42356. return true;
  42357. };
  42358. /**
  42359. * Internal method, you should use the Prim2DBase version instead
  42360. */
  42361. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  42362. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  42363. return false;
  42364. }
  42365. // Try to release the pointer on the HTML side
  42366. try {
  42367. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  42368. }
  42369. catch (e) {
  42370. }
  42371. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  42372. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  42373. this._capturedPointers.remove(pointerId.toString());
  42374. return true;
  42375. };
  42376. /**
  42377. * Determine if the given pointer is captured or not
  42378. * @param pointerId the Id of the pointer
  42379. * @return true if it's captured, false otherwise
  42380. */
  42381. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  42382. return this._capturedPointers.contains(pointerId.toString());
  42383. };
  42384. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  42385. // Avoid unnecessary lookup
  42386. if (this._capturedPointers.count === 0) {
  42387. return null;
  42388. }
  42389. return this._capturedPointers.get(pointerId.toString());
  42390. };
  42391. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  42392. // Dispose check
  42393. if (this.isDisposed) {
  42394. return;
  42395. }
  42396. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  42397. this._updatePointerInfo(eventData, localPosition);
  42398. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  42399. // 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.
  42400. // 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.
  42401. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  42402. // 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
  42403. this._updateOverStatus();
  42404. // Check if we have nothing to raise
  42405. if (!this._actualOverPrimitive && !capturedPrim) {
  42406. return;
  42407. }
  42408. // Update the relatedTarget info with the over primitive or the captured one (if any)
  42409. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  42410. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  42411. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  42412. // Analyze the pointer event type and fire proper events on the primitive
  42413. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  42414. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  42415. }
  42416. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42417. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  42418. }
  42419. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  42420. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  42421. }
  42422. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  42423. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  42424. }
  42425. };
  42426. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  42427. var pii = this._primPointerInfo;
  42428. if (!pii.canvasPointerPos) {
  42429. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  42430. }
  42431. var camera = this._scene.activeCamera;
  42432. var engine = this._scene.getEngine();
  42433. if (this._isScreeSpace) {
  42434. var cameraViewport = camera.viewport;
  42435. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  42436. // Moving coordinates to local viewport world
  42437. var x = localPosition.x - viewport.x;
  42438. var y = localPosition.y - viewport.y;
  42439. pii.canvasPointerPos.x = x - this.position.x;
  42440. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.position.y;
  42441. }
  42442. else {
  42443. pii.canvasPointerPos.x = localPosition.x;
  42444. pii.canvasPointerPos.y = localPosition.y;
  42445. }
  42446. pii.mouseWheelDelta = 0;
  42447. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  42448. var event = eventData.event;
  42449. if (event.wheelDelta) {
  42450. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  42451. }
  42452. else if (event.detail) {
  42453. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  42454. }
  42455. }
  42456. else {
  42457. var pe = eventData.event;
  42458. pii.ctrlKey = pe.ctrlKey;
  42459. pii.altKey = pe.altKey;
  42460. pii.shiftKey = pe.shiftKey;
  42461. pii.metaKey = pe.metaKey;
  42462. pii.button = pe.button;
  42463. pii.buttons = pe.buttons;
  42464. pii.pointerId = pe.pointerId;
  42465. pii.width = pe.width;
  42466. pii.height = pe.height;
  42467. pii.presssure = pe.pressure;
  42468. pii.tilt.x = pe.tiltX;
  42469. pii.tilt.y = pe.tiltY;
  42470. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  42471. }
  42472. };
  42473. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  42474. if (this.scene.getRenderId() === this._intersectionRenderId) {
  42475. return;
  42476. }
  42477. var ii = Canvas2D._interInfo;
  42478. ii.pickPosition.x = mouseLocalPos.x;
  42479. ii.pickPosition.y = mouseLocalPos.y;
  42480. ii.findFirstOnly = false;
  42481. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  42482. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  42483. this._previousIntersectionList = this._actualIntersectionList;
  42484. this._actualIntersectionList = null;
  42485. this._previousOverPrimitive = this._actualOverPrimitive;
  42486. this._actualOverPrimitive = null;
  42487. return;
  42488. }
  42489. this.intersect(ii);
  42490. this._previousIntersectionList = this._actualIntersectionList;
  42491. this._actualIntersectionList = ii.intersectedPrimitives;
  42492. this._previousOverPrimitive = this._actualOverPrimitive;
  42493. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  42494. this._intersectionRenderId = this.scene.getRenderId();
  42495. };
  42496. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  42497. Canvas2D.prototype._updateOverStatus = function () {
  42498. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  42499. return;
  42500. }
  42501. // Detect a change of over
  42502. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  42503. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  42504. if (prevPrim !== actualPrim) {
  42505. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  42506. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  42507. // Notify the previous "over" prim that the pointer is no longer over it
  42508. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  42509. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  42510. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  42511. }
  42512. // Notify the new "over" prim that the pointer is over it
  42513. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  42514. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  42515. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  42516. }
  42517. }
  42518. this._hoverStatusRenderId = this.scene.getRenderId();
  42519. };
  42520. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  42521. if (this._primPointerInfo.isCaptured) {
  42522. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  42523. }
  42524. else {
  42525. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  42526. var pii = _a[_i];
  42527. if (pii.prim === prim) {
  42528. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  42529. return;
  42530. }
  42531. }
  42532. }
  42533. };
  42534. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  42535. if (!this._notifDebugMode) {
  42536. return;
  42537. }
  42538. var debug = "";
  42539. for (var i = 0; i < prim.hierarchyDepth; i++) {
  42540. debug += " ";
  42541. }
  42542. var pii = this._primPointerInfo;
  42543. 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();
  42544. console.log(debug);
  42545. };
  42546. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  42547. var ppi = this._primPointerInfo;
  42548. // In case of PointerOver/Out we will first notify the children (but the deepest to the closest) with PointerEnter/Leave
  42549. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  42550. this._notifChildren(prim, mask);
  42551. }
  42552. var bubbleCancelled = false;
  42553. var cur = prim;
  42554. while (cur) {
  42555. // Only trigger the observers if the primitive is intersected (except for out)
  42556. if (!bubbleCancelled) {
  42557. this._updatePrimPointerPos(cur);
  42558. // Exec the observers
  42559. this._debugExecObserver(cur, mask);
  42560. cur._pointerEventObservable.notifyObservers(ppi, mask);
  42561. this._triggerActionManager(cur, ppi, mask, eventData);
  42562. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  42563. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  42564. if (ppi.cancelBubble) {
  42565. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  42566. return;
  42567. }
  42568. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  42569. bubbleCancelled = true;
  42570. }
  42571. }
  42572. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  42573. if (bubbleCancelled) {
  42574. this._updatePrimPointerPos(cur);
  42575. }
  42576. // Trigger a PointerEnter corresponding to the PointerOver
  42577. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  42578. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  42579. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  42580. }
  42581. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  42582. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  42583. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  42584. }
  42585. // Loop to the parent
  42586. cur = cur.parent;
  42587. }
  42588. };
  42589. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  42590. var _this = this;
  42591. // Process Trigger related to PointerDown
  42592. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  42593. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  42594. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  42595. this._pickStartingTime = new Date().getTime();
  42596. this._pickedDownPrim = null;
  42597. if (prim.actionManager) {
  42598. this._pickedDownPrim = prim;
  42599. if (prim.actionManager.hasPickTriggers) {
  42600. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  42601. switch (eventData.button) {
  42602. case 0:
  42603. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  42604. break;
  42605. case 1:
  42606. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  42607. break;
  42608. case 2:
  42609. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  42610. break;
  42611. }
  42612. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  42613. }
  42614. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  42615. window.setTimeout(function () {
  42616. var ppi = _this._primPointerInfo;
  42617. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  42618. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  42619. var ii = new BABYLON.IntersectInfo2D();
  42620. ii.pickPosition = ppi.canvasPointerPos.clone();
  42621. ii.findFirstOnly = false;
  42622. _this.intersect(ii);
  42623. if (ii.isPrimIntersected(prim) !== null) {
  42624. if (prim.actionManager) {
  42625. 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)) {
  42626. _this._pickStartingTime = 0;
  42627. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  42628. }
  42629. }
  42630. }
  42631. }, BABYLON.ActionManager.LongPressDelay);
  42632. }
  42633. }
  42634. }
  42635. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  42636. this._pickStartingTime = 0;
  42637. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  42638. if (prim.actionManager) {
  42639. // OnPickUpTrigger
  42640. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  42641. // OnPickTrigger
  42642. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  42643. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  42644. }
  42645. }
  42646. // OnPickOutTrigger
  42647. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  42648. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  42649. }
  42650. }
  42651. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  42652. if (prim.actionManager) {
  42653. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  42654. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  42655. }
  42656. }
  42657. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  42658. if (prim.actionManager) {
  42659. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  42660. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  42661. }
  42662. }
  42663. };
  42664. Canvas2D.prototype._notifChildren = function (prim, mask) {
  42665. var _this = this;
  42666. var pii = this._primPointerInfo;
  42667. prim.children.forEach(function (curChild) {
  42668. // Recurse first, we want the deepest to be notified first
  42669. _this._notifChildren(curChild, mask);
  42670. _this._updatePrimPointerPos(curChild);
  42671. // Fire the proper notification
  42672. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  42673. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerEnter);
  42674. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  42675. }
  42676. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  42677. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerLeave);
  42678. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  42679. }
  42680. });
  42681. };
  42682. /**
  42683. * Don't forget to call the dispose method when you're done with the Canvas instance.
  42684. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  42685. */
  42686. Canvas2D.prototype.dispose = function () {
  42687. if (!_super.prototype.dispose.call(this)) {
  42688. return false;
  42689. }
  42690. if (this.interactionEnabled) {
  42691. this._setupInteraction(false);
  42692. }
  42693. if (this._beforeRenderObserver) {
  42694. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  42695. this._beforeRenderObserver = null;
  42696. }
  42697. if (this._afterRenderObserver) {
  42698. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  42699. this._afterRenderObserver = null;
  42700. }
  42701. if (this._groupCacheMaps) {
  42702. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  42703. this._groupCacheMaps = null;
  42704. }
  42705. };
  42706. Object.defineProperty(Canvas2D.prototype, "scene", {
  42707. /**
  42708. * Accessor to the Scene that owns the Canvas
  42709. * @returns The instance of the Scene object
  42710. */
  42711. get: function () {
  42712. return this._scene;
  42713. },
  42714. enumerable: true,
  42715. configurable: true
  42716. });
  42717. Object.defineProperty(Canvas2D.prototype, "engine", {
  42718. /**
  42719. * Accessor to the Engine that drives the Scene used by this Canvas
  42720. * @returns The instance of the Engine object
  42721. */
  42722. get: function () {
  42723. return this._engine;
  42724. },
  42725. enumerable: true,
  42726. configurable: true
  42727. });
  42728. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  42729. /**
  42730. * Accessor of the Caching Strategy used by this Canvas.
  42731. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  42732. * @returns the value corresponding to the used strategy.
  42733. */
  42734. get: function () {
  42735. return this._cachingStrategy;
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  42741. /**
  42742. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  42743. */
  42744. get: function () {
  42745. return this._worldSpaceNode;
  42746. },
  42747. enumerable: true,
  42748. configurable: true
  42749. });
  42750. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  42751. /**
  42752. * Check if the WebGL Instanced Array extension is supported or not
  42753. * @returns {}
  42754. */
  42755. get: function () {
  42756. return this._supprtInstancedArray;
  42757. },
  42758. enumerable: true,
  42759. configurable: true
  42760. });
  42761. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  42762. /**
  42763. * Property that defines the fill object used to draw the background of the Canvas.
  42764. * Note that Canvas with a Caching Strategy of
  42765. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  42766. */
  42767. get: function () {
  42768. if (!this._background || !this._background.isVisible) {
  42769. return null;
  42770. }
  42771. return this._background.fill;
  42772. },
  42773. set: function (value) {
  42774. this.checkBackgroundAvailability();
  42775. if (value === this._background.fill) {
  42776. return;
  42777. }
  42778. this._background.fill = value;
  42779. this._background.levelVisible = true;
  42780. },
  42781. enumerable: true,
  42782. configurable: true
  42783. });
  42784. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  42785. /**
  42786. * Property that defines the border object used to draw the background of the Canvas.
  42787. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  42788. */
  42789. get: function () {
  42790. if (!this._background || !this._background.isVisible) {
  42791. return null;
  42792. }
  42793. return this._background.border;
  42794. },
  42795. set: function (value) {
  42796. this.checkBackgroundAvailability();
  42797. if (value === this._background.border) {
  42798. return;
  42799. }
  42800. this._background.border = value;
  42801. this._background.levelVisible = true;
  42802. },
  42803. enumerable: true,
  42804. configurable: true
  42805. });
  42806. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  42807. /**
  42808. * You can set the roundRadius of the background
  42809. * @returns The current roundRadius
  42810. */
  42811. get: function () {
  42812. if (!this._background || !this._background.isVisible) {
  42813. return null;
  42814. }
  42815. return this._background.roundRadius;
  42816. },
  42817. set: function (value) {
  42818. this.checkBackgroundAvailability();
  42819. if (value === this._background.roundRadius) {
  42820. return;
  42821. }
  42822. this._background.roundRadius = value;
  42823. this._background.levelVisible = true;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  42829. /**
  42830. * Enable/Disable interaction for this Canvas
  42831. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  42832. */
  42833. get: function () {
  42834. return this._interactionEnabled;
  42835. },
  42836. set: function (enable) {
  42837. this._setupInteraction(enable);
  42838. },
  42839. enumerable: true,
  42840. configurable: true
  42841. });
  42842. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  42843. get: function () {
  42844. return this.__engineData;
  42845. },
  42846. enumerable: true,
  42847. configurable: true
  42848. });
  42849. Canvas2D.prototype.checkBackgroundAvailability = function () {
  42850. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42851. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  42852. }
  42853. };
  42854. Canvas2D.prototype.onPrimBecomesDirty = function () {
  42855. this._addPrimToDirtyList(this);
  42856. };
  42857. Canvas2D.prototype._updateCanvasState = function () {
  42858. // Check if the update has already been made for this render Frame
  42859. if (this.scene.getRenderId() === this._updateRenderId) {
  42860. return;
  42861. }
  42862. this._renderingSize.width = this.engine.getRenderWidth();
  42863. this._renderingSize.height = this.engine.getRenderHeight();
  42864. if (this._fitRenderingDevice) {
  42865. this.size = this._renderingSize;
  42866. if (this._background) {
  42867. this._background.size = this.size;
  42868. }
  42869. }
  42870. var context = new BABYLON.PrepareRender2DContext();
  42871. ++this._globalTransformProcessStep;
  42872. this.updateGlobalTransVis(false);
  42873. this._prepareGroupRender(context);
  42874. this._updateRenderId = this.scene.getRenderId();
  42875. };
  42876. /**
  42877. * Method that renders the Canvas, you should not invoke
  42878. */
  42879. Canvas2D.prototype._render = function () {
  42880. this._updateCanvasState();
  42881. if (this._primPointerInfo.canvasPointerPos) {
  42882. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  42883. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  42884. }
  42885. this._groupRender();
  42886. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  42887. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  42888. this._cachedCanvasGroup._renderCachedCanvas();
  42889. }
  42890. };
  42891. /**
  42892. * Internal method that allocate a cache for the given group.
  42893. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  42894. * @param group The group to allocate the cache of.
  42895. * @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.
  42896. */
  42897. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  42898. // Determine size
  42899. var size = group.actualSize;
  42900. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  42901. if (minSize) {
  42902. size.width = Math.max(minSize.width, size.width);
  42903. size.height = Math.max(minSize.height, size.height);
  42904. }
  42905. if (!this._groupCacheMaps) {
  42906. this._groupCacheMaps = new Array();
  42907. }
  42908. // Try to find a spot in one of the cached texture
  42909. var res = null;
  42910. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  42911. var map = _a[_i];
  42912. var node = map.allocateRect(size);
  42913. if (node) {
  42914. res = { node: node, texture: map };
  42915. break;
  42916. }
  42917. }
  42918. // Couldn't find a map that could fit the rect, create a new map for it
  42919. if (!res) {
  42920. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  42921. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  42922. if (size.width > mapSize.width || size.height > mapSize.height) {
  42923. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  42924. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  42925. }
  42926. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  42927. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  42928. this._groupCacheMaps.push(map);
  42929. var node = map.allocateRect(size);
  42930. res = { node: node, texture: map };
  42931. }
  42932. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  42933. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  42934. if (group !== this || this._isScreeSpace) {
  42935. var node = res.node;
  42936. // 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
  42937. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  42938. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  42939. var sprite = BABYLON.Sprite2D.Create(this._cachedCanvasGroup, map, { id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  42940. sprite.zOrder = 1;
  42941. sprite.origin = BABYLON.Vector2.Zero();
  42942. }
  42943. else {
  42944. 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 });
  42945. sprite.origin = group.origin.clone();
  42946. res.sprite = sprite;
  42947. }
  42948. }
  42949. return res;
  42950. };
  42951. /**
  42952. * Get a Solid Color Brush instance matching the given color.
  42953. * @param color The color to retrieve
  42954. * @return A shared instance of the SolidColorBrush2D class that use the given color
  42955. */
  42956. Canvas2D.GetSolidColorBrush = function (color) {
  42957. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  42958. };
  42959. /**
  42960. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  42961. * @param color The color to retrieve
  42962. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  42963. */
  42964. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  42965. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  42966. };
  42967. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  42968. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  42969. if (rotation === void 0) { rotation = 0; }
  42970. if (scale === void 0) { scale = 1; }
  42971. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  42972. };
  42973. /**
  42974. * 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.
  42975. * This strategy doesn't allow primitives added directly as children of the Canvas.
  42976. * 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.
  42977. */
  42978. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  42979. /**
  42980. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  42981. * 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.
  42982. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  42983. * 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.
  42984. */
  42985. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  42986. /**
  42987. * 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).
  42988. */
  42989. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  42990. /**
  42991. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  42992. * 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).
  42993. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  42994. */
  42995. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  42996. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  42997. /**
  42998. * Define the default size used for both the width and height of a MapTexture to allocate.
  42999. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  43000. */
  43001. Canvas2D._groupTextureCacheSize = 1024;
  43002. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  43003. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  43004. Canvas2D = __decorate([
  43005. BABYLON.className("Canvas2D")
  43006. ], Canvas2D);
  43007. return Canvas2D;
  43008. })(BABYLON.Group2D);
  43009. BABYLON.Canvas2D = Canvas2D;
  43010. })(BABYLON || (BABYLON = {}));
  43011. var BABYLON;
  43012. (function (BABYLON) {
  43013. /**
  43014. * This is the class that is used to display a World Space Canvas into a scene
  43015. */
  43016. var WorldSpaceCanvas2D = (function (_super) {
  43017. __extends(WorldSpaceCanvas2D, _super);
  43018. function WorldSpaceCanvas2D(name, scene, canvas) {
  43019. _super.call(this, name, scene);
  43020. this._canvas = canvas;
  43021. }
  43022. WorldSpaceCanvas2D.prototype.dispose = function () {
  43023. _super.prototype.dispose.call(this);
  43024. if (this._canvas) {
  43025. this._canvas.dispose();
  43026. this._canvas = null;
  43027. }
  43028. };
  43029. return WorldSpaceCanvas2D;
  43030. })(BABYLON.Mesh);
  43031. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  43032. })(BABYLON || (BABYLON = {}));
  43033. var BABYLON;
  43034. (function (BABYLON) {
  43035. var ShaderMaterial = (function (_super) {
  43036. __extends(ShaderMaterial, _super);
  43037. function ShaderMaterial(name, scene, shaderPath, options) {
  43038. _super.call(this, name, scene);
  43039. this._textures = {};
  43040. this._floats = {};
  43041. this._floatsArrays = {};
  43042. this._colors3 = {};
  43043. this._colors4 = {};
  43044. this._vectors2 = {};
  43045. this._vectors3 = {};
  43046. this._vectors4 = {};
  43047. this._matrices = {};
  43048. this._matrices3x3 = {};
  43049. this._matrices2x2 = {};
  43050. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43051. this._shaderPath = shaderPath;
  43052. options.needAlphaBlending = options.needAlphaBlending || false;
  43053. options.needAlphaTesting = options.needAlphaTesting || false;
  43054. options.attributes = options.attributes || ["position", "normal", "uv"];
  43055. options.uniforms = options.uniforms || ["worldViewProjection"];
  43056. options.samplers = options.samplers || [];
  43057. options.defines = options.defines || [];
  43058. this._options = options;
  43059. }
  43060. ShaderMaterial.prototype.needAlphaBlending = function () {
  43061. return this._options.needAlphaBlending;
  43062. };
  43063. ShaderMaterial.prototype.needAlphaTesting = function () {
  43064. return this._options.needAlphaTesting;
  43065. };
  43066. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43067. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43068. this._options.uniforms.push(uniformName);
  43069. }
  43070. };
  43071. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43072. if (this._options.samplers.indexOf(name) === -1) {
  43073. this._options.samplers.push(name);
  43074. }
  43075. this._textures[name] = texture;
  43076. return this;
  43077. };
  43078. ShaderMaterial.prototype.setFloat = function (name, value) {
  43079. this._checkUniform(name);
  43080. this._floats[name] = value;
  43081. return this;
  43082. };
  43083. ShaderMaterial.prototype.setFloats = function (name, value) {
  43084. this._checkUniform(name);
  43085. this._floatsArrays[name] = value;
  43086. return this;
  43087. };
  43088. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43089. this._checkUniform(name);
  43090. this._colors3[name] = value;
  43091. return this;
  43092. };
  43093. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43094. this._checkUniform(name);
  43095. this._colors4[name] = value;
  43096. return this;
  43097. };
  43098. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43099. this._checkUniform(name);
  43100. this._vectors2[name] = value;
  43101. return this;
  43102. };
  43103. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43104. this._checkUniform(name);
  43105. this._vectors3[name] = value;
  43106. return this;
  43107. };
  43108. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43109. this._checkUniform(name);
  43110. this._vectors4[name] = value;
  43111. return this;
  43112. };
  43113. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43114. this._checkUniform(name);
  43115. this._matrices[name] = value;
  43116. return this;
  43117. };
  43118. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43119. this._checkUniform(name);
  43120. this._matrices3x3[name] = value;
  43121. return this;
  43122. };
  43123. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43124. this._checkUniform(name);
  43125. this._matrices2x2[name] = value;
  43126. return this;
  43127. };
  43128. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43129. var scene = this.getScene();
  43130. var engine = scene.getEngine();
  43131. if (!this.checkReadyOnEveryCall) {
  43132. if (this._renderId === scene.getRenderId()) {
  43133. return true;
  43134. }
  43135. }
  43136. // Instances
  43137. var defines = [];
  43138. var fallbacks = new BABYLON.EffectFallbacks();
  43139. if (useInstances) {
  43140. defines.push("#define INSTANCES");
  43141. }
  43142. for (var index = 0; index < this._options.defines.length; index++) {
  43143. defines.push(this._options.defines[index]);
  43144. }
  43145. // Bones
  43146. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43147. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43148. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43149. fallbacks.addCPUSkinningFallback(0, mesh);
  43150. }
  43151. // Alpha test
  43152. if (engine.getAlphaTesting()) {
  43153. defines.push("#define ALPHATEST");
  43154. }
  43155. var previousEffect = this._effect;
  43156. var join = defines.join("\n");
  43157. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  43158. if (!this._effect.isReady()) {
  43159. return false;
  43160. }
  43161. if (previousEffect !== this._effect) {
  43162. scene.resetCachedMaterial();
  43163. }
  43164. this._renderId = scene.getRenderId();
  43165. return true;
  43166. };
  43167. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43168. var scene = this.getScene();
  43169. if (this._options.uniforms.indexOf("world") !== -1) {
  43170. this._effect.setMatrix("world", world);
  43171. }
  43172. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43173. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43174. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43175. }
  43176. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43177. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43178. }
  43179. };
  43180. ShaderMaterial.prototype.bind = function (world, mesh) {
  43181. // Std values
  43182. this.bindOnlyWorldMatrix(world);
  43183. if (this.getScene().getCachedMaterial() !== this) {
  43184. if (this._options.uniforms.indexOf("view") !== -1) {
  43185. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43186. }
  43187. if (this._options.uniforms.indexOf("projection") !== -1) {
  43188. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43189. }
  43190. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43191. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43192. }
  43193. // Bones
  43194. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43195. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43196. }
  43197. // Texture
  43198. for (var name in this._textures) {
  43199. this._effect.setTexture(name, this._textures[name]);
  43200. }
  43201. // Float
  43202. for (name in this._floats) {
  43203. this._effect.setFloat(name, this._floats[name]);
  43204. }
  43205. // Float s
  43206. for (name in this._floatsArrays) {
  43207. this._effect.setArray(name, this._floatsArrays[name]);
  43208. }
  43209. // Color3
  43210. for (name in this._colors3) {
  43211. this._effect.setColor3(name, this._colors3[name]);
  43212. }
  43213. // Color4
  43214. for (name in this._colors4) {
  43215. var color = this._colors4[name];
  43216. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43217. }
  43218. // Vector2
  43219. for (name in this._vectors2) {
  43220. this._effect.setVector2(name, this._vectors2[name]);
  43221. }
  43222. // Vector3
  43223. for (name in this._vectors3) {
  43224. this._effect.setVector3(name, this._vectors3[name]);
  43225. }
  43226. // Vector4
  43227. for (name in this._vectors4) {
  43228. this._effect.setVector4(name, this._vectors4[name]);
  43229. }
  43230. // Matrix
  43231. for (name in this._matrices) {
  43232. this._effect.setMatrix(name, this._matrices[name]);
  43233. }
  43234. // Matrix 3x3
  43235. for (name in this._matrices3x3) {
  43236. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43237. }
  43238. // Matrix 2x2
  43239. for (name in this._matrices2x2) {
  43240. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43241. }
  43242. }
  43243. _super.prototype.bind.call(this, world, mesh);
  43244. };
  43245. ShaderMaterial.prototype.clone = function (name) {
  43246. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43247. return newShaderMaterial;
  43248. };
  43249. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43250. if (forceDisposeTextures) {
  43251. for (var name in this._textures) {
  43252. this._textures[name].dispose();
  43253. }
  43254. }
  43255. this._textures = {};
  43256. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43257. };
  43258. ShaderMaterial.prototype.serialize = function () {
  43259. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43260. serializationObject.customType = "BABYLON.ShaderMaterial";
  43261. serializationObject.options = this._options;
  43262. serializationObject.shaderPath = this._shaderPath;
  43263. // Texture
  43264. serializationObject.textures = {};
  43265. for (var name in this._textures) {
  43266. serializationObject.textures[name] = this._textures[name].serialize();
  43267. }
  43268. // Float
  43269. serializationObject.floats = {};
  43270. for (name in this._floats) {
  43271. serializationObject.floats[name] = this._floats[name];
  43272. }
  43273. // Float s
  43274. serializationObject.floatArrays = {};
  43275. for (name in this._floatsArrays) {
  43276. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43277. }
  43278. // Color3
  43279. serializationObject.colors3 = {};
  43280. for (name in this._colors3) {
  43281. serializationObject.colors3[name] = this._colors3[name].asArray();
  43282. }
  43283. // Color4
  43284. serializationObject.colors4 = {};
  43285. for (name in this._colors4) {
  43286. serializationObject.colors4[name] = this._colors4[name].asArray();
  43287. }
  43288. // Vector2
  43289. serializationObject.vectors2 = {};
  43290. for (name in this._vectors2) {
  43291. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43292. }
  43293. // Vector3
  43294. serializationObject.vectors3 = {};
  43295. for (name in this._vectors3) {
  43296. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43297. }
  43298. // Vector4
  43299. serializationObject.vectors4 = {};
  43300. for (name in this._vectors4) {
  43301. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43302. }
  43303. // Matrix
  43304. serializationObject.matrices = {};
  43305. for (name in this._matrices) {
  43306. serializationObject.matrices[name] = this._matrices[name].asArray();
  43307. }
  43308. // Matrix 3x3
  43309. serializationObject.matrices3x3 = {};
  43310. for (name in this._matrices3x3) {
  43311. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43312. }
  43313. // Matrix 2x2
  43314. serializationObject.matrices2x2 = {};
  43315. for (name in this._matrices2x2) {
  43316. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43317. }
  43318. return serializationObject;
  43319. };
  43320. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43321. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43322. // Texture
  43323. for (var name in source.textures) {
  43324. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43325. }
  43326. // Float
  43327. for (name in source.floats) {
  43328. material.setFloat(name, source.floats[name]);
  43329. }
  43330. // Float s
  43331. for (name in source.floatsArrays) {
  43332. material.setFloats(name, source.floatsArrays[name]);
  43333. }
  43334. // Color3
  43335. for (name in source.colors3) {
  43336. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43337. }
  43338. // Color4
  43339. for (name in source.colors4) {
  43340. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43341. }
  43342. // Vector2
  43343. for (name in source.vectors2) {
  43344. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43345. }
  43346. // Vector3
  43347. for (name in source.vectors3) {
  43348. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43349. }
  43350. // Vector4
  43351. for (name in source.vectors4) {
  43352. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43353. }
  43354. // Matrix
  43355. for (name in source.matrices) {
  43356. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43357. }
  43358. // Matrix 3x3
  43359. for (name in source.matrices3x3) {
  43360. material.setMatrix3x3(name, source.matrices3x3[name]);
  43361. }
  43362. // Matrix 2x2
  43363. for (name in source.matrices2x2) {
  43364. material.setMatrix2x2(name, source.matrices2x2[name]);
  43365. }
  43366. return material;
  43367. };
  43368. return ShaderMaterial;
  43369. })(BABYLON.Material);
  43370. BABYLON.ShaderMaterial = ShaderMaterial;
  43371. })(BABYLON || (BABYLON = {}));
  43372. var BABYLON;
  43373. (function (BABYLON) {
  43374. var Internals;
  43375. (function (Internals) {
  43376. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  43377. // All values and structures referenced from:
  43378. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  43379. var DDS_MAGIC = 0x20534444;
  43380. 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;
  43381. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  43382. 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;
  43383. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  43384. function FourCCToInt32(value) {
  43385. return value.charCodeAt(0) +
  43386. (value.charCodeAt(1) << 8) +
  43387. (value.charCodeAt(2) << 16) +
  43388. (value.charCodeAt(3) << 24);
  43389. }
  43390. function Int32ToFourCC(value) {
  43391. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  43392. }
  43393. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  43394. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  43395. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  43396. var headerLengthInt = 31; // The header length in 32 bit ints
  43397. // Offsets into the header array
  43398. var off_magic = 0;
  43399. var off_size = 1;
  43400. var off_flags = 2;
  43401. var off_height = 3;
  43402. var off_width = 4;
  43403. var off_mipmapCount = 7;
  43404. var off_pfFlags = 20;
  43405. var off_pfFourCC = 21;
  43406. var off_RGBbpp = 22;
  43407. var off_RMask = 23;
  43408. var off_GMask = 24;
  43409. var off_BMask = 25;
  43410. var off_AMask = 26;
  43411. var off_caps1 = 27;
  43412. var off_caps2 = 28;
  43413. ;
  43414. var DDSTools = (function () {
  43415. function DDSTools() {
  43416. }
  43417. DDSTools.GetDDSInfo = function (arrayBuffer) {
  43418. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  43419. var mipmapCount = 1;
  43420. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  43421. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43422. }
  43423. return {
  43424. width: header[off_width],
  43425. height: header[off_height],
  43426. mipmapCount: mipmapCount,
  43427. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  43428. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  43429. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  43430. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  43431. };
  43432. };
  43433. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43434. var byteArray = new Uint8Array(dataLength);
  43435. var srcData = new Uint8Array(arrayBuffer);
  43436. var index = 0;
  43437. for (var y = height - 1; y >= 0; y--) {
  43438. for (var x = 0; x < width; x++) {
  43439. var srcPos = dataOffset + (x + y * width) * 4;
  43440. byteArray[index + 2] = srcData[srcPos];
  43441. byteArray[index + 1] = srcData[srcPos + 1];
  43442. byteArray[index] = srcData[srcPos + 2];
  43443. byteArray[index + 3] = srcData[srcPos + 3];
  43444. index += 4;
  43445. }
  43446. }
  43447. return byteArray;
  43448. };
  43449. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43450. var byteArray = new Uint8Array(dataLength);
  43451. var srcData = new Uint8Array(arrayBuffer);
  43452. var index = 0;
  43453. for (var y = height - 1; y >= 0; y--) {
  43454. for (var x = 0; x < width; x++) {
  43455. var srcPos = dataOffset + (x + y * width) * 3;
  43456. byteArray[index + 2] = srcData[srcPos];
  43457. byteArray[index + 1] = srcData[srcPos + 1];
  43458. byteArray[index] = srcData[srcPos + 2];
  43459. index += 3;
  43460. }
  43461. }
  43462. return byteArray;
  43463. };
  43464. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43465. var byteArray = new Uint8Array(dataLength);
  43466. var srcData = new Uint8Array(arrayBuffer);
  43467. var index = 0;
  43468. for (var y = height - 1; y >= 0; y--) {
  43469. for (var x = 0; x < width; x++) {
  43470. var srcPos = dataOffset + (x + y * width);
  43471. byteArray[index] = srcData[srcPos];
  43472. index++;
  43473. }
  43474. }
  43475. return byteArray;
  43476. };
  43477. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  43478. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  43479. if (header[off_magic] != DDS_MAGIC) {
  43480. BABYLON.Tools.Error("Invalid magic number in DDS header");
  43481. return;
  43482. }
  43483. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  43484. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  43485. return;
  43486. }
  43487. if (info.isFourCC) {
  43488. fourCC = header[off_pfFourCC];
  43489. switch (fourCC) {
  43490. case FOURCC_DXT1:
  43491. blockBytes = 8;
  43492. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43493. break;
  43494. case FOURCC_DXT3:
  43495. blockBytes = 16;
  43496. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43497. break;
  43498. case FOURCC_DXT5:
  43499. blockBytes = 16;
  43500. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43501. break;
  43502. default:
  43503. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  43504. return;
  43505. }
  43506. }
  43507. mipmapCount = 1;
  43508. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  43509. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43510. }
  43511. var bpp = header[off_RGBbpp];
  43512. for (var face = 0; face < faces; face++) {
  43513. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  43514. width = header[off_width];
  43515. height = header[off_height];
  43516. dataOffset = header[off_size] + 4;
  43517. for (i = 0; i < mipmapCount; ++i) {
  43518. if (info.isRGB) {
  43519. if (bpp === 24) {
  43520. dataLength = width * height * 3;
  43521. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43522. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  43523. }
  43524. else {
  43525. dataLength = width * height * 4;
  43526. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43527. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  43528. }
  43529. }
  43530. else if (info.isLuminance) {
  43531. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  43532. var unpaddedRowSize = width;
  43533. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  43534. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  43535. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  43536. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  43537. }
  43538. else {
  43539. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  43540. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  43541. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  43542. }
  43543. dataOffset += dataLength;
  43544. width *= 0.5;
  43545. height *= 0.5;
  43546. width = Math.max(1.0, width);
  43547. height = Math.max(1.0, height);
  43548. }
  43549. }
  43550. };
  43551. return DDSTools;
  43552. })();
  43553. Internals.DDSTools = DDSTools;
  43554. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43555. })(BABYLON || (BABYLON = {}));
  43556. var BABYLON;
  43557. (function (BABYLON) {
  43558. var CannonJSPlugin = (function () {
  43559. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  43560. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  43561. if (iterations === void 0) { iterations = 10; }
  43562. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  43563. this.name = "CannonJSPlugin";
  43564. this._physicsMaterials = [];
  43565. this._fixedTimeStep = 1 / 60;
  43566. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  43567. this._currentCollisionGroup = 2;
  43568. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  43569. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  43570. this._tmpPosition = BABYLON.Vector3.Zero();
  43571. this._tmpQuaternion = new BABYLON.Quaternion();
  43572. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  43573. this._tmpDeltaRotation = new BABYLON.Quaternion();
  43574. this._tmpUnityRotation = new BABYLON.Quaternion();
  43575. if (!this.isSupported()) {
  43576. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  43577. return;
  43578. }
  43579. this.world = new CANNON.World();
  43580. this.world.broadphase = new CANNON.NaiveBroadphase();
  43581. this.world.solver.iterations = iterations;
  43582. }
  43583. CannonJSPlugin.prototype.setGravity = function (gravity) {
  43584. this.world.gravity.copy(gravity);
  43585. };
  43586. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  43587. this._fixedTimeStep = timeStep;
  43588. };
  43589. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  43590. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  43591. };
  43592. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  43593. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  43594. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  43595. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  43596. };
  43597. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  43598. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  43599. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  43600. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  43601. };
  43602. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  43603. //parent-child relationship. Does this impostor has a parent impostor?
  43604. if (impostor.parent) {
  43605. if (impostor.physicsBody) {
  43606. this.removePhysicsBody(impostor);
  43607. //TODO is that needed?
  43608. impostor.forceUpdate();
  43609. }
  43610. return;
  43611. }
  43612. //should a new body be created for this impostor?
  43613. if (impostor.isBodyInitRequired()) {
  43614. var shape = this._createShape(impostor);
  43615. //unregister events, if body is being changed
  43616. var oldBody = impostor.physicsBody;
  43617. if (oldBody) {
  43618. this.removePhysicsBody(impostor);
  43619. }
  43620. //create the body and material
  43621. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  43622. var bodyCreationObject = {
  43623. mass: impostor.getParam("mass"),
  43624. material: material
  43625. };
  43626. // A simple extend, in case native options were used.
  43627. var nativeOptions = impostor.getParam("nativeOptions");
  43628. for (var key in nativeOptions) {
  43629. if (nativeOptions.hasOwnProperty(key)) {
  43630. bodyCreationObject[key] = nativeOptions[key];
  43631. }
  43632. }
  43633. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  43634. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  43635. this.world.addEventListener("preStep", impostor.beforeStep);
  43636. this.world.addEventListener("postStep", impostor.afterStep);
  43637. impostor.physicsBody.addShape(shape);
  43638. this.world.add(impostor.physicsBody);
  43639. //try to keep the body moving in the right direction by taking old properties.
  43640. //Should be tested!
  43641. if (oldBody) {
  43642. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  43643. impostor.physicsBody[param].copy(oldBody[param]);
  43644. });
  43645. }
  43646. this._processChildMeshes(impostor);
  43647. }
  43648. //now update the body's transformation
  43649. this._updatePhysicsBodyTransformation(impostor);
  43650. };
  43651. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  43652. var _this = this;
  43653. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  43654. if (meshChildren.length) {
  43655. var processMesh = function (localPosition, mesh) {
  43656. var childImpostor = mesh.getPhysicsImpostor();
  43657. if (childImpostor) {
  43658. var parent = childImpostor.parent;
  43659. if (parent !== mainImpostor) {
  43660. var localPosition = mesh.position;
  43661. if (childImpostor.physicsBody) {
  43662. _this.removePhysicsBody(childImpostor);
  43663. childImpostor.physicsBody = null;
  43664. }
  43665. childImpostor.parent = mainImpostor;
  43666. childImpostor.resetUpdateFlags();
  43667. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  43668. //Add the mass of the children.
  43669. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  43670. }
  43671. }
  43672. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  43673. };
  43674. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  43675. }
  43676. };
  43677. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  43678. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  43679. this.world.removeEventListener("preStep", impostor.beforeStep);
  43680. this.world.removeEventListener("postStep", impostor.afterStep);
  43681. this.world.remove(impostor.physicsBody);
  43682. };
  43683. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  43684. var mainBody = impostorJoint.mainImpostor.physicsBody;
  43685. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  43686. if (!mainBody || !connectedBody) {
  43687. return;
  43688. }
  43689. var constraint;
  43690. var jointData = impostorJoint.joint.jointData;
  43691. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  43692. var constraintData = {
  43693. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  43694. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  43695. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  43696. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  43697. maxForce: jointData.nativeParams.maxForce,
  43698. collideConnected: !!jointData.collision
  43699. };
  43700. //Not needed, Cannon has a collideConnected flag
  43701. /*if (!jointData.collision) {
  43702. //add 1st body to a collision group of its own, if it is not in 1
  43703. if (mainBody.collisionFilterGroup === 1) {
  43704. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  43705. this._currentCollisionGroup <<= 1;
  43706. }
  43707. if (connectedBody.collisionFilterGroup === 1) {
  43708. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  43709. this._currentCollisionGroup <<= 1;
  43710. }
  43711. //add their mask to the collisionFilterMask of each other:
  43712. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  43713. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  43714. }*/
  43715. switch (impostorJoint.joint.type) {
  43716. case BABYLON.PhysicsJoint.HingeJoint:
  43717. case BABYLON.PhysicsJoint.Hinge2Joint:
  43718. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  43719. break;
  43720. case BABYLON.PhysicsJoint.DistanceJoint:
  43721. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  43722. break;
  43723. case BABYLON.PhysicsJoint.SpringJoint:
  43724. var springData = jointData;
  43725. constraint = new CANNON.Spring(mainBody, connectedBody, {
  43726. restLength: springData.length,
  43727. stiffness: springData.stiffness,
  43728. damping: springData.damping,
  43729. localAnchorA: constraintData.pivotA,
  43730. localAnchorB: constraintData.pivotB
  43731. });
  43732. break;
  43733. case BABYLON.PhysicsJoint.LockJoint:
  43734. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  43735. break;
  43736. case BABYLON.PhysicsJoint.PointToPointJoint:
  43737. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  43738. default:
  43739. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  43740. break;
  43741. }
  43742. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  43743. constraint.collideConnected = !!jointData.collision;
  43744. impostorJoint.joint.physicsJoint = constraint;
  43745. //don't add spring as constraint, as it is not one.
  43746. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  43747. this.world.addConstraint(constraint);
  43748. }
  43749. else {
  43750. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  43751. constraint.applyForce();
  43752. });
  43753. }
  43754. };
  43755. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  43756. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  43757. };
  43758. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  43759. var index;
  43760. var mat;
  43761. for (index = 0; index < this._physicsMaterials.length; index++) {
  43762. mat = this._physicsMaterials[index];
  43763. if (mat.friction === friction && mat.restitution === restitution) {
  43764. return mat;
  43765. }
  43766. }
  43767. var currentMat = new CANNON.Material(name);
  43768. currentMat.friction = friction;
  43769. currentMat.restitution = restitution;
  43770. this._physicsMaterials.push(currentMat);
  43771. return currentMat;
  43772. };
  43773. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  43774. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  43775. };
  43776. CannonJSPlugin.prototype._createShape = function (impostor) {
  43777. var object = impostor.object;
  43778. var returnValue;
  43779. var extendSize = impostor.getObjectExtendSize();
  43780. switch (impostor.type) {
  43781. case BABYLON.PhysicsEngine.SphereImpostor:
  43782. var radiusX = extendSize.x;
  43783. var radiusY = extendSize.y;
  43784. var radiusZ = extendSize.z;
  43785. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  43786. break;
  43787. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  43788. case BABYLON.PhysicsImpostor.CylinderImpostor:
  43789. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  43790. break;
  43791. case BABYLON.PhysicsImpostor.BoxImpostor:
  43792. var box = extendSize.scale(0.5);
  43793. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  43794. break;
  43795. case BABYLON.PhysicsImpostor.PlaneImpostor:
  43796. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  43797. returnValue = new CANNON.Plane();
  43798. break;
  43799. case BABYLON.PhysicsImpostor.MeshImpostor:
  43800. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  43801. var rawFaces = object.getIndices ? object.getIndices() : [];
  43802. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  43803. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  43804. break;
  43805. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  43806. returnValue = this._createHeightmap(object);
  43807. break;
  43808. case BABYLON.PhysicsImpostor.ParticleImpostor:
  43809. returnValue = new CANNON.Particle();
  43810. break;
  43811. }
  43812. return returnValue;
  43813. };
  43814. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  43815. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43816. var matrix = [];
  43817. //For now pointDepth will not be used and will be automatically calculated.
  43818. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  43819. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  43820. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  43821. var elementSize = dim * 2 / arraySize;
  43822. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  43823. for (var i = 0; i < pos.length; i = i + 3) {
  43824. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  43825. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  43826. var y = pos[i + 1] + minY;
  43827. if (!matrix[x]) {
  43828. matrix[x] = [];
  43829. }
  43830. if (!matrix[x][z]) {
  43831. matrix[x][z] = y;
  43832. }
  43833. matrix[x][z] = Math.max(y, matrix[x][z]);
  43834. }
  43835. for (var x = 0; x <= arraySize; ++x) {
  43836. if (!matrix[x]) {
  43837. var loc = 1;
  43838. while (!matrix[(x + loc) % arraySize]) {
  43839. loc++;
  43840. }
  43841. matrix[x] = matrix[(x + loc) % arraySize].slice();
  43842. }
  43843. for (var z = 0; z <= arraySize; ++z) {
  43844. if (!matrix[x][z]) {
  43845. var loc = 1;
  43846. var newValue;
  43847. while (newValue === undefined) {
  43848. newValue = matrix[x][(z + loc++) % arraySize];
  43849. }
  43850. matrix[x][z] = newValue;
  43851. }
  43852. }
  43853. }
  43854. var shape = new CANNON.Heightfield(matrix, {
  43855. elementSize: elementSize
  43856. });
  43857. //For future reference, needed for body transformation
  43858. shape.minY = minY;
  43859. return shape;
  43860. };
  43861. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  43862. var object = impostor.object;
  43863. //make sure it is updated...
  43864. object.computeWorldMatrix && object.computeWorldMatrix(true);
  43865. // The delta between the mesh position and the mesh bounding box center
  43866. var center = impostor.getObjectCenter();
  43867. var extendSize = impostor.getObjectExtendSize();
  43868. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  43869. this._tmpPosition.copyFrom(center);
  43870. var quaternion = object.rotationQuaternion;
  43871. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  43872. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  43873. //-90 DEG in X, precalculated
  43874. quaternion = quaternion.multiply(this._minus90X);
  43875. //Invert! (Precalculated, 90 deg in X)
  43876. //No need to clone. this will never change.
  43877. impostor.setDeltaRotation(this._plus90X);
  43878. }
  43879. //If it is a heightfield, if should be centered.
  43880. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  43881. var mesh = object;
  43882. //calculate the correct body position:
  43883. var rotationQuaternion = mesh.rotationQuaternion;
  43884. mesh.rotationQuaternion = this._tmpUnityRotation;
  43885. mesh.computeWorldMatrix(true);
  43886. //get original center with no rotation
  43887. var c = center.clone();
  43888. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  43889. //rotation is back
  43890. mesh.rotationQuaternion = rotationQuaternion;
  43891. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  43892. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  43893. mesh.setPivotMatrix(p);
  43894. mesh.computeWorldMatrix(true);
  43895. //calculate the translation
  43896. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  43897. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  43898. //add it inverted to the delta
  43899. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  43900. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  43901. mesh.setPivotMatrix(oldPivot);
  43902. mesh.computeWorldMatrix(true);
  43903. }
  43904. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  43905. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  43906. this._tmpPosition.copyFrom(object.position);
  43907. }
  43908. impostor.setDeltaPosition(this._tmpDeltaPosition);
  43909. //Now update the impostor object
  43910. impostor.physicsBody.position.copy(this._tmpPosition);
  43911. impostor.physicsBody.quaternion.copy(quaternion);
  43912. };
  43913. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  43914. impostor.object.position.copyFrom(impostor.physicsBody.position);
  43915. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  43916. };
  43917. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  43918. impostor.physicsBody.position.copy(newPosition);
  43919. impostor.physicsBody.quaternion.copy(newRotation);
  43920. };
  43921. CannonJSPlugin.prototype.isSupported = function () {
  43922. return window.CANNON !== undefined;
  43923. };
  43924. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  43925. impostor.physicsBody.velocity.copy(velocity);
  43926. };
  43927. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  43928. impostor.physicsBody.angularVelocity.copy(velocity);
  43929. };
  43930. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  43931. var v = impostor.physicsBody.velocity;
  43932. if (!v)
  43933. return null;
  43934. return new BABYLON.Vector3(v.x, v.y, v.z);
  43935. };
  43936. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  43937. var v = impostor.physicsBody.angularVelocity;
  43938. if (!v)
  43939. return null;
  43940. return new BABYLON.Vector3(v.x, v.y, v.z);
  43941. };
  43942. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  43943. impostor.physicsBody.mass = mass;
  43944. impostor.physicsBody.updateMassProperties();
  43945. };
  43946. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  43947. impostor.physicsBody.sleep();
  43948. };
  43949. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  43950. impostor.physicsBody.wakeUp();
  43951. };
  43952. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  43953. joint.physicsJoint.distance = maxDistance;
  43954. };
  43955. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  43956. if (!motorIndex) {
  43957. joint.physicsJoint.enableMotor();
  43958. }
  43959. };
  43960. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  43961. if (!motorIndex) {
  43962. joint.physicsJoint.disableMotor();
  43963. }
  43964. };
  43965. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  43966. if (!motorIndex) {
  43967. joint.physicsJoint.enableMotor();
  43968. joint.physicsJoint.setMotorSpeed(speed);
  43969. if (maxForce) {
  43970. this.setLimit(joint, maxForce);
  43971. }
  43972. }
  43973. };
  43974. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  43975. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  43976. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  43977. };
  43978. CannonJSPlugin.prototype.dispose = function () {
  43979. //nothing to do, actually.
  43980. };
  43981. return CannonJSPlugin;
  43982. })();
  43983. BABYLON.CannonJSPlugin = CannonJSPlugin;
  43984. })(BABYLON || (BABYLON = {}));
  43985. var BABYLON;
  43986. (function (BABYLON) {
  43987. var OimoJSPlugin = (function () {
  43988. function OimoJSPlugin(iterations) {
  43989. this.name = "OimoJSPlugin";
  43990. this._tmpImpostorsArray = [];
  43991. this._tmpPositionVector = BABYLON.Vector3.Zero();
  43992. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  43993. this.world.clear();
  43994. //making sure no stats are calculated
  43995. this.world.isNoStat = true;
  43996. }
  43997. OimoJSPlugin.prototype.setGravity = function (gravity) {
  43998. this.world.gravity.copy(gravity);
  43999. };
  44000. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  44001. this.world.timeStep = timeStep;
  44002. };
  44003. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  44004. var _this = this;
  44005. impostors.forEach(function (impostor) {
  44006. impostor.beforeStep();
  44007. });
  44008. this.world.step();
  44009. impostors.forEach(function (impostor) {
  44010. impostor.afterStep();
  44011. //update the ordered impostors array
  44012. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44013. });
  44014. //check for collisions
  44015. var contact = this.world.contacts;
  44016. while (contact !== null) {
  44017. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  44018. contact = contact.next;
  44019. continue;
  44020. }
  44021. //is this body colliding with any other? get the impostor
  44022. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  44023. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  44024. if (!mainImpostor || !collidingImpostor) {
  44025. contact = contact.next;
  44026. continue;
  44027. }
  44028. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  44029. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  44030. contact = contact.next;
  44031. }
  44032. };
  44033. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44034. var mass = impostor.physicsBody.massInfo.mass;
  44035. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  44036. };
  44037. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44038. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  44039. this.applyImpulse(impostor, force, contactPoint);
  44040. };
  44041. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44042. var _this = this;
  44043. //parent-child relationship. Does this impostor has a parent impostor?
  44044. if (impostor.parent) {
  44045. if (impostor.physicsBody) {
  44046. this.removePhysicsBody(impostor);
  44047. //TODO is that needed?
  44048. impostor.forceUpdate();
  44049. }
  44050. return;
  44051. }
  44052. if (impostor.isBodyInitRequired()) {
  44053. var bodyConfig = {
  44054. name: impostor.uniqueId,
  44055. //Oimo must have mass, also for static objects.
  44056. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  44057. size: [],
  44058. type: [],
  44059. pos: [],
  44060. rot: [],
  44061. move: impostor.getParam("mass") !== 0,
  44062. //Supporting older versions of Oimo
  44063. world: this.world
  44064. };
  44065. var impostors = [impostor];
  44066. function addToArray(parent) {
  44067. if (!parent.getChildMeshes)
  44068. return;
  44069. parent.getChildMeshes().forEach(function (m) {
  44070. if (m.physicsImpostor) {
  44071. impostors.push(m.physicsImpostor);
  44072. m.physicsImpostor._init();
  44073. }
  44074. });
  44075. }
  44076. addToArray(impostor.object);
  44077. function checkWithEpsilon(value) {
  44078. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  44079. }
  44080. impostors.forEach(function (i) {
  44081. //get the correct bounding box
  44082. var oldQuaternion = i.object.rotationQuaternion;
  44083. var rot = new OIMO.Euler().setFromQuaternion({
  44084. x: impostor.object.rotationQuaternion.x,
  44085. y: impostor.object.rotationQuaternion.y,
  44086. z: impostor.object.rotationQuaternion.z,
  44087. s: impostor.object.rotationQuaternion.w
  44088. });
  44089. var extendSize = i.getObjectExtendSize();
  44090. if (i === impostor) {
  44091. var center = impostor.getObjectCenter();
  44092. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  44093. //Can also use Array.prototype.push.apply
  44094. bodyConfig.pos.push(center.x);
  44095. bodyConfig.pos.push(center.y);
  44096. bodyConfig.pos.push(center.z);
  44097. //tmp solution
  44098. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  44099. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  44100. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  44101. }
  44102. else {
  44103. bodyConfig.pos.push(i.object.position.x);
  44104. bodyConfig.pos.push(i.object.position.y);
  44105. bodyConfig.pos.push(i.object.position.z);
  44106. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  44107. bodyConfig.rot.push(0);
  44108. bodyConfig.rot.push(0);
  44109. bodyConfig.rot.push(0);
  44110. }
  44111. // register mesh
  44112. switch (i.type) {
  44113. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44114. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  44115. case BABYLON.PhysicsImpostor.SphereImpostor:
  44116. var radiusX = extendSize.x;
  44117. var radiusY = extendSize.y;
  44118. var radiusZ = extendSize.z;
  44119. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  44120. bodyConfig.type.push('sphere');
  44121. //due to the way oimo works with compounds, add 3 times
  44122. bodyConfig.size.push(size);
  44123. bodyConfig.size.push(size);
  44124. bodyConfig.size.push(size);
  44125. break;
  44126. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44127. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  44128. var sizeY = checkWithEpsilon(extendSize.y);
  44129. bodyConfig.type.push('cylinder');
  44130. bodyConfig.size.push(sizeX);
  44131. bodyConfig.size.push(sizeY);
  44132. //due to the way oimo works with compounds, add one more value.
  44133. bodyConfig.size.push(sizeY);
  44134. break;
  44135. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44136. case BABYLON.PhysicsImpostor.BoxImpostor:
  44137. default:
  44138. var sizeX = checkWithEpsilon(extendSize.x);
  44139. var sizeY = checkWithEpsilon(extendSize.y);
  44140. var sizeZ = checkWithEpsilon(extendSize.z);
  44141. bodyConfig.type.push('box');
  44142. bodyConfig.size.push(sizeX);
  44143. bodyConfig.size.push(sizeY);
  44144. bodyConfig.size.push(sizeZ);
  44145. break;
  44146. }
  44147. //actually not needed, but hey...
  44148. i.object.rotationQuaternion = oldQuaternion;
  44149. });
  44150. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  44151. }
  44152. else {
  44153. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  44154. }
  44155. impostor.setDeltaPosition(this._tmpPositionVector);
  44156. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  44157. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  44158. };
  44159. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44160. //impostor.physicsBody.dispose();
  44161. //Same as : (older oimo versions)
  44162. this.world.removeRigidBody(impostor.physicsBody);
  44163. };
  44164. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44165. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44166. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44167. if (!mainBody || !connectedBody) {
  44168. return;
  44169. }
  44170. var jointData = impostorJoint.joint.jointData;
  44171. var options = jointData.nativeParams || {};
  44172. var type;
  44173. var nativeJointData = {
  44174. body1: mainBody,
  44175. body2: connectedBody,
  44176. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  44177. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  44178. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  44179. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  44180. min: options.min,
  44181. max: options.max,
  44182. collision: options.collision || jointData.collision,
  44183. spring: options.spring,
  44184. //supporting older version of Oimo
  44185. world: this.world
  44186. };
  44187. switch (impostorJoint.joint.type) {
  44188. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44189. type = "jointBall";
  44190. break;
  44191. case BABYLON.PhysicsJoint.SpringJoint:
  44192. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  44193. var springData = jointData;
  44194. nativeJointData.min = springData.length || nativeJointData.min;
  44195. //Max should also be set, just make sure it is at least min
  44196. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  44197. case BABYLON.PhysicsJoint.DistanceJoint:
  44198. type = "jointDistance";
  44199. nativeJointData.max = jointData.maxDistance;
  44200. break;
  44201. case BABYLON.PhysicsJoint.PrismaticJoint:
  44202. type = "jointPrisme";
  44203. break;
  44204. case BABYLON.PhysicsJoint.SliderJoint:
  44205. type = "jointSlide";
  44206. break;
  44207. case BABYLON.PhysicsJoint.WheelJoint:
  44208. type = "jointWheel";
  44209. break;
  44210. case BABYLON.PhysicsJoint.HingeJoint:
  44211. default:
  44212. type = "jointHinge";
  44213. break;
  44214. }
  44215. nativeJointData.type = type;
  44216. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  44217. };
  44218. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44219. //Bug in Oimo prevents us from disposing a joint in the playground
  44220. //joint.joint.physicsJoint.dispose();
  44221. //So we will bruteforce it!
  44222. try {
  44223. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  44224. }
  44225. catch (e) {
  44226. BABYLON.Tools.Warn(e);
  44227. }
  44228. };
  44229. OimoJSPlugin.prototype.isSupported = function () {
  44230. return OIMO !== undefined;
  44231. };
  44232. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44233. if (!impostor.physicsBody.sleeping) {
  44234. //TODO check that
  44235. if (impostor.physicsBody.shapes.next) {
  44236. var parentShape = this._getLastShape(impostor.physicsBody);
  44237. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  44238. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  44239. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  44240. }
  44241. else {
  44242. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  44243. }
  44244. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  44245. }
  44246. };
  44247. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44248. var body = impostor.physicsBody;
  44249. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  44250. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  44251. body.syncShapes();
  44252. body.awake();
  44253. };
  44254. OimoJSPlugin.prototype._getLastShape = function (body) {
  44255. var lastShape = body.shapes;
  44256. while (lastShape.next) {
  44257. lastShape = lastShape.next;
  44258. }
  44259. return lastShape;
  44260. };
  44261. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44262. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  44263. };
  44264. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44265. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  44266. };
  44267. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44268. var v = impostor.physicsBody.linearVelocity;
  44269. if (!v)
  44270. return null;
  44271. return new BABYLON.Vector3(v.x, v.y, v.z);
  44272. };
  44273. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44274. var v = impostor.physicsBody.angularVelocity;
  44275. if (!v)
  44276. return null;
  44277. return new BABYLON.Vector3(v.x, v.y, v.z);
  44278. };
  44279. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44280. var staticBody = mass === 0;
  44281. //this will actually set the body's density and not its mass.
  44282. //But this is how oimo treats the mass variable.
  44283. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  44284. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  44285. };
  44286. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  44287. impostor.physicsBody.sleep();
  44288. };
  44289. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  44290. impostor.physicsBody.awake();
  44291. };
  44292. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44293. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  44294. if (minDistance !== void 0) {
  44295. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  44296. }
  44297. };
  44298. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44299. //TODO separate rotational and transational motors.
  44300. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44301. if (motor) {
  44302. motor.setMotor(speed, maxForce);
  44303. }
  44304. };
  44305. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  44306. //TODO separate rotational and transational motors.
  44307. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44308. if (motor) {
  44309. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  44310. }
  44311. };
  44312. OimoJSPlugin.prototype.dispose = function () {
  44313. this.world.clear();
  44314. };
  44315. return OimoJSPlugin;
  44316. })();
  44317. BABYLON.OimoJSPlugin = OimoJSPlugin;
  44318. })(BABYLON || (BABYLON = {}));
  44319. var BABYLON;
  44320. (function (BABYLON) {
  44321. var DisplayPassPostProcess = (function (_super) {
  44322. __extends(DisplayPassPostProcess, _super);
  44323. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44324. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  44325. }
  44326. return DisplayPassPostProcess;
  44327. })(BABYLON.PostProcess);
  44328. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  44329. })(BABYLON || (BABYLON = {}));
  44330. var BABYLON;
  44331. (function (BABYLON) {
  44332. var SimplificationSettings = (function () {
  44333. function SimplificationSettings(quality, distance, optimizeMesh) {
  44334. this.quality = quality;
  44335. this.distance = distance;
  44336. this.optimizeMesh = optimizeMesh;
  44337. }
  44338. return SimplificationSettings;
  44339. })();
  44340. BABYLON.SimplificationSettings = SimplificationSettings;
  44341. var SimplificationQueue = (function () {
  44342. function SimplificationQueue() {
  44343. this.running = false;
  44344. this._simplificationArray = [];
  44345. }
  44346. SimplificationQueue.prototype.addTask = function (task) {
  44347. this._simplificationArray.push(task);
  44348. };
  44349. SimplificationQueue.prototype.executeNext = function () {
  44350. var task = this._simplificationArray.pop();
  44351. if (task) {
  44352. this.running = true;
  44353. this.runSimplification(task);
  44354. }
  44355. else {
  44356. this.running = false;
  44357. }
  44358. };
  44359. SimplificationQueue.prototype.runSimplification = function (task) {
  44360. var _this = this;
  44361. if (task.parallelProcessing) {
  44362. //parallel simplifier
  44363. task.settings.forEach(function (setting) {
  44364. var simplifier = _this.getSimplifier(task);
  44365. simplifier.simplify(setting, function (newMesh) {
  44366. task.mesh.addLODLevel(setting.distance, newMesh);
  44367. newMesh.isVisible = true;
  44368. //check if it is the last
  44369. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  44370. //all done, run the success callback.
  44371. task.successCallback();
  44372. }
  44373. _this.executeNext();
  44374. });
  44375. });
  44376. }
  44377. else {
  44378. //single simplifier.
  44379. var simplifier = this.getSimplifier(task);
  44380. var runDecimation = function (setting, callback) {
  44381. simplifier.simplify(setting, function (newMesh) {
  44382. task.mesh.addLODLevel(setting.distance, newMesh);
  44383. newMesh.isVisible = true;
  44384. //run the next quality level
  44385. callback();
  44386. });
  44387. };
  44388. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  44389. runDecimation(task.settings[loop.index], function () {
  44390. loop.executeNext();
  44391. });
  44392. }, function () {
  44393. //execution ended, run the success callback.
  44394. if (task.successCallback) {
  44395. task.successCallback();
  44396. }
  44397. _this.executeNext();
  44398. });
  44399. }
  44400. };
  44401. SimplificationQueue.prototype.getSimplifier = function (task) {
  44402. switch (task.simplificationType) {
  44403. case SimplificationType.QUADRATIC:
  44404. default:
  44405. return new QuadraticErrorSimplification(task.mesh);
  44406. }
  44407. };
  44408. return SimplificationQueue;
  44409. })();
  44410. BABYLON.SimplificationQueue = SimplificationQueue;
  44411. /**
  44412. * The implemented types of simplification.
  44413. * At the moment only Quadratic Error Decimation is implemented.
  44414. */
  44415. (function (SimplificationType) {
  44416. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  44417. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  44418. var SimplificationType = BABYLON.SimplificationType;
  44419. var DecimationTriangle = (function () {
  44420. function DecimationTriangle(vertices) {
  44421. this.vertices = vertices;
  44422. this.error = new Array(4);
  44423. this.deleted = false;
  44424. this.isDirty = false;
  44425. this.deletePending = false;
  44426. this.borderFactor = 0;
  44427. }
  44428. return DecimationTriangle;
  44429. })();
  44430. BABYLON.DecimationTriangle = DecimationTriangle;
  44431. var DecimationVertex = (function () {
  44432. function DecimationVertex(position, id) {
  44433. this.position = position;
  44434. this.id = id;
  44435. this.isBorder = true;
  44436. this.q = new QuadraticMatrix();
  44437. this.triangleCount = 0;
  44438. this.triangleStart = 0;
  44439. this.originalOffsets = [];
  44440. }
  44441. DecimationVertex.prototype.updatePosition = function (newPosition) {
  44442. this.position.copyFrom(newPosition);
  44443. };
  44444. return DecimationVertex;
  44445. })();
  44446. BABYLON.DecimationVertex = DecimationVertex;
  44447. var QuadraticMatrix = (function () {
  44448. function QuadraticMatrix(data) {
  44449. this.data = new Array(10);
  44450. for (var i = 0; i < 10; ++i) {
  44451. if (data && data[i]) {
  44452. this.data[i] = data[i];
  44453. }
  44454. else {
  44455. this.data[i] = 0;
  44456. }
  44457. }
  44458. }
  44459. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  44460. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  44461. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  44462. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  44463. return det;
  44464. };
  44465. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  44466. for (var i = 0; i < 10; ++i) {
  44467. this.data[i] += matrix.data[i];
  44468. }
  44469. };
  44470. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  44471. for (var i = 0; i < 10; ++i) {
  44472. this.data[i] += data[i];
  44473. }
  44474. };
  44475. QuadraticMatrix.prototype.add = function (matrix) {
  44476. var m = new QuadraticMatrix();
  44477. for (var i = 0; i < 10; ++i) {
  44478. m.data[i] = this.data[i] + matrix.data[i];
  44479. }
  44480. return m;
  44481. };
  44482. QuadraticMatrix.FromData = function (a, b, c, d) {
  44483. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  44484. };
  44485. //returning an array to avoid garbage collection
  44486. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  44487. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  44488. };
  44489. return QuadraticMatrix;
  44490. })();
  44491. BABYLON.QuadraticMatrix = QuadraticMatrix;
  44492. var Reference = (function () {
  44493. function Reference(vertexId, triangleId) {
  44494. this.vertexId = vertexId;
  44495. this.triangleId = triangleId;
  44496. }
  44497. return Reference;
  44498. })();
  44499. BABYLON.Reference = Reference;
  44500. /**
  44501. * An implementation of the Quadratic Error simplification algorithm.
  44502. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  44503. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  44504. * @author RaananW
  44505. */
  44506. var QuadraticErrorSimplification = (function () {
  44507. function QuadraticErrorSimplification(_mesh) {
  44508. this._mesh = _mesh;
  44509. this.initialized = false;
  44510. this.syncIterations = 5000;
  44511. this.aggressiveness = 7;
  44512. this.decimationIterations = 100;
  44513. this.boundingBoxEpsilon = BABYLON.Epsilon;
  44514. }
  44515. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  44516. var _this = this;
  44517. this.initDecimatedMesh();
  44518. //iterating through the submeshes array, one after the other.
  44519. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  44520. _this.initWithMesh(loop.index, function () {
  44521. _this.runDecimation(settings, loop.index, function () {
  44522. loop.executeNext();
  44523. });
  44524. }, settings.optimizeMesh);
  44525. }, function () {
  44526. setTimeout(function () {
  44527. successCallback(_this._reconstructedMesh);
  44528. }, 0);
  44529. });
  44530. };
  44531. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  44532. var _this = this;
  44533. var gCount = 0;
  44534. triangle.vertices.forEach(function (vertex) {
  44535. var count = 0;
  44536. var vPos = vertex.position;
  44537. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  44538. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  44539. ++count;
  44540. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  44541. ++count;
  44542. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  44543. ++count;
  44544. if (count > 1) {
  44545. ++gCount;
  44546. }
  44547. ;
  44548. });
  44549. if (gCount > 1) {
  44550. console.log(triangle, gCount);
  44551. }
  44552. return gCount > 1;
  44553. };
  44554. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  44555. var _this = this;
  44556. var targetCount = ~~(this.triangles.length * settings.quality);
  44557. var deletedTriangles = 0;
  44558. var triangleCount = this.triangles.length;
  44559. var iterationFunction = function (iteration, callback) {
  44560. setTimeout(function () {
  44561. if (iteration % 5 === 0) {
  44562. _this.updateMesh(iteration === 0);
  44563. }
  44564. for (var i = 0; i < _this.triangles.length; ++i) {
  44565. _this.triangles[i].isDirty = false;
  44566. }
  44567. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  44568. var trianglesIterator = function (i) {
  44569. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  44570. var t = _this.triangles[tIdx];
  44571. if (!t)
  44572. return;
  44573. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  44574. return;
  44575. }
  44576. for (var j = 0; j < 3; ++j) {
  44577. if (t.error[j] < threshold) {
  44578. var deleted0 = [];
  44579. var deleted1 = [];
  44580. var v0 = t.vertices[j];
  44581. var v1 = t.vertices[(j + 1) % 3];
  44582. if (v0.isBorder || v1.isBorder)
  44583. continue;
  44584. var p = BABYLON.Vector3.Zero();
  44585. var n = BABYLON.Vector3.Zero();
  44586. var uv = BABYLON.Vector2.Zero();
  44587. var color = new BABYLON.Color4(0, 0, 0, 1);
  44588. _this.calculateError(v0, v1, p, n, uv, color);
  44589. var delTr = [];
  44590. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  44591. continue;
  44592. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  44593. continue;
  44594. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  44595. continue;
  44596. var uniqueArray = [];
  44597. delTr.forEach(function (deletedT) {
  44598. if (uniqueArray.indexOf(deletedT) === -1) {
  44599. deletedT.deletePending = true;
  44600. uniqueArray.push(deletedT);
  44601. }
  44602. });
  44603. if (uniqueArray.length % 2 !== 0) {
  44604. continue;
  44605. }
  44606. v0.q = v1.q.add(v0.q);
  44607. v0.updatePosition(p);
  44608. var tStart = _this.references.length;
  44609. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  44610. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  44611. var tCount = _this.references.length - tStart;
  44612. if (tCount <= v0.triangleCount) {
  44613. if (tCount) {
  44614. for (var c = 0; c < tCount; c++) {
  44615. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  44616. }
  44617. }
  44618. }
  44619. else {
  44620. v0.triangleStart = tStart;
  44621. }
  44622. v0.triangleCount = tCount;
  44623. break;
  44624. }
  44625. }
  44626. };
  44627. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  44628. }, 0);
  44629. };
  44630. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  44631. if (triangleCount - deletedTriangles <= targetCount)
  44632. loop.breakLoop();
  44633. else {
  44634. iterationFunction(loop.index, function () {
  44635. loop.executeNext();
  44636. });
  44637. }
  44638. }, function () {
  44639. setTimeout(function () {
  44640. //reconstruct this part of the mesh
  44641. _this.reconstructMesh(submeshIndex);
  44642. successCallback();
  44643. }, 0);
  44644. });
  44645. };
  44646. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  44647. var _this = this;
  44648. this.vertices = [];
  44649. this.triangles = [];
  44650. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44651. var indices = this._mesh.getIndices();
  44652. var submesh = this._mesh.subMeshes[submeshIndex];
  44653. var findInVertices = function (positionToSearch) {
  44654. if (optimizeMesh) {
  44655. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  44656. if (_this.vertices[ii].position.equals(positionToSearch)) {
  44657. return _this.vertices[ii];
  44658. }
  44659. }
  44660. }
  44661. return null;
  44662. };
  44663. var vertexReferences = [];
  44664. var vertexInit = function (i) {
  44665. var offset = i + submesh.verticesStart;
  44666. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  44667. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  44668. vertex.originalOffsets.push(offset);
  44669. if (vertex.id === _this.vertices.length) {
  44670. _this.vertices.push(vertex);
  44671. }
  44672. vertexReferences.push(vertex.id);
  44673. };
  44674. //var totalVertices = mesh.getTotalVertices();
  44675. var totalVertices = submesh.verticesCount;
  44676. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  44677. var indicesInit = function (i) {
  44678. var offset = (submesh.indexStart / 3) + i;
  44679. var pos = (offset * 3);
  44680. var i0 = indices[pos + 0];
  44681. var i1 = indices[pos + 1];
  44682. var i2 = indices[pos + 2];
  44683. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  44684. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  44685. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  44686. var triangle = new DecimationTriangle([v0, v1, v2]);
  44687. triangle.originalOffset = pos;
  44688. _this.triangles.push(triangle);
  44689. };
  44690. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  44691. _this.init(callback);
  44692. });
  44693. });
  44694. };
  44695. QuadraticErrorSimplification.prototype.init = function (callback) {
  44696. var _this = this;
  44697. var triangleInit1 = function (i) {
  44698. var t = _this.triangles[i];
  44699. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  44700. for (var j = 0; j < 3; j++) {
  44701. 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))));
  44702. }
  44703. };
  44704. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  44705. var triangleInit2 = function (i) {
  44706. var t = _this.triangles[i];
  44707. for (var j = 0; j < 3; ++j) {
  44708. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  44709. }
  44710. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  44711. };
  44712. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  44713. _this.initialized = true;
  44714. callback();
  44715. });
  44716. });
  44717. };
  44718. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  44719. var newTriangles = [];
  44720. var i;
  44721. for (i = 0; i < this.vertices.length; ++i) {
  44722. this.vertices[i].triangleCount = 0;
  44723. }
  44724. var t;
  44725. var j;
  44726. for (i = 0; i < this.triangles.length; ++i) {
  44727. if (!this.triangles[i].deleted) {
  44728. t = this.triangles[i];
  44729. for (j = 0; j < 3; ++j) {
  44730. t.vertices[j].triangleCount = 1;
  44731. }
  44732. newTriangles.push(t);
  44733. }
  44734. }
  44735. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  44736. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  44737. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  44738. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  44739. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44740. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44741. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44742. var vertexCount = 0;
  44743. for (i = 0; i < this.vertices.length; ++i) {
  44744. var vertex = this.vertices[i];
  44745. vertex.id = vertexCount;
  44746. if (vertex.triangleCount) {
  44747. vertex.originalOffsets.forEach(function (originalOffset) {
  44748. newPositionData.push(vertex.position.x);
  44749. newPositionData.push(vertex.position.y);
  44750. newPositionData.push(vertex.position.z);
  44751. newNormalData.push(normalData[originalOffset * 3]);
  44752. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  44753. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  44754. if (uvs && uvs.length) {
  44755. newUVsData.push(uvs[(originalOffset * 2)]);
  44756. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  44757. }
  44758. else if (colorsData && colorsData.length) {
  44759. newColorsData.push(colorsData[(originalOffset * 4)]);
  44760. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  44761. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  44762. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  44763. }
  44764. ++vertexCount;
  44765. });
  44766. }
  44767. }
  44768. var startingIndex = this._reconstructedMesh.getTotalIndices();
  44769. var startingVertex = this._reconstructedMesh.getTotalVertices();
  44770. var submeshesArray = this._reconstructedMesh.subMeshes;
  44771. this._reconstructedMesh.subMeshes = [];
  44772. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  44773. var originalIndices = this._mesh.getIndices();
  44774. for (i = 0; i < newTriangles.length; ++i) {
  44775. t = newTriangles[i]; //now get the new referencing point for each vertex
  44776. [0, 1, 2].forEach(function (idx) {
  44777. var id = originalIndices[t.originalOffset + idx];
  44778. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  44779. if (offset < 0)
  44780. offset = 0;
  44781. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  44782. });
  44783. }
  44784. //overwriting the old vertex buffers and indices.
  44785. this._reconstructedMesh.setIndices(newIndicesArray);
  44786. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  44787. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  44788. if (newUVsData.length > 0)
  44789. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  44790. if (newColorsData.length > 0)
  44791. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  44792. //create submesh
  44793. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  44794. if (submeshIndex > 0) {
  44795. this._reconstructedMesh.subMeshes = [];
  44796. submeshesArray.forEach(function (submesh) {
  44797. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  44798. });
  44799. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  44800. }
  44801. };
  44802. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  44803. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  44804. this._reconstructedMesh.material = this._mesh.material;
  44805. this._reconstructedMesh.parent = this._mesh.parent;
  44806. this._reconstructedMesh.isVisible = false;
  44807. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  44808. };
  44809. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  44810. for (var i = 0; i < vertex1.triangleCount; ++i) {
  44811. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  44812. if (t.deleted)
  44813. continue;
  44814. var s = this.references[vertex1.triangleStart + i].vertexId;
  44815. var v1 = t.vertices[(s + 1) % 3];
  44816. var v2 = t.vertices[(s + 2) % 3];
  44817. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  44818. deletedArray[i] = true;
  44819. delTr.push(t);
  44820. continue;
  44821. }
  44822. var d1 = v1.position.subtract(point);
  44823. d1 = d1.normalize();
  44824. var d2 = v2.position.subtract(point);
  44825. d2 = d2.normalize();
  44826. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  44827. return true;
  44828. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  44829. deletedArray[i] = false;
  44830. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  44831. return true;
  44832. }
  44833. return false;
  44834. };
  44835. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  44836. var newDeleted = deletedTriangles;
  44837. for (var i = 0; i < vertex.triangleCount; ++i) {
  44838. var ref = this.references[vertex.triangleStart + i];
  44839. var t = this.triangles[ref.triangleId];
  44840. if (t.deleted)
  44841. continue;
  44842. if (deletedArray[i] && t.deletePending) {
  44843. t.deleted = true;
  44844. newDeleted++;
  44845. continue;
  44846. }
  44847. t.vertices[ref.vertexId] = origVertex;
  44848. t.isDirty = true;
  44849. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  44850. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  44851. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  44852. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  44853. this.references.push(ref);
  44854. }
  44855. return newDeleted;
  44856. };
  44857. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  44858. for (var i = 0; i < this.vertices.length; ++i) {
  44859. var vCount = [];
  44860. var vId = [];
  44861. var v = this.vertices[i];
  44862. var j;
  44863. for (j = 0; j < v.triangleCount; ++j) {
  44864. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  44865. for (var ii = 0; ii < 3; ii++) {
  44866. var ofs = 0;
  44867. var vv = triangle.vertices[ii];
  44868. while (ofs < vCount.length) {
  44869. if (vId[ofs] === vv.id)
  44870. break;
  44871. ++ofs;
  44872. }
  44873. if (ofs === vCount.length) {
  44874. vCount.push(1);
  44875. vId.push(vv.id);
  44876. }
  44877. else {
  44878. vCount[ofs]++;
  44879. }
  44880. }
  44881. }
  44882. for (j = 0; j < vCount.length; ++j) {
  44883. if (vCount[j] === 1) {
  44884. this.vertices[vId[j]].isBorder = true;
  44885. }
  44886. else {
  44887. this.vertices[vId[j]].isBorder = false;
  44888. }
  44889. }
  44890. }
  44891. };
  44892. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  44893. if (identifyBorders === void 0) { identifyBorders = false; }
  44894. var i;
  44895. if (!identifyBorders) {
  44896. var newTrianglesVector = [];
  44897. for (i = 0; i < this.triangles.length; ++i) {
  44898. if (!this.triangles[i].deleted) {
  44899. newTrianglesVector.push(this.triangles[i]);
  44900. }
  44901. }
  44902. this.triangles = newTrianglesVector;
  44903. }
  44904. for (i = 0; i < this.vertices.length; ++i) {
  44905. this.vertices[i].triangleCount = 0;
  44906. this.vertices[i].triangleStart = 0;
  44907. }
  44908. var t;
  44909. var j;
  44910. var v;
  44911. for (i = 0; i < this.triangles.length; ++i) {
  44912. t = this.triangles[i];
  44913. for (j = 0; j < 3; ++j) {
  44914. v = t.vertices[j];
  44915. v.triangleCount++;
  44916. }
  44917. }
  44918. var tStart = 0;
  44919. for (i = 0; i < this.vertices.length; ++i) {
  44920. this.vertices[i].triangleStart = tStart;
  44921. tStart += this.vertices[i].triangleCount;
  44922. this.vertices[i].triangleCount = 0;
  44923. }
  44924. var newReferences = new Array(this.triangles.length * 3);
  44925. for (i = 0; i < this.triangles.length; ++i) {
  44926. t = this.triangles[i];
  44927. for (j = 0; j < 3; ++j) {
  44928. v = t.vertices[j];
  44929. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  44930. v.triangleCount++;
  44931. }
  44932. }
  44933. this.references = newReferences;
  44934. if (identifyBorders) {
  44935. this.identifyBorder();
  44936. }
  44937. };
  44938. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  44939. var x = point.x;
  44940. var y = point.y;
  44941. var z = point.z;
  44942. 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
  44943. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  44944. };
  44945. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  44946. var q = vertex1.q.add(vertex2.q);
  44947. var border = vertex1.isBorder && vertex2.isBorder;
  44948. var error = 0;
  44949. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  44950. if (qDet !== 0 && !border) {
  44951. if (!pointResult) {
  44952. pointResult = BABYLON.Vector3.Zero();
  44953. }
  44954. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  44955. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  44956. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  44957. error = this.vertexError(q, pointResult);
  44958. }
  44959. else {
  44960. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  44961. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  44962. var error1 = this.vertexError(q, vertex1.position);
  44963. var error2 = this.vertexError(q, vertex2.position);
  44964. var error3 = this.vertexError(q, p3);
  44965. error = Math.min(error1, error2, error3);
  44966. if (error === error1) {
  44967. if (pointResult) {
  44968. pointResult.copyFrom(vertex1.position);
  44969. }
  44970. }
  44971. else if (error === error2) {
  44972. if (pointResult) {
  44973. pointResult.copyFrom(vertex2.position);
  44974. }
  44975. }
  44976. else {
  44977. if (pointResult) {
  44978. pointResult.copyFrom(p3);
  44979. }
  44980. }
  44981. }
  44982. return error;
  44983. };
  44984. return QuadraticErrorSimplification;
  44985. })();
  44986. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  44987. })(BABYLON || (BABYLON = {}));
  44988. var BABYLON;
  44989. (function (BABYLON) {
  44990. var serializedGeometries = [];
  44991. var serializeGeometry = function (geometry, serializationGeometries) {
  44992. if (serializedGeometries[geometry.id]) {
  44993. return;
  44994. }
  44995. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  44996. serializationGeometries.boxes.push(geometry.serialize());
  44997. }
  44998. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  44999. serializationGeometries.spheres.push(geometry.serialize());
  45000. }
  45001. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  45002. serializationGeometries.cylinders.push(geometry.serialize());
  45003. }
  45004. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  45005. serializationGeometries.toruses.push(geometry.serialize());
  45006. }
  45007. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  45008. serializationGeometries.grounds.push(geometry.serialize());
  45009. }
  45010. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  45011. serializationGeometries.planes.push(geometry.serialize());
  45012. }
  45013. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  45014. serializationGeometries.torusKnots.push(geometry.serialize());
  45015. }
  45016. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  45017. throw new Error("Unknown primitive type");
  45018. }
  45019. else {
  45020. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  45021. }
  45022. serializedGeometries[geometry.id] = true;
  45023. };
  45024. var serializeMesh = function (mesh, serializationScene) {
  45025. var serializationObject = {};
  45026. serializationObject.name = mesh.name;
  45027. serializationObject.id = mesh.id;
  45028. if (BABYLON.Tags.HasTags(mesh)) {
  45029. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  45030. }
  45031. serializationObject.position = mesh.position.asArray();
  45032. if (mesh.rotationQuaternion) {
  45033. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  45034. }
  45035. else if (mesh.rotation) {
  45036. serializationObject.rotation = mesh.rotation.asArray();
  45037. }
  45038. serializationObject.scaling = mesh.scaling.asArray();
  45039. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  45040. serializationObject.isEnabled = mesh.isEnabled();
  45041. serializationObject.isVisible = mesh.isVisible;
  45042. serializationObject.infiniteDistance = mesh.infiniteDistance;
  45043. serializationObject.pickable = mesh.isPickable;
  45044. serializationObject.receiveShadows = mesh.receiveShadows;
  45045. serializationObject.billboardMode = mesh.billboardMode;
  45046. serializationObject.visibility = mesh.visibility;
  45047. serializationObject.checkCollisions = mesh.checkCollisions;
  45048. // Parent
  45049. if (mesh.parent) {
  45050. serializationObject.parentId = mesh.parent.id;
  45051. }
  45052. // Geometry
  45053. var geometry = mesh._geometry;
  45054. if (geometry) {
  45055. var geometryId = geometry.id;
  45056. serializationObject.geometryId = geometryId;
  45057. if (!mesh.getScene().getGeometryByID(geometryId)) {
  45058. // 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
  45059. serializeGeometry(geometry, serializationScene.geometries);
  45060. }
  45061. // SubMeshes
  45062. serializationObject.subMeshes = [];
  45063. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45064. var subMesh = mesh.subMeshes[subIndex];
  45065. serializationObject.subMeshes.push({
  45066. materialIndex: subMesh.materialIndex,
  45067. verticesStart: subMesh.verticesStart,
  45068. verticesCount: subMesh.verticesCount,
  45069. indexStart: subMesh.indexStart,
  45070. indexCount: subMesh.indexCount
  45071. });
  45072. }
  45073. }
  45074. // Material
  45075. if (mesh.material) {
  45076. serializationObject.materialId = mesh.material.id;
  45077. }
  45078. else {
  45079. mesh.material = null;
  45080. }
  45081. // Skeleton
  45082. if (mesh.skeleton) {
  45083. serializationObject.skeletonId = mesh.skeleton.id;
  45084. }
  45085. // Physics
  45086. //TODO implement correct serialization for physics impostors.
  45087. if (mesh.getPhysicsImpostor()) {
  45088. serializationObject.physicsMass = mesh.getPhysicsMass();
  45089. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  45090. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  45091. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  45092. }
  45093. // Instances
  45094. serializationObject.instances = [];
  45095. for (var index = 0; index < mesh.instances.length; index++) {
  45096. var instance = mesh.instances[index];
  45097. var serializationInstance = {
  45098. name: instance.name,
  45099. position: instance.position.asArray(),
  45100. scaling: instance.scaling.asArray()
  45101. };
  45102. if (instance.rotationQuaternion) {
  45103. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  45104. }
  45105. else if (instance.rotation) {
  45106. serializationInstance.rotation = instance.rotation.asArray();
  45107. }
  45108. serializationObject.instances.push(serializationInstance);
  45109. // Animations
  45110. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  45111. serializationInstance.ranges = instance.serializeAnimationRanges();
  45112. }
  45113. // Animations
  45114. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  45115. serializationObject.ranges = mesh.serializeAnimationRanges();
  45116. // Layer mask
  45117. serializationObject.layerMask = mesh.layerMask;
  45118. // Action Manager
  45119. if (mesh.actionManager) {
  45120. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  45121. }
  45122. return serializationObject;
  45123. };
  45124. var finalizeSingleMesh = function (mesh, serializationObject) {
  45125. //only works if the mesh is already loaded
  45126. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45127. //serialize material
  45128. if (mesh.material) {
  45129. if (mesh.material instanceof BABYLON.StandardMaterial) {
  45130. serializationObject.materials = serializationObject.materials || [];
  45131. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45132. serializationObject.materials.push(mesh.material.serialize());
  45133. }
  45134. }
  45135. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  45136. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  45137. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45138. serializationObject.multiMaterials.push(mesh.material.serialize());
  45139. }
  45140. }
  45141. }
  45142. //serialize geometry
  45143. var geometry = mesh._geometry;
  45144. if (geometry) {
  45145. if (!serializationObject.geometries) {
  45146. serializationObject.geometries = {};
  45147. serializationObject.geometries.boxes = [];
  45148. serializationObject.geometries.spheres = [];
  45149. serializationObject.geometries.cylinders = [];
  45150. serializationObject.geometries.toruses = [];
  45151. serializationObject.geometries.grounds = [];
  45152. serializationObject.geometries.planes = [];
  45153. serializationObject.geometries.torusKnots = [];
  45154. serializationObject.geometries.vertexData = [];
  45155. }
  45156. serializeGeometry(geometry, serializationObject.geometries);
  45157. }
  45158. // Skeletons
  45159. if (mesh.skeleton) {
  45160. serializationObject.skeletons = serializationObject.skeletons || [];
  45161. serializationObject.skeletons.push(mesh.skeleton.serialize());
  45162. }
  45163. //serialize the actual mesh
  45164. serializationObject.meshes = serializationObject.meshes || [];
  45165. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45166. }
  45167. };
  45168. var SceneSerializer = (function () {
  45169. function SceneSerializer() {
  45170. }
  45171. SceneSerializer.ClearCache = function () {
  45172. serializedGeometries = [];
  45173. };
  45174. SceneSerializer.Serialize = function (scene) {
  45175. var serializationObject = {};
  45176. // Scene
  45177. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  45178. serializationObject.autoClear = scene.autoClear;
  45179. serializationObject.clearColor = scene.clearColor.asArray();
  45180. serializationObject.ambientColor = scene.ambientColor.asArray();
  45181. serializationObject.gravity = scene.gravity.asArray();
  45182. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  45183. serializationObject.workerCollisions = scene.workerCollisions;
  45184. // Fog
  45185. if (scene.fogMode && scene.fogMode !== 0) {
  45186. serializationObject.fogMode = scene.fogMode;
  45187. serializationObject.fogColor = scene.fogColor.asArray();
  45188. serializationObject.fogStart = scene.fogStart;
  45189. serializationObject.fogEnd = scene.fogEnd;
  45190. serializationObject.fogDensity = scene.fogDensity;
  45191. }
  45192. //Physics
  45193. if (scene.isPhysicsEnabled()) {
  45194. serializationObject.physicsEnabled = true;
  45195. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  45196. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  45197. }
  45198. // Lights
  45199. serializationObject.lights = [];
  45200. var index;
  45201. var light;
  45202. for (index = 0; index < scene.lights.length; index++) {
  45203. light = scene.lights[index];
  45204. serializationObject.lights.push(light.serialize());
  45205. }
  45206. // Cameras
  45207. serializationObject.cameras = [];
  45208. for (index = 0; index < scene.cameras.length; index++) {
  45209. var camera = scene.cameras[index];
  45210. serializationObject.cameras.push(camera.serialize());
  45211. }
  45212. if (scene.activeCamera) {
  45213. serializationObject.activeCameraID = scene.activeCamera.id;
  45214. }
  45215. // Animations
  45216. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  45217. // Materials
  45218. serializationObject.materials = [];
  45219. serializationObject.multiMaterials = [];
  45220. var material;
  45221. for (index = 0; index < scene.materials.length; index++) {
  45222. material = scene.materials[index];
  45223. serializationObject.materials.push(material.serialize());
  45224. }
  45225. // MultiMaterials
  45226. serializationObject.multiMaterials = [];
  45227. for (index = 0; index < scene.multiMaterials.length; index++) {
  45228. var multiMaterial = scene.multiMaterials[index];
  45229. serializationObject.multiMaterials.push(multiMaterial.serialize());
  45230. }
  45231. // Skeletons
  45232. serializationObject.skeletons = [];
  45233. for (index = 0; index < scene.skeletons.length; index++) {
  45234. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  45235. }
  45236. // Geometries
  45237. serializationObject.geometries = {};
  45238. serializationObject.geometries.boxes = [];
  45239. serializationObject.geometries.spheres = [];
  45240. serializationObject.geometries.cylinders = [];
  45241. serializationObject.geometries.toruses = [];
  45242. serializationObject.geometries.grounds = [];
  45243. serializationObject.geometries.planes = [];
  45244. serializationObject.geometries.torusKnots = [];
  45245. serializationObject.geometries.vertexData = [];
  45246. serializedGeometries = [];
  45247. var geometries = scene.getGeometries();
  45248. for (index = 0; index < geometries.length; index++) {
  45249. var geometry = geometries[index];
  45250. if (geometry.isReady()) {
  45251. serializeGeometry(geometry, serializationObject.geometries);
  45252. }
  45253. }
  45254. // Meshes
  45255. serializationObject.meshes = [];
  45256. for (index = 0; index < scene.meshes.length; index++) {
  45257. var abstractMesh = scene.meshes[index];
  45258. if (abstractMesh instanceof BABYLON.Mesh) {
  45259. var mesh = abstractMesh;
  45260. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45261. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45262. }
  45263. }
  45264. }
  45265. // Particles Systems
  45266. serializationObject.particleSystems = [];
  45267. for (index = 0; index < scene.particleSystems.length; index++) {
  45268. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  45269. }
  45270. // Lens flares
  45271. serializationObject.lensFlareSystems = [];
  45272. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  45273. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  45274. }
  45275. // Shadows
  45276. serializationObject.shadowGenerators = [];
  45277. for (index = 0; index < scene.lights.length; index++) {
  45278. light = scene.lights[index];
  45279. if (light.getShadowGenerator()) {
  45280. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  45281. }
  45282. }
  45283. // Action Manager
  45284. if (scene.actionManager) {
  45285. serializationObject.actions = scene.actionManager.serialize("scene");
  45286. }
  45287. return serializationObject;
  45288. };
  45289. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  45290. if (withParents === void 0) { withParents = false; }
  45291. if (withChildren === void 0) { withChildren = false; }
  45292. var serializationObject = {};
  45293. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  45294. if (withParents || withChildren) {
  45295. //deliberate for loop! not for each, appended should be processed as well.
  45296. for (var i = 0; i < toSerialize.length; ++i) {
  45297. if (withChildren) {
  45298. toSerialize[i].getDescendants().forEach(function (node) {
  45299. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  45300. toSerialize.push(node);
  45301. }
  45302. });
  45303. }
  45304. //make sure the array doesn't contain the object already
  45305. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  45306. toSerialize.push(toSerialize[i].parent);
  45307. }
  45308. }
  45309. }
  45310. toSerialize.forEach(function (mesh) {
  45311. finalizeSingleMesh(mesh, serializationObject);
  45312. });
  45313. return serializationObject;
  45314. };
  45315. return SceneSerializer;
  45316. })();
  45317. BABYLON.SceneSerializer = SceneSerializer;
  45318. })(BABYLON || (BABYLON = {}));
  45319. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  45320. // Huge respect for a such great lib.
  45321. // Earcut license:
  45322. // Copyright (c) 2016, Mapbox
  45323. //
  45324. // Permission to use, copy, modify, and/or distribute this software for any purpose
  45325. // with or without fee is hereby granted, provided that the above copyright notice
  45326. // and this permission notice appear in all copies.
  45327. //
  45328. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  45329. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  45330. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  45331. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  45332. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  45333. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  45334. // THIS SOFTWARE.
  45335. var Earcut;
  45336. (function (Earcut) {
  45337. /**
  45338. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  45339. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  45340. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  45341. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  45342. */
  45343. function earcut(data, holeIndices, dim) {
  45344. dim = dim || 2;
  45345. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  45346. if (!outerNode)
  45347. return triangles;
  45348. var minX, minY, maxX, maxY, x, y, size;
  45349. if (hasHoles)
  45350. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  45351. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  45352. if (data.length > 80 * dim) {
  45353. minX = maxX = data[0];
  45354. minY = maxY = data[1];
  45355. for (var i = dim; i < outerLen; i += dim) {
  45356. x = data[i];
  45357. y = data[i + 1];
  45358. if (x < minX)
  45359. minX = x;
  45360. if (y < minY)
  45361. minY = y;
  45362. if (x > maxX)
  45363. maxX = x;
  45364. if (y > maxY)
  45365. maxY = y;
  45366. }
  45367. // minX, minY and size are later used to transform coords into integers for z-order calculation
  45368. size = Math.max(maxX - minX, maxY - minY);
  45369. }
  45370. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  45371. return triangles;
  45372. }
  45373. Earcut.earcut = earcut;
  45374. // create a circular doubly linked list from polygon points in the specified winding order
  45375. function linkedList(data, start, end, dim, clockwise) {
  45376. var i, last;
  45377. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  45378. for (i = start; i < end; i += dim)
  45379. last = insertNode(i, data[i], data[i + 1], last);
  45380. }
  45381. else {
  45382. for (i = end - dim; i >= start; i -= dim)
  45383. last = insertNode(i, data[i], data[i + 1], last);
  45384. }
  45385. if (last && equals(last, last.next)) {
  45386. removeNode(last);
  45387. last = last.next;
  45388. }
  45389. return last;
  45390. }
  45391. // eliminate colinear or duplicate points
  45392. function filterPoints(start, end) {
  45393. if (!start)
  45394. return start;
  45395. if (!end)
  45396. end = start;
  45397. var p = start, again;
  45398. do {
  45399. again = false;
  45400. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  45401. removeNode(p);
  45402. p = end = p.prev;
  45403. if (p === p.next)
  45404. return null;
  45405. again = true;
  45406. }
  45407. else {
  45408. p = p.next;
  45409. }
  45410. } while (again || p !== end);
  45411. return end;
  45412. }
  45413. // main ear slicing loop which triangulates a polygon (given as a linked list)
  45414. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  45415. if (!ear)
  45416. return;
  45417. // interlink polygon nodes in z-order
  45418. if (!pass && size)
  45419. indexCurve(ear, minX, minY, size);
  45420. var stop = ear, prev, next;
  45421. // iterate through ears, slicing them one by one
  45422. while (ear.prev !== ear.next) {
  45423. prev = ear.prev;
  45424. next = ear.next;
  45425. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  45426. // cut off the triangle
  45427. triangles.push(prev.i / dim);
  45428. triangles.push(ear.i / dim);
  45429. triangles.push(next.i / dim);
  45430. removeNode(ear);
  45431. // skipping the next vertice leads to less sliver triangles
  45432. ear = next.next;
  45433. stop = next.next;
  45434. continue;
  45435. }
  45436. ear = next;
  45437. // if we looped through the whole remaining polygon and can't find any more ears
  45438. if (ear === stop) {
  45439. // try filtering points and slicing again
  45440. if (!pass) {
  45441. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  45442. }
  45443. else if (pass === 1) {
  45444. ear = cureLocalIntersections(ear, triangles, dim);
  45445. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  45446. }
  45447. else if (pass === 2) {
  45448. splitEarcut(ear, triangles, dim, minX, minY, size);
  45449. }
  45450. break;
  45451. }
  45452. }
  45453. }
  45454. // check whether a polygon node forms a valid ear with adjacent nodes
  45455. function isEar(ear) {
  45456. var a = ear.prev, b = ear, c = ear.next;
  45457. if (area(a, b, c) >= 0)
  45458. return false; // reflex, can't be an ear
  45459. // now make sure we don't have other points inside the potential ear
  45460. var p = ear.next.next;
  45461. while (p !== ear.prev) {
  45462. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  45463. area(p.prev, p, p.next) >= 0)
  45464. return false;
  45465. p = p.next;
  45466. }
  45467. return true;
  45468. }
  45469. function isEarHashed(ear, minX, minY, size) {
  45470. var a = ear.prev, b = ear, c = ear.next;
  45471. if (area(a, b, c) >= 0)
  45472. return false; // reflex, can't be an ear
  45473. // triangle bbox; min & max are calculated like this for speed
  45474. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  45475. // z-order range for the current triangle bbox;
  45476. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  45477. // first look for points inside the triangle in increasing z-order
  45478. var p = ear.nextZ;
  45479. while (p && p.z <= maxZ) {
  45480. if (p !== ear.prev &&
  45481. p !== ear.next &&
  45482. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  45483. area(p.prev, p, p.next) >= 0)
  45484. return false;
  45485. p = p.nextZ;
  45486. }
  45487. // then look for points in decreasing z-order
  45488. p = ear.prevZ;
  45489. while (p && p.z >= minZ) {
  45490. if (p !== ear.prev &&
  45491. p !== ear.next &&
  45492. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  45493. area(p.prev, p, p.next) >= 0)
  45494. return false;
  45495. p = p.prevZ;
  45496. }
  45497. return true;
  45498. }
  45499. // go through all polygon nodes and cure small local self-intersections
  45500. function cureLocalIntersections(start, triangles, dim) {
  45501. var p = start;
  45502. do {
  45503. var a = p.prev, b = p.next.next;
  45504. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  45505. triangles.push(a.i / dim);
  45506. triangles.push(p.i / dim);
  45507. triangles.push(b.i / dim);
  45508. // remove two nodes involved
  45509. removeNode(p);
  45510. removeNode(p.next);
  45511. p = start = b;
  45512. }
  45513. p = p.next;
  45514. } while (p !== start);
  45515. return p;
  45516. }
  45517. // try splitting polygon into two and triangulate them independently
  45518. function splitEarcut(start, triangles, dim, minX, minY, size) {
  45519. // look for a valid diagonal that divides the polygon into two
  45520. var a = start;
  45521. do {
  45522. var b = a.next.next;
  45523. while (b !== a.prev) {
  45524. if (a.i !== b.i && isValidDiagonal(a, b)) {
  45525. // split the polygon in two by the diagonal
  45526. var c = splitPolygon(a, b);
  45527. // filter colinear points around the cuts
  45528. a = filterPoints(a, a.next);
  45529. c = filterPoints(c, c.next);
  45530. // run earcut on each half
  45531. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  45532. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  45533. return;
  45534. }
  45535. b = b.next;
  45536. }
  45537. a = a.next;
  45538. } while (a !== start);
  45539. }
  45540. // link every hole into the outer loop, producing a single-ring polygon without holes
  45541. function eliminateHoles(data, holeIndices, outerNode, dim) {
  45542. var queue = [], i, len, start, end, list;
  45543. for (i = 0, len = holeIndices.length; i < len; i++) {
  45544. start = holeIndices[i] * dim;
  45545. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  45546. list = linkedList(data, start, end, dim, false);
  45547. if (list === list.next)
  45548. list.steiner = true;
  45549. queue.push(getLeftmost(list));
  45550. }
  45551. queue.sort(compareX);
  45552. // process holes from left to right
  45553. for (i = 0; i < queue.length; i++) {
  45554. eliminateHole(queue[i], outerNode);
  45555. outerNode = filterPoints(outerNode, outerNode.next);
  45556. }
  45557. return outerNode;
  45558. }
  45559. function compareX(a, b) {
  45560. return a.x - b.x;
  45561. }
  45562. // find a bridge between vertices that connects hole with an outer ring and and link it
  45563. function eliminateHole(hole, outerNode) {
  45564. outerNode = findHoleBridge(hole, outerNode);
  45565. if (outerNode) {
  45566. var b = splitPolygon(outerNode, hole);
  45567. filterPoints(b, b.next);
  45568. }
  45569. }
  45570. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  45571. function findHoleBridge(hole, outerNode) {
  45572. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  45573. // find a segment intersected by a ray from the hole's leftmost point to the left;
  45574. // segment's endpoint with lesser x will be potential connection point
  45575. do {
  45576. if (hy <= p.y && hy >= p.next.y) {
  45577. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  45578. if (x <= hx && x > qx) {
  45579. qx = x;
  45580. if (x === hx) {
  45581. if (hy === p.y)
  45582. return p;
  45583. if (hy === p.next.y)
  45584. return p.next;
  45585. }
  45586. m = p.x < p.next.x ? p : p.next;
  45587. }
  45588. }
  45589. p = p.next;
  45590. } while (p !== outerNode);
  45591. if (!m)
  45592. return null;
  45593. if (hx === qx)
  45594. return m.prev; // hole touches outer segment; pick lower endpoint
  45595. // look for points inside the triangle of hole point, segment intersection and endpoint;
  45596. // if there are no points found, we have a valid connection;
  45597. // otherwise choose the point of the minimum angle with the ray as connection point
  45598. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  45599. p = m.next;
  45600. while (p !== stop) {
  45601. if (hx >= p.x &&
  45602. p.x >= mx &&
  45603. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  45604. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  45605. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  45606. m = p;
  45607. tanMin = tan;
  45608. }
  45609. }
  45610. p = p.next;
  45611. }
  45612. return m;
  45613. }
  45614. // interlink polygon nodes in z-order
  45615. function indexCurve(start, minX, minY, size) {
  45616. var p = start;
  45617. do {
  45618. if (p.z === null)
  45619. p.z = zOrder(p.x, p.y, minX, minY, size);
  45620. p.prevZ = p.prev;
  45621. p.nextZ = p.next;
  45622. p = p.next;
  45623. } while (p !== start);
  45624. p.prevZ.nextZ = null;
  45625. p.prevZ = null;
  45626. sortLinked(p);
  45627. }
  45628. // Simon Tatham's linked list merge sort algorithm
  45629. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  45630. function sortLinked(list) {
  45631. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  45632. do {
  45633. p = list;
  45634. list = null;
  45635. tail = null;
  45636. numMerges = 0;
  45637. while (p) {
  45638. numMerges++;
  45639. q = p;
  45640. pSize = 0;
  45641. for (i = 0; i < inSize; i++) {
  45642. pSize++;
  45643. q = q.nextZ;
  45644. if (!q)
  45645. break;
  45646. }
  45647. qSize = inSize;
  45648. while (pSize > 0 || (qSize > 0 && q)) {
  45649. if (pSize === 0) {
  45650. e = q;
  45651. q = q.nextZ;
  45652. qSize--;
  45653. }
  45654. else if (qSize === 0 || !q) {
  45655. e = p;
  45656. p = p.nextZ;
  45657. pSize--;
  45658. }
  45659. else if (p.z <= q.z) {
  45660. e = p;
  45661. p = p.nextZ;
  45662. pSize--;
  45663. }
  45664. else {
  45665. e = q;
  45666. q = q.nextZ;
  45667. qSize--;
  45668. }
  45669. if (tail)
  45670. tail.nextZ = e;
  45671. else
  45672. list = e;
  45673. e.prevZ = tail;
  45674. tail = e;
  45675. }
  45676. p = q;
  45677. }
  45678. tail.nextZ = null;
  45679. inSize *= 2;
  45680. } while (numMerges > 1);
  45681. return list;
  45682. }
  45683. // z-order of a point given coords and size of the data bounding box
  45684. function zOrder(x, y, minX, minY, size) {
  45685. // coords are transformed into non-negative 15-bit integer range
  45686. x = 32767 * (x - minX) / size;
  45687. y = 32767 * (y - minY) / size;
  45688. x = (x | (x << 8)) & 0x00FF00FF;
  45689. x = (x | (x << 4)) & 0x0F0F0F0F;
  45690. x = (x | (x << 2)) & 0x33333333;
  45691. x = (x | (x << 1)) & 0x55555555;
  45692. y = (y | (y << 8)) & 0x00FF00FF;
  45693. y = (y | (y << 4)) & 0x0F0F0F0F;
  45694. y = (y | (y << 2)) & 0x33333333;
  45695. y = (y | (y << 1)) & 0x55555555;
  45696. return x | (y << 1);
  45697. }
  45698. // find the leftmost node of a polygon ring
  45699. function getLeftmost(start) {
  45700. var p = start, leftmost = start;
  45701. do {
  45702. if (p.x < leftmost.x)
  45703. leftmost = p;
  45704. p = p.next;
  45705. } while (p !== start);
  45706. return leftmost;
  45707. }
  45708. // check if a point lies within a convex triangle
  45709. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  45710. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  45711. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  45712. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  45713. }
  45714. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  45715. function isValidDiagonal(a, b) {
  45716. return a.next.i !== b.i &&
  45717. a.prev.i !== b.i &&
  45718. !intersectsPolygon(a, b) &&
  45719. locallyInside(a, b) &&
  45720. locallyInside(b, a) &&
  45721. middleInside(a, b);
  45722. }
  45723. // signed area of a triangle
  45724. function area(p, q, r) {
  45725. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  45726. }
  45727. // check if two points are equal
  45728. function equals(p1, p2) {
  45729. return p1.x === p2.x && p1.y === p2.y;
  45730. }
  45731. // check if two segments intersect
  45732. function intersects(p1, q1, p2, q2) {
  45733. if ((equals(p1, q1) && equals(p2, q2)) ||
  45734. (equals(p1, q2) && equals(p2, q1)))
  45735. return true;
  45736. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  45737. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  45738. }
  45739. // check if a polygon diagonal intersects any polygon segments
  45740. function intersectsPolygon(a, b) {
  45741. var p = a;
  45742. do {
  45743. if (p.i !== a.i &&
  45744. p.next.i !== a.i &&
  45745. p.i !== b.i &&
  45746. p.next.i !== b.i &&
  45747. intersects(p, p.next, a, b))
  45748. return true;
  45749. p = p.next;
  45750. } while (p !== a);
  45751. return false;
  45752. }
  45753. // check if a polygon diagonal is locally inside the polygon
  45754. function locallyInside(a, b) {
  45755. return area(a.prev, a, a.next) < 0
  45756. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  45757. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  45758. }
  45759. // check if the middle point of a polygon diagonal is inside the polygon
  45760. function middleInside(a, b) {
  45761. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  45762. do {
  45763. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  45764. inside = !inside;
  45765. p = p.next;
  45766. } while (p !== a);
  45767. return inside;
  45768. }
  45769. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  45770. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  45771. function splitPolygon(a, b) {
  45772. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  45773. a.next = b;
  45774. b.prev = a;
  45775. a2.next = an;
  45776. an.prev = a2;
  45777. b2.next = a2;
  45778. a2.prev = b2;
  45779. bp.next = b2;
  45780. b2.prev = bp;
  45781. return b2;
  45782. }
  45783. // create a node and optionally link it with previous one (in a circular doubly linked list)
  45784. function insertNode(i, x, y, last) {
  45785. var p = new Node(i, x, y);
  45786. if (!last) {
  45787. p.prev = p;
  45788. p.next = p;
  45789. }
  45790. else {
  45791. p.next = last.next;
  45792. p.prev = last;
  45793. last.next.prev = p;
  45794. last.next = p;
  45795. }
  45796. return p;
  45797. }
  45798. function removeNode(p) {
  45799. p.next.prev = p.prev;
  45800. p.prev.next = p.next;
  45801. if (p.prevZ)
  45802. p.prevZ.nextZ = p.nextZ;
  45803. if (p.nextZ)
  45804. p.nextZ.prevZ = p.prevZ;
  45805. }
  45806. function Node(i, x, y) {
  45807. // vertice index in coordinates array
  45808. this.i = i;
  45809. // vertex coordinates
  45810. this.x = x;
  45811. this.y = y;
  45812. // previous and next vertice nodes in a polygon ring
  45813. this.prev = null;
  45814. this.next = null;
  45815. // z-order curve value
  45816. this.z = null;
  45817. // previous and next nodes in z-order
  45818. this.prevZ = null;
  45819. this.nextZ = null;
  45820. // indicates whether this is a steiner point
  45821. this.steiner = false;
  45822. }
  45823. /**
  45824. * return a percentage difference between the polygon area and its triangulation area;
  45825. * used to verify correctness of triangulation
  45826. */
  45827. function deviation(data, holeIndices, dim, triangles) {
  45828. var hasHoles = holeIndices && holeIndices.length;
  45829. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  45830. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  45831. if (hasHoles) {
  45832. for (var i = 0, len = holeIndices.length; i < len; i++) {
  45833. var start = holeIndices[i] * dim;
  45834. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  45835. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  45836. }
  45837. }
  45838. var trianglesArea = 0;
  45839. for (i = 0; i < triangles.length; i += 3) {
  45840. var a = triangles[i] * dim;
  45841. var b = triangles[i + 1] * dim;
  45842. var c = triangles[i + 2] * dim;
  45843. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  45844. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  45845. }
  45846. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  45847. }
  45848. Earcut.deviation = deviation;
  45849. ;
  45850. function signedArea(data, start, end, dim) {
  45851. var sum = 0;
  45852. for (var i = start, j = end - dim; i < end; i += dim) {
  45853. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  45854. j = i;
  45855. }
  45856. return sum;
  45857. }
  45858. /**
  45859. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  45860. */
  45861. function flatten(data) {
  45862. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  45863. for (var i = 0; i < data.length; i++) {
  45864. for (var j = 0; j < data[i].length; j++) {
  45865. for (var d = 0; d < dim; d++)
  45866. result.vertices.push(data[i][j][d]);
  45867. }
  45868. if (i > 0) {
  45869. holeIndex += data[i - 1].length;
  45870. result.holes.push(holeIndex);
  45871. }
  45872. }
  45873. return result;
  45874. }
  45875. Earcut.flatten = flatten;
  45876. ;
  45877. })(Earcut || (Earcut = {}));
  45878. var BABYLON;
  45879. (function (BABYLON) {
  45880. // Unique ID when we import meshes from Babylon to CSG
  45881. var currentCSGMeshId = 0;
  45882. // # class Vertex
  45883. // Represents a vertex of a polygon. Use your own vertex class instead of this
  45884. // one to provide additional features like texture coordinates and vertex
  45885. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  45886. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  45887. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  45888. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  45889. // is not used anywhere else.
  45890. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  45891. var Vertex = (function () {
  45892. function Vertex(pos, normal, uv) {
  45893. this.pos = pos;
  45894. this.normal = normal;
  45895. this.uv = uv;
  45896. }
  45897. Vertex.prototype.clone = function () {
  45898. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  45899. };
  45900. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  45901. // orientation of a polygon is flipped.
  45902. Vertex.prototype.flip = function () {
  45903. this.normal = this.normal.scale(-1);
  45904. };
  45905. // Create a new vertex between this vertex and `other` by linearly
  45906. // interpolating all properties using a parameter of `t`. Subclasses should
  45907. // override this to interpolate additional properties.
  45908. Vertex.prototype.interpolate = function (other, t) {
  45909. 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));
  45910. };
  45911. return Vertex;
  45912. })();
  45913. // # class Plane
  45914. // Represents a plane in 3D space.
  45915. var Plane = (function () {
  45916. function Plane(normal, w) {
  45917. this.normal = normal;
  45918. this.w = w;
  45919. }
  45920. Plane.FromPoints = function (a, b, c) {
  45921. var v0 = c.subtract(a);
  45922. var v1 = b.subtract(a);
  45923. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  45924. return null;
  45925. }
  45926. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  45927. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  45928. };
  45929. Plane.prototype.clone = function () {
  45930. return new Plane(this.normal.clone(), this.w);
  45931. };
  45932. Plane.prototype.flip = function () {
  45933. this.normal.scaleInPlace(-1);
  45934. this.w = -this.w;
  45935. };
  45936. // Split `polygon` by this plane if needed, then put the polygon or polygon
  45937. // fragments in the appropriate lists. Coplanar polygons go into either
  45938. // `coplanarFront` or `coplanarBack` depending on their orientation with
  45939. // respect to this plane. Polygons in front or in back of this plane go into
  45940. // either `front` or `back`.
  45941. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  45942. var COPLANAR = 0;
  45943. var FRONT = 1;
  45944. var BACK = 2;
  45945. var SPANNING = 3;
  45946. // Classify each point as well as the entire polygon into one of the above
  45947. // four classes.
  45948. var polygonType = 0;
  45949. var types = [];
  45950. var i;
  45951. var t;
  45952. for (i = 0; i < polygon.vertices.length; i++) {
  45953. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  45954. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  45955. polygonType |= type;
  45956. types.push(type);
  45957. }
  45958. // Put the polygon in the correct list, splitting it when necessary.
  45959. switch (polygonType) {
  45960. case COPLANAR:
  45961. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  45962. break;
  45963. case FRONT:
  45964. front.push(polygon);
  45965. break;
  45966. case BACK:
  45967. back.push(polygon);
  45968. break;
  45969. case SPANNING:
  45970. var f = [], b = [];
  45971. for (i = 0; i < polygon.vertices.length; i++) {
  45972. var j = (i + 1) % polygon.vertices.length;
  45973. var ti = types[i], tj = types[j];
  45974. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  45975. if (ti !== BACK)
  45976. f.push(vi);
  45977. if (ti !== FRONT)
  45978. b.push(ti !== BACK ? vi.clone() : vi);
  45979. if ((ti | tj) === SPANNING) {
  45980. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  45981. var v = vi.interpolate(vj, t);
  45982. f.push(v);
  45983. b.push(v.clone());
  45984. }
  45985. }
  45986. var poly;
  45987. if (f.length >= 3) {
  45988. poly = new Polygon(f, polygon.shared);
  45989. if (poly.plane)
  45990. front.push(poly);
  45991. }
  45992. if (b.length >= 3) {
  45993. poly = new Polygon(b, polygon.shared);
  45994. if (poly.plane)
  45995. back.push(poly);
  45996. }
  45997. break;
  45998. }
  45999. };
  46000. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  46001. // point is on the plane.
  46002. Plane.EPSILON = 1e-5;
  46003. return Plane;
  46004. })();
  46005. // # class Polygon
  46006. // Represents a convex polygon. The vertices used to initialize a polygon must
  46007. // be coplanar and form a convex loop.
  46008. //
  46009. // Each convex polygon has a `shared` property, which is shared between all
  46010. // polygons that are clones of each other or were split from the same polygon.
  46011. // This can be used to define per-polygon properties (such as surface color).
  46012. var Polygon = (function () {
  46013. function Polygon(vertices, shared) {
  46014. this.vertices = vertices;
  46015. this.shared = shared;
  46016. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  46017. }
  46018. Polygon.prototype.clone = function () {
  46019. var vertices = this.vertices.map(function (v) { return v.clone(); });
  46020. return new Polygon(vertices, this.shared);
  46021. };
  46022. Polygon.prototype.flip = function () {
  46023. this.vertices.reverse().map(function (v) { v.flip(); });
  46024. this.plane.flip();
  46025. };
  46026. return Polygon;
  46027. })();
  46028. // # class Node
  46029. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  46030. // by picking a polygon to split along. That polygon (and all other coplanar
  46031. // polygons) are added directly to that node and the other polygons are added to
  46032. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  46033. // no distinction between internal and leaf nodes.
  46034. var Node = (function () {
  46035. function Node(polygons) {
  46036. this.plane = null;
  46037. this.front = null;
  46038. this.back = null;
  46039. this.polygons = [];
  46040. if (polygons) {
  46041. this.build(polygons);
  46042. }
  46043. }
  46044. Node.prototype.clone = function () {
  46045. var node = new Node();
  46046. node.plane = this.plane && this.plane.clone();
  46047. node.front = this.front && this.front.clone();
  46048. node.back = this.back && this.back.clone();
  46049. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  46050. return node;
  46051. };
  46052. // Convert solid space to empty space and empty space to solid space.
  46053. Node.prototype.invert = function () {
  46054. for (var i = 0; i < this.polygons.length; i++) {
  46055. this.polygons[i].flip();
  46056. }
  46057. if (this.plane) {
  46058. this.plane.flip();
  46059. }
  46060. if (this.front) {
  46061. this.front.invert();
  46062. }
  46063. if (this.back) {
  46064. this.back.invert();
  46065. }
  46066. var temp = this.front;
  46067. this.front = this.back;
  46068. this.back = temp;
  46069. };
  46070. // Recursively remove all polygons in `polygons` that are inside this BSP
  46071. // tree.
  46072. Node.prototype.clipPolygons = function (polygons) {
  46073. if (!this.plane)
  46074. return polygons.slice();
  46075. var front = [], back = [];
  46076. for (var i = 0; i < polygons.length; i++) {
  46077. this.plane.splitPolygon(polygons[i], front, back, front, back);
  46078. }
  46079. if (this.front) {
  46080. front = this.front.clipPolygons(front);
  46081. }
  46082. if (this.back) {
  46083. back = this.back.clipPolygons(back);
  46084. }
  46085. else {
  46086. back = [];
  46087. }
  46088. return front.concat(back);
  46089. };
  46090. // Remove all polygons in this BSP tree that are inside the other BSP tree
  46091. // `bsp`.
  46092. Node.prototype.clipTo = function (bsp) {
  46093. this.polygons = bsp.clipPolygons(this.polygons);
  46094. if (this.front)
  46095. this.front.clipTo(bsp);
  46096. if (this.back)
  46097. this.back.clipTo(bsp);
  46098. };
  46099. // Return a list of all polygons in this BSP tree.
  46100. Node.prototype.allPolygons = function () {
  46101. var polygons = this.polygons.slice();
  46102. if (this.front)
  46103. polygons = polygons.concat(this.front.allPolygons());
  46104. if (this.back)
  46105. polygons = polygons.concat(this.back.allPolygons());
  46106. return polygons;
  46107. };
  46108. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  46109. // new polygons are filtered down to the bottom of the tree and become new
  46110. // nodes there. Each set of polygons is partitioned using the first polygon
  46111. // (no heuristic is used to pick a good split).
  46112. Node.prototype.build = function (polygons) {
  46113. if (!polygons.length)
  46114. return;
  46115. if (!this.plane)
  46116. this.plane = polygons[0].plane.clone();
  46117. var front = [], back = [];
  46118. for (var i = 0; i < polygons.length; i++) {
  46119. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  46120. }
  46121. if (front.length) {
  46122. if (!this.front)
  46123. this.front = new Node();
  46124. this.front.build(front);
  46125. }
  46126. if (back.length) {
  46127. if (!this.back)
  46128. this.back = new Node();
  46129. this.back.build(back);
  46130. }
  46131. };
  46132. return Node;
  46133. })();
  46134. var CSG = (function () {
  46135. function CSG() {
  46136. this.polygons = new Array();
  46137. }
  46138. // Convert BABYLON.Mesh to BABYLON.CSG
  46139. CSG.FromMesh = function (mesh) {
  46140. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  46141. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  46142. if (mesh instanceof BABYLON.Mesh) {
  46143. mesh.computeWorldMatrix(true);
  46144. matrix = mesh.getWorldMatrix();
  46145. meshPosition = mesh.position.clone();
  46146. meshRotation = mesh.rotation.clone();
  46147. if (mesh.rotationQuaternion) {
  46148. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  46149. }
  46150. meshScaling = mesh.scaling.clone();
  46151. }
  46152. else {
  46153. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  46154. }
  46155. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46156. var subMeshes = mesh.subMeshes;
  46157. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  46158. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  46159. vertices = [];
  46160. for (var j = 0; j < 3; j++) {
  46161. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  46162. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  46163. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  46164. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  46165. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  46166. vertex = new Vertex(position, normal, uv);
  46167. vertices.push(vertex);
  46168. }
  46169. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  46170. // To handle the case of degenerated triangle
  46171. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  46172. if (polygon.plane)
  46173. polygons.push(polygon);
  46174. }
  46175. }
  46176. var csg = CSG.FromPolygons(polygons);
  46177. csg.matrix = matrix;
  46178. csg.position = meshPosition;
  46179. csg.rotation = meshRotation;
  46180. csg.scaling = meshScaling;
  46181. csg.rotationQuaternion = meshRotationQuaternion;
  46182. currentCSGMeshId++;
  46183. return csg;
  46184. };
  46185. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  46186. CSG.FromPolygons = function (polygons) {
  46187. var csg = new CSG();
  46188. csg.polygons = polygons;
  46189. return csg;
  46190. };
  46191. CSG.prototype.clone = function () {
  46192. var csg = new CSG();
  46193. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  46194. csg.copyTransformAttributes(this);
  46195. return csg;
  46196. };
  46197. CSG.prototype.toPolygons = function () {
  46198. return this.polygons;
  46199. };
  46200. CSG.prototype.union = function (csg) {
  46201. var a = new Node(this.clone().polygons);
  46202. var b = new Node(csg.clone().polygons);
  46203. a.clipTo(b);
  46204. b.clipTo(a);
  46205. b.invert();
  46206. b.clipTo(a);
  46207. b.invert();
  46208. a.build(b.allPolygons());
  46209. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46210. };
  46211. CSG.prototype.unionInPlace = function (csg) {
  46212. var a = new Node(this.polygons);
  46213. var b = new Node(csg.polygons);
  46214. a.clipTo(b);
  46215. b.clipTo(a);
  46216. b.invert();
  46217. b.clipTo(a);
  46218. b.invert();
  46219. a.build(b.allPolygons());
  46220. this.polygons = a.allPolygons();
  46221. };
  46222. CSG.prototype.subtract = function (csg) {
  46223. var a = new Node(this.clone().polygons);
  46224. var b = new Node(csg.clone().polygons);
  46225. a.invert();
  46226. a.clipTo(b);
  46227. b.clipTo(a);
  46228. b.invert();
  46229. b.clipTo(a);
  46230. b.invert();
  46231. a.build(b.allPolygons());
  46232. a.invert();
  46233. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46234. };
  46235. CSG.prototype.subtractInPlace = function (csg) {
  46236. var a = new Node(this.polygons);
  46237. var b = new Node(csg.polygons);
  46238. a.invert();
  46239. a.clipTo(b);
  46240. b.clipTo(a);
  46241. b.invert();
  46242. b.clipTo(a);
  46243. b.invert();
  46244. a.build(b.allPolygons());
  46245. a.invert();
  46246. this.polygons = a.allPolygons();
  46247. };
  46248. CSG.prototype.intersect = function (csg) {
  46249. var a = new Node(this.clone().polygons);
  46250. var b = new Node(csg.clone().polygons);
  46251. a.invert();
  46252. b.clipTo(a);
  46253. b.invert();
  46254. a.clipTo(b);
  46255. b.clipTo(a);
  46256. a.build(b.allPolygons());
  46257. a.invert();
  46258. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46259. };
  46260. CSG.prototype.intersectInPlace = function (csg) {
  46261. var a = new Node(this.polygons);
  46262. var b = new Node(csg.polygons);
  46263. a.invert();
  46264. b.clipTo(a);
  46265. b.invert();
  46266. a.clipTo(b);
  46267. b.clipTo(a);
  46268. a.build(b.allPolygons());
  46269. a.invert();
  46270. this.polygons = a.allPolygons();
  46271. };
  46272. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  46273. // not modified.
  46274. CSG.prototype.inverse = function () {
  46275. var csg = this.clone();
  46276. csg.inverseInPlace();
  46277. return csg;
  46278. };
  46279. CSG.prototype.inverseInPlace = function () {
  46280. this.polygons.map(function (p) { p.flip(); });
  46281. };
  46282. // This is used to keep meshes transformations so they can be restored
  46283. // when we build back a Babylon Mesh
  46284. // NB : All CSG operations are performed in world coordinates
  46285. CSG.prototype.copyTransformAttributes = function (csg) {
  46286. this.matrix = csg.matrix;
  46287. this.position = csg.position;
  46288. this.rotation = csg.rotation;
  46289. this.scaling = csg.scaling;
  46290. this.rotationQuaternion = csg.rotationQuaternion;
  46291. return this;
  46292. };
  46293. // Build Raw mesh from CSG
  46294. // Coordinates here are in world space
  46295. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  46296. var matrix = this.matrix.clone();
  46297. matrix.invert();
  46298. 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;
  46299. if (keepSubMeshes) {
  46300. // Sort Polygons, since subMeshes are indices range
  46301. polygons.sort(function (a, b) {
  46302. if (a.shared.meshId === b.shared.meshId) {
  46303. return a.shared.subMeshId - b.shared.subMeshId;
  46304. }
  46305. else {
  46306. return a.shared.meshId - b.shared.meshId;
  46307. }
  46308. });
  46309. }
  46310. for (var i = 0, il = polygons.length; i < il; i++) {
  46311. polygon = polygons[i];
  46312. // Building SubMeshes
  46313. if (!subMesh_dict[polygon.shared.meshId]) {
  46314. subMesh_dict[polygon.shared.meshId] = {};
  46315. }
  46316. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  46317. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  46318. indexStart: +Infinity,
  46319. indexEnd: -Infinity,
  46320. materialIndex: polygon.shared.materialIndex
  46321. };
  46322. }
  46323. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  46324. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  46325. polygonIndices[0] = 0;
  46326. polygonIndices[1] = j - 1;
  46327. polygonIndices[2] = j;
  46328. for (var k = 0; k < 3; k++) {
  46329. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  46330. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  46331. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  46332. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  46333. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  46334. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  46335. // Check if 2 points can be merged
  46336. if (!(typeof vertex_idx !== 'undefined' &&
  46337. normals[vertex_idx * 3] === localNormal.x &&
  46338. normals[vertex_idx * 3 + 1] === localNormal.y &&
  46339. normals[vertex_idx * 3 + 2] === localNormal.z &&
  46340. uvs[vertex_idx * 2] === uv.x &&
  46341. uvs[vertex_idx * 2 + 1] === uv.y)) {
  46342. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  46343. uvs.push(uv.x, uv.y);
  46344. normals.push(normal.x, normal.y, normal.z);
  46345. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  46346. }
  46347. indices.push(vertex_idx);
  46348. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  46349. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  46350. currentIndex++;
  46351. }
  46352. }
  46353. }
  46354. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  46355. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  46356. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  46357. mesh.setIndices(indices);
  46358. if (keepSubMeshes) {
  46359. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  46360. var materialIndexOffset = 0, materialMaxIndex;
  46361. mesh.subMeshes = new Array();
  46362. for (var m in subMesh_dict) {
  46363. materialMaxIndex = -1;
  46364. for (var sm in subMesh_dict[m]) {
  46365. subMesh_obj = subMesh_dict[m][sm];
  46366. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  46367. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  46368. }
  46369. materialIndexOffset += ++materialMaxIndex;
  46370. }
  46371. }
  46372. return mesh;
  46373. };
  46374. // Build Mesh from CSG taking material and transforms into account
  46375. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  46376. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  46377. mesh.material = material;
  46378. mesh.position.copyFrom(this.position);
  46379. mesh.rotation.copyFrom(this.rotation);
  46380. if (this.rotationQuaternion) {
  46381. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  46382. }
  46383. mesh.scaling.copyFrom(this.scaling);
  46384. mesh.computeWorldMatrix(true);
  46385. return mesh;
  46386. };
  46387. return CSG;
  46388. })();
  46389. BABYLON.CSG = CSG;
  46390. })(BABYLON || (BABYLON = {}));
  46391. var BABYLON;
  46392. (function (BABYLON) {
  46393. var VRDistortionCorrectionPostProcess = (function (_super) {
  46394. __extends(VRDistortionCorrectionPostProcess, _super);
  46395. //ANY
  46396. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  46397. var _this = this;
  46398. _super.call(this, name, "vrDistortionCorrection", [
  46399. 'LensCenter',
  46400. 'Scale',
  46401. 'ScaleIn',
  46402. 'HmdWarpParam'
  46403. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  46404. this._isRightEye = isRightEye;
  46405. this._distortionFactors = vrMetrics.distortionK;
  46406. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  46407. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  46408. this.onSizeChangedObservable.add(function () {
  46409. _this.aspectRatio = _this.width * .5 / _this.height;
  46410. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  46411. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  46412. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  46413. });
  46414. this.onApplyObservable.add(function (effect) {
  46415. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  46416. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  46417. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  46418. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  46419. });
  46420. }
  46421. return VRDistortionCorrectionPostProcess;
  46422. })(BABYLON.PostProcess);
  46423. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  46424. })(BABYLON || (BABYLON = {}));
  46425. // Mainly based on these 2 articles :
  46426. // 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
  46427. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  46428. var BABYLON;
  46429. (function (BABYLON) {
  46430. (function (JoystickAxis) {
  46431. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  46432. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  46433. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  46434. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  46435. var JoystickAxis = BABYLON.JoystickAxis;
  46436. var VirtualJoystick = (function () {
  46437. function VirtualJoystick(leftJoystick) {
  46438. var _this = this;
  46439. if (leftJoystick) {
  46440. this._leftJoystick = true;
  46441. }
  46442. else {
  46443. this._leftJoystick = false;
  46444. }
  46445. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  46446. VirtualJoystick._globalJoystickIndex++;
  46447. // By default left & right arrow keys are moving the X
  46448. // and up & down keys are moving the Y
  46449. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  46450. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  46451. this.reverseLeftRight = false;
  46452. this.reverseUpDown = false;
  46453. // collections of pointers
  46454. this._touches = new BABYLON.StringDictionary();
  46455. this.deltaPosition = BABYLON.Vector3.Zero();
  46456. this._joystickSensibility = 25;
  46457. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  46458. this._rotationSpeed = 25;
  46459. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  46460. this._rotateOnAxisRelativeToMesh = false;
  46461. this._onResize = function (evt) {
  46462. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  46463. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  46464. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  46465. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  46466. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  46467. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  46468. };
  46469. // injecting a canvas element on top of the canvas 3D game
  46470. if (!VirtualJoystick.vjCanvas) {
  46471. window.addEventListener("resize", this._onResize, false);
  46472. VirtualJoystick.vjCanvas = document.createElement("canvas");
  46473. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  46474. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  46475. VirtualJoystick.vjCanvas.width = window.innerWidth;
  46476. VirtualJoystick.vjCanvas.height = window.innerHeight;
  46477. VirtualJoystick.vjCanvas.style.width = "100%";
  46478. VirtualJoystick.vjCanvas.style.height = "100%";
  46479. VirtualJoystick.vjCanvas.style.position = "absolute";
  46480. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  46481. VirtualJoystick.vjCanvas.style.top = "0px";
  46482. VirtualJoystick.vjCanvas.style.left = "0px";
  46483. VirtualJoystick.vjCanvas.style.zIndex = "5";
  46484. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  46485. // Support for jQuery PEP polyfill
  46486. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  46487. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  46488. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  46489. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  46490. document.body.appendChild(VirtualJoystick.vjCanvas);
  46491. }
  46492. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  46493. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  46494. this.pressed = false;
  46495. // default joystick color
  46496. this._joystickColor = "cyan";
  46497. this._joystickPointerID = -1;
  46498. // current joystick position
  46499. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  46500. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  46501. // origin joystick position
  46502. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  46503. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  46504. this._onPointerDownHandlerRef = function (evt) {
  46505. _this._onPointerDown(evt);
  46506. };
  46507. this._onPointerMoveHandlerRef = function (evt) {
  46508. _this._onPointerMove(evt);
  46509. };
  46510. this._onPointerOutHandlerRef = function (evt) {
  46511. _this._onPointerUp(evt);
  46512. };
  46513. this._onPointerUpHandlerRef = function (evt) {
  46514. _this._onPointerUp(evt);
  46515. };
  46516. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  46517. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  46518. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  46519. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  46520. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  46521. evt.preventDefault(); // Disables system menu
  46522. }, false);
  46523. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  46524. }
  46525. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  46526. this._joystickSensibility = newJoystickSensibility;
  46527. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  46528. };
  46529. VirtualJoystick.prototype._onPointerDown = function (e) {
  46530. var positionOnScreenCondition;
  46531. e.preventDefault();
  46532. if (this._leftJoystick === true) {
  46533. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  46534. }
  46535. else {
  46536. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  46537. }
  46538. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  46539. // First contact will be dedicated to the virtual joystick
  46540. this._joystickPointerID = e.pointerId;
  46541. this._joystickPointerStartPos.x = e.clientX;
  46542. this._joystickPointerStartPos.y = e.clientY;
  46543. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  46544. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  46545. this._deltaJoystickVector.x = 0;
  46546. this._deltaJoystickVector.y = 0;
  46547. this.pressed = true;
  46548. this._touches.add(e.pointerId.toString(), e);
  46549. }
  46550. else {
  46551. // You can only trigger the action buttons with a joystick declared
  46552. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  46553. this._action();
  46554. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  46555. }
  46556. }
  46557. };
  46558. VirtualJoystick.prototype._onPointerMove = function (e) {
  46559. // If the current pointer is the one associated to the joystick (first touch contact)
  46560. if (this._joystickPointerID == e.pointerId) {
  46561. this._joystickPointerPos.x = e.clientX;
  46562. this._joystickPointerPos.y = e.clientY;
  46563. this._deltaJoystickVector = this._joystickPointerPos.clone();
  46564. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  46565. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  46566. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  46567. switch (this._axisTargetedByLeftAndRight) {
  46568. case JoystickAxis.X:
  46569. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  46570. break;
  46571. case JoystickAxis.Y:
  46572. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  46573. break;
  46574. case JoystickAxis.Z:
  46575. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  46576. break;
  46577. }
  46578. var directionUpDown = this.reverseUpDown ? 1 : -1;
  46579. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  46580. switch (this._axisTargetedByUpAndDown) {
  46581. case JoystickAxis.X:
  46582. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  46583. break;
  46584. case JoystickAxis.Y:
  46585. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  46586. break;
  46587. case JoystickAxis.Z:
  46588. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  46589. break;
  46590. }
  46591. }
  46592. else {
  46593. var data = this._touches.get(e.pointerId.toString());
  46594. if (data) {
  46595. data.x = e.clientX;
  46596. data.y = e.clientY;
  46597. }
  46598. }
  46599. };
  46600. VirtualJoystick.prototype._onPointerUp = function (e) {
  46601. if (this._joystickPointerID == e.pointerId) {
  46602. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  46603. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  46604. this._joystickPointerID = -1;
  46605. this.pressed = false;
  46606. }
  46607. else {
  46608. var touch = this._touches.get(e.pointerId.toString());
  46609. if (touch) {
  46610. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  46611. }
  46612. }
  46613. this._deltaJoystickVector.x = 0;
  46614. this._deltaJoystickVector.y = 0;
  46615. this._touches.remove(e.pointerId.toString());
  46616. };
  46617. /**
  46618. * Change the color of the virtual joystick
  46619. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  46620. */
  46621. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  46622. this._joystickColor = newColor;
  46623. };
  46624. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  46625. this._action = action;
  46626. };
  46627. // Define which axis you'd like to control for left & right
  46628. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  46629. switch (axis) {
  46630. case JoystickAxis.X:
  46631. case JoystickAxis.Y:
  46632. case JoystickAxis.Z:
  46633. this._axisTargetedByLeftAndRight = axis;
  46634. break;
  46635. default:
  46636. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  46637. break;
  46638. }
  46639. };
  46640. // Define which axis you'd like to control for up & down
  46641. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  46642. switch (axis) {
  46643. case JoystickAxis.X:
  46644. case JoystickAxis.Y:
  46645. case JoystickAxis.Z:
  46646. this._axisTargetedByUpAndDown = axis;
  46647. break;
  46648. default:
  46649. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  46650. break;
  46651. }
  46652. };
  46653. VirtualJoystick.prototype._clearCanvas = function () {
  46654. if (this._leftJoystick) {
  46655. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  46656. }
  46657. else {
  46658. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  46659. }
  46660. };
  46661. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  46662. var _this = this;
  46663. if (this.pressed) {
  46664. this._touches.forEach(function (touch) {
  46665. if (touch.pointerId === _this._joystickPointerID) {
  46666. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  46667. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  46668. VirtualJoystick.vjCanvasContext.beginPath();
  46669. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  46670. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  46671. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  46672. VirtualJoystick.vjCanvasContext.stroke();
  46673. VirtualJoystick.vjCanvasContext.closePath();
  46674. VirtualJoystick.vjCanvasContext.beginPath();
  46675. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  46676. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  46677. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  46678. VirtualJoystick.vjCanvasContext.stroke();
  46679. VirtualJoystick.vjCanvasContext.closePath();
  46680. VirtualJoystick.vjCanvasContext.beginPath();
  46681. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  46682. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  46683. VirtualJoystick.vjCanvasContext.stroke();
  46684. VirtualJoystick.vjCanvasContext.closePath();
  46685. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  46686. }
  46687. else {
  46688. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  46689. VirtualJoystick.vjCanvasContext.beginPath();
  46690. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  46691. VirtualJoystick.vjCanvasContext.beginPath();
  46692. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  46693. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  46694. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  46695. VirtualJoystick.vjCanvasContext.stroke();
  46696. VirtualJoystick.vjCanvasContext.closePath();
  46697. touch.prevX = touch.x;
  46698. touch.prevY = touch.y;
  46699. }
  46700. ;
  46701. });
  46702. }
  46703. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  46704. };
  46705. VirtualJoystick.prototype.releaseCanvas = function () {
  46706. if (VirtualJoystick.vjCanvas) {
  46707. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  46708. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  46709. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  46710. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  46711. window.removeEventListener("resize", this._onResize);
  46712. document.body.removeChild(VirtualJoystick.vjCanvas);
  46713. VirtualJoystick.vjCanvas = null;
  46714. }
  46715. };
  46716. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  46717. VirtualJoystick._globalJoystickIndex = 0;
  46718. return VirtualJoystick;
  46719. })();
  46720. BABYLON.VirtualJoystick = VirtualJoystick;
  46721. })(BABYLON || (BABYLON = {}));
  46722. var BABYLON;
  46723. (function (BABYLON) {
  46724. // We're mainly based on the logic defined into the FreeCamera code
  46725. var VirtualJoysticksCamera = (function (_super) {
  46726. __extends(VirtualJoysticksCamera, _super);
  46727. function VirtualJoysticksCamera(name, position, scene) {
  46728. _super.call(this, name, position, scene);
  46729. this.inputs.addVirtualJoystick();
  46730. }
  46731. return VirtualJoysticksCamera;
  46732. })(BABYLON.FreeCamera);
  46733. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  46734. })(BABYLON || (BABYLON = {}));
  46735. var BABYLON;
  46736. (function (BABYLON) {
  46737. var FreeCameraVirtualJoystickInput = (function () {
  46738. function FreeCameraVirtualJoystickInput() {
  46739. }
  46740. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  46741. return this._leftjoystick;
  46742. };
  46743. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  46744. return this._rightjoystick;
  46745. };
  46746. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  46747. if (this._leftjoystick) {
  46748. var camera = this.camera;
  46749. var speed = camera._computeLocalCameraSpeed() * 50;
  46750. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  46751. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  46752. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  46753. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  46754. if (!this._leftjoystick.pressed) {
  46755. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  46756. }
  46757. if (!this._rightjoystick.pressed) {
  46758. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  46759. }
  46760. }
  46761. };
  46762. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  46763. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  46764. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  46765. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  46766. this._leftjoystick.setJoystickSensibility(0.15);
  46767. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  46768. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  46769. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  46770. this._rightjoystick.reverseUpDown = true;
  46771. this._rightjoystick.setJoystickSensibility(0.05);
  46772. this._rightjoystick.setJoystickColor("yellow");
  46773. };
  46774. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  46775. this._leftjoystick.releaseCanvas();
  46776. this._rightjoystick.releaseCanvas();
  46777. };
  46778. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  46779. return "FreeCameraVirtualJoystickInput";
  46780. };
  46781. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  46782. return "virtualJoystick";
  46783. };
  46784. return FreeCameraVirtualJoystickInput;
  46785. })();
  46786. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  46787. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  46788. })(BABYLON || (BABYLON = {}));
  46789. var BABYLON;
  46790. (function (BABYLON) {
  46791. var AnaglyphPostProcess = (function (_super) {
  46792. __extends(AnaglyphPostProcess, _super);
  46793. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  46794. var _this = this;
  46795. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  46796. this._passedProcess = rigCameras[0]._rigPostProcess;
  46797. this.onApplyObservable.add(function (effect) {
  46798. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  46799. });
  46800. }
  46801. return AnaglyphPostProcess;
  46802. })(BABYLON.PostProcess);
  46803. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  46804. })(BABYLON || (BABYLON = {}));
  46805. var BABYLON;
  46806. (function (BABYLON) {
  46807. var OutlineRenderer = (function () {
  46808. function OutlineRenderer(scene) {
  46809. this._scene = scene;
  46810. }
  46811. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  46812. var _this = this;
  46813. if (useOverlay === void 0) { useOverlay = false; }
  46814. var scene = this._scene;
  46815. var engine = this._scene.getEngine();
  46816. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  46817. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  46818. return;
  46819. }
  46820. var mesh = subMesh.getRenderingMesh();
  46821. var material = subMesh.getMaterial();
  46822. engine.enableEffect(this._effect);
  46823. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  46824. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  46825. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46826. // Bones
  46827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46828. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46829. }
  46830. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  46831. // Alpha test
  46832. if (material && material.needAlphaTesting()) {
  46833. var alphaTexture = material.getAlphaTestTexture();
  46834. this._effect.setTexture("diffuseSampler", alphaTexture);
  46835. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46836. }
  46837. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  46838. };
  46839. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  46840. var defines = [];
  46841. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  46842. var mesh = subMesh.getMesh();
  46843. var material = subMesh.getMaterial();
  46844. // Alpha test
  46845. if (material && material.needAlphaTesting()) {
  46846. defines.push("#define ALPHATEST");
  46847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46848. attribs.push(BABYLON.VertexBuffer.UVKind);
  46849. defines.push("#define UV1");
  46850. }
  46851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46852. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46853. defines.push("#define UV2");
  46854. }
  46855. }
  46856. // Bones
  46857. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46860. if (mesh.numBoneInfluencers > 4) {
  46861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46863. }
  46864. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46865. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46866. }
  46867. else {
  46868. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46869. }
  46870. // Instances
  46871. if (useInstances) {
  46872. defines.push("#define INSTANCES");
  46873. attribs.push("world0");
  46874. attribs.push("world1");
  46875. attribs.push("world2");
  46876. attribs.push("world3");
  46877. }
  46878. // Get correct effect
  46879. var join = defines.join("\n");
  46880. if (this._cachedDefines !== join) {
  46881. this._cachedDefines = join;
  46882. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  46883. }
  46884. return this._effect.isReady();
  46885. };
  46886. return OutlineRenderer;
  46887. })();
  46888. BABYLON.OutlineRenderer = OutlineRenderer;
  46889. })(BABYLON || (BABYLON = {}));
  46890. var BABYLON;
  46891. (function (BABYLON) {
  46892. var MeshAssetTask = (function () {
  46893. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  46894. this.name = name;
  46895. this.meshesNames = meshesNames;
  46896. this.rootUrl = rootUrl;
  46897. this.sceneFilename = sceneFilename;
  46898. this.isCompleted = false;
  46899. }
  46900. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  46901. var _this = this;
  46902. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  46903. _this.loadedMeshes = meshes;
  46904. _this.loadedParticleSystems = particleSystems;
  46905. _this.loadedSkeletons = skeletons;
  46906. _this.isCompleted = true;
  46907. if (_this.onSuccess) {
  46908. _this.onSuccess(_this);
  46909. }
  46910. onSuccess();
  46911. }, null, function () {
  46912. if (_this.onError) {
  46913. _this.onError(_this);
  46914. }
  46915. onError();
  46916. });
  46917. };
  46918. return MeshAssetTask;
  46919. })();
  46920. BABYLON.MeshAssetTask = MeshAssetTask;
  46921. var TextFileAssetTask = (function () {
  46922. function TextFileAssetTask(name, url) {
  46923. this.name = name;
  46924. this.url = url;
  46925. this.isCompleted = false;
  46926. }
  46927. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  46928. var _this = this;
  46929. BABYLON.Tools.LoadFile(this.url, function (data) {
  46930. _this.text = data;
  46931. _this.isCompleted = true;
  46932. if (_this.onSuccess) {
  46933. _this.onSuccess(_this);
  46934. }
  46935. onSuccess();
  46936. }, null, scene.database, false, function () {
  46937. if (_this.onError) {
  46938. _this.onError(_this);
  46939. }
  46940. onError();
  46941. });
  46942. };
  46943. return TextFileAssetTask;
  46944. })();
  46945. BABYLON.TextFileAssetTask = TextFileAssetTask;
  46946. var BinaryFileAssetTask = (function () {
  46947. function BinaryFileAssetTask(name, url) {
  46948. this.name = name;
  46949. this.url = url;
  46950. this.isCompleted = false;
  46951. }
  46952. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  46953. var _this = this;
  46954. BABYLON.Tools.LoadFile(this.url, function (data) {
  46955. _this.data = data;
  46956. _this.isCompleted = true;
  46957. if (_this.onSuccess) {
  46958. _this.onSuccess(_this);
  46959. }
  46960. onSuccess();
  46961. }, null, scene.database, true, function () {
  46962. if (_this.onError) {
  46963. _this.onError(_this);
  46964. }
  46965. onError();
  46966. });
  46967. };
  46968. return BinaryFileAssetTask;
  46969. })();
  46970. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  46971. var ImageAssetTask = (function () {
  46972. function ImageAssetTask(name, url) {
  46973. this.name = name;
  46974. this.url = url;
  46975. this.isCompleted = false;
  46976. }
  46977. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  46978. var _this = this;
  46979. var img = new Image();
  46980. img.onload = function () {
  46981. _this.image = img;
  46982. _this.isCompleted = true;
  46983. if (_this.onSuccess) {
  46984. _this.onSuccess(_this);
  46985. }
  46986. onSuccess();
  46987. };
  46988. img.onerror = function () {
  46989. if (_this.onError) {
  46990. _this.onError(_this);
  46991. }
  46992. onError();
  46993. };
  46994. img.src = this.url;
  46995. };
  46996. return ImageAssetTask;
  46997. })();
  46998. BABYLON.ImageAssetTask = ImageAssetTask;
  46999. var TextureAssetTask = (function () {
  47000. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  47001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47002. this.name = name;
  47003. this.url = url;
  47004. this.noMipmap = noMipmap;
  47005. this.invertY = invertY;
  47006. this.samplingMode = samplingMode;
  47007. this.isCompleted = false;
  47008. }
  47009. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47010. var _this = this;
  47011. var onload = function () {
  47012. _this.isCompleted = true;
  47013. if (_this.onSuccess) {
  47014. _this.onSuccess(_this);
  47015. }
  47016. onSuccess();
  47017. };
  47018. var onerror = function () {
  47019. if (_this.onError) {
  47020. _this.onError(_this);
  47021. }
  47022. onError();
  47023. };
  47024. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  47025. };
  47026. return TextureAssetTask;
  47027. })();
  47028. BABYLON.TextureAssetTask = TextureAssetTask;
  47029. var AssetsManager = (function () {
  47030. function AssetsManager(scene) {
  47031. this._tasks = new Array();
  47032. this._waitingTasksCount = 0;
  47033. this.useDefaultLoadingScreen = true;
  47034. this._scene = scene;
  47035. }
  47036. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  47037. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  47038. this._tasks.push(task);
  47039. return task;
  47040. };
  47041. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  47042. var task = new TextFileAssetTask(taskName, url);
  47043. this._tasks.push(task);
  47044. return task;
  47045. };
  47046. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  47047. var task = new BinaryFileAssetTask(taskName, url);
  47048. this._tasks.push(task);
  47049. return task;
  47050. };
  47051. AssetsManager.prototype.addImageTask = function (taskName, url) {
  47052. var task = new ImageAssetTask(taskName, url);
  47053. this._tasks.push(task);
  47054. return task;
  47055. };
  47056. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  47057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47058. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  47059. this._tasks.push(task);
  47060. return task;
  47061. };
  47062. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  47063. this._waitingTasksCount--;
  47064. if (this._waitingTasksCount === 0) {
  47065. if (this.onFinish) {
  47066. this.onFinish(this._tasks);
  47067. }
  47068. this._scene.getEngine().hideLoadingUI();
  47069. }
  47070. };
  47071. AssetsManager.prototype._runTask = function (task) {
  47072. var _this = this;
  47073. task.run(this._scene, function () {
  47074. if (_this.onTaskSuccess) {
  47075. _this.onTaskSuccess(task);
  47076. }
  47077. _this._decreaseWaitingTasksCount();
  47078. }, function () {
  47079. if (_this.onTaskError) {
  47080. _this.onTaskError(task);
  47081. }
  47082. _this._decreaseWaitingTasksCount();
  47083. });
  47084. };
  47085. AssetsManager.prototype.reset = function () {
  47086. this._tasks = new Array();
  47087. return this;
  47088. };
  47089. AssetsManager.prototype.load = function () {
  47090. this._waitingTasksCount = this._tasks.length;
  47091. if (this._waitingTasksCount === 0) {
  47092. if (this.onFinish) {
  47093. this.onFinish(this._tasks);
  47094. }
  47095. return this;
  47096. }
  47097. if (this.useDefaultLoadingScreen) {
  47098. this._scene.getEngine().displayLoadingUI();
  47099. }
  47100. for (var index = 0; index < this._tasks.length; index++) {
  47101. var task = this._tasks[index];
  47102. this._runTask(task);
  47103. }
  47104. return this;
  47105. };
  47106. return AssetsManager;
  47107. })();
  47108. BABYLON.AssetsManager = AssetsManager;
  47109. })(BABYLON || (BABYLON = {}));
  47110. var BABYLON;
  47111. (function (BABYLON) {
  47112. var VRCameraMetrics = (function () {
  47113. function VRCameraMetrics() {
  47114. this.compensateDistortion = true;
  47115. }
  47116. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  47117. get: function () {
  47118. return this.hResolution / (2 * this.vResolution);
  47119. },
  47120. enumerable: true,
  47121. configurable: true
  47122. });
  47123. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  47124. get: function () {
  47125. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  47126. },
  47127. enumerable: true,
  47128. configurable: true
  47129. });
  47130. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  47131. get: function () {
  47132. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47133. var h = (4 * meters) / this.hScreenSize;
  47134. return BABYLON.Matrix.Translation(h, 0, 0);
  47135. },
  47136. enumerable: true,
  47137. configurable: true
  47138. });
  47139. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  47140. get: function () {
  47141. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47142. var h = (4 * meters) / this.hScreenSize;
  47143. return BABYLON.Matrix.Translation(-h, 0, 0);
  47144. },
  47145. enumerable: true,
  47146. configurable: true
  47147. });
  47148. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  47149. get: function () {
  47150. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  47151. },
  47152. enumerable: true,
  47153. configurable: true
  47154. });
  47155. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  47156. get: function () {
  47157. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  47158. },
  47159. enumerable: true,
  47160. configurable: true
  47161. });
  47162. VRCameraMetrics.GetDefault = function () {
  47163. var result = new VRCameraMetrics();
  47164. result.hResolution = 1280;
  47165. result.vResolution = 800;
  47166. result.hScreenSize = 0.149759993;
  47167. result.vScreenSize = 0.0935999975;
  47168. result.vScreenCenter = 0.0467999987,
  47169. result.eyeToScreenDistance = 0.0410000011;
  47170. result.lensSeparationDistance = 0.0635000020;
  47171. result.interpupillaryDistance = 0.0640000030;
  47172. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  47173. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  47174. result.postProcessScaleFactor = 1.714605507808412;
  47175. result.lensCenterOffset = 0.151976421;
  47176. return result;
  47177. };
  47178. return VRCameraMetrics;
  47179. })();
  47180. BABYLON.VRCameraMetrics = VRCameraMetrics;
  47181. })(BABYLON || (BABYLON = {}));
  47182. var BABYLON;
  47183. (function (BABYLON) {
  47184. var VRDeviceOrientationFreeCamera = (function (_super) {
  47185. __extends(VRDeviceOrientationFreeCamera, _super);
  47186. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  47187. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47188. _super.call(this, name, position, scene);
  47189. this.rotationQuaternion = new BABYLON.Quaternion();
  47190. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  47191. metrics.compensateDistortion = compensateDistortion;
  47192. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  47193. this.inputs.addDeviceOrientation();
  47194. }
  47195. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  47196. return "VRDeviceOrientationFreeCamera";
  47197. };
  47198. return VRDeviceOrientationFreeCamera;
  47199. })(BABYLON.FreeCamera);
  47200. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  47201. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  47202. __extends(VRDeviceOrientationArcRotateCamera, _super);
  47203. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  47204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47205. _super.call(this, name, alpha, beta, radius, target, scene);
  47206. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  47207. metrics.compensateDistortion = compensateDistortion;
  47208. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  47209. this.inputs.addVRDeviceOrientation();
  47210. }
  47211. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  47212. return "VRDeviceOrientationArcRotateCamera";
  47213. };
  47214. return VRDeviceOrientationArcRotateCamera;
  47215. })(BABYLON.ArcRotateCamera);
  47216. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  47217. })(BABYLON || (BABYLON = {}));
  47218. var BABYLON;
  47219. (function (BABYLON) {
  47220. var WebVRFreeCamera = (function (_super) {
  47221. __extends(WebVRFreeCamera, _super);
  47222. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  47223. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47224. _super.call(this, name, position, scene);
  47225. this._hmdDevice = null;
  47226. this._sensorDevice = null;
  47227. this._cacheState = null;
  47228. this._vrEnabled = false;
  47229. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  47230. metrics.compensateDistortion = compensateDistortion;
  47231. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  47232. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  47233. this.rotationQuaternion = new BABYLON.Quaternion();
  47234. }
  47235. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  47236. var size = devices.length;
  47237. var i = 0;
  47238. // Reset devices.
  47239. this._sensorDevice = null;
  47240. this._hmdDevice = null;
  47241. // Search for a HmdDevice.
  47242. while (i < size && this._hmdDevice === null) {
  47243. if (devices[i] instanceof HMDVRDevice) {
  47244. this._hmdDevice = devices[i];
  47245. }
  47246. i++;
  47247. }
  47248. i = 0;
  47249. while (i < size && this._sensorDevice === null) {
  47250. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  47251. this._sensorDevice = devices[i];
  47252. }
  47253. i++;
  47254. }
  47255. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  47256. };
  47257. WebVRFreeCamera.prototype._checkInputs = function () {
  47258. if (this._vrEnabled) {
  47259. this._cacheState = this._sensorDevice.getState();
  47260. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  47261. //Flip in XY plane
  47262. this.rotationQuaternion.z *= -1;
  47263. this.rotationQuaternion.w *= -1;
  47264. }
  47265. _super.prototype._checkInputs.call(this);
  47266. };
  47267. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47268. _super.prototype.attachControl.call(this, element, noPreventDefault);
  47269. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47270. if (navigator.getVRDevices) {
  47271. navigator.getVRDevices().then(this._getWebVRDevices);
  47272. }
  47273. else if (navigator.mozGetVRDevices) {
  47274. navigator.mozGetVRDevices(this._getWebVRDevices);
  47275. }
  47276. };
  47277. WebVRFreeCamera.prototype.detachControl = function (element) {
  47278. _super.prototype.detachControl.call(this, element);
  47279. this._vrEnabled = false;
  47280. };
  47281. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  47282. if (!this._hmdDevice)
  47283. return;
  47284. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  47285. };
  47286. WebVRFreeCamera.prototype.getTypeName = function () {
  47287. return "WebVRFreeCamera";
  47288. };
  47289. return WebVRFreeCamera;
  47290. })(BABYLON.FreeCamera);
  47291. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  47292. })(BABYLON || (BABYLON = {}));
  47293. var BABYLON;
  47294. (function (BABYLON) {
  47295. // Standard optimizations
  47296. var SceneOptimization = (function () {
  47297. function SceneOptimization(priority) {
  47298. if (priority === void 0) { priority = 0; }
  47299. this.priority = priority;
  47300. this.apply = function (scene) {
  47301. return true; // Return true if everything that can be done was applied
  47302. };
  47303. }
  47304. return SceneOptimization;
  47305. })();
  47306. BABYLON.SceneOptimization = SceneOptimization;
  47307. var TextureOptimization = (function (_super) {
  47308. __extends(TextureOptimization, _super);
  47309. function TextureOptimization(priority, maximumSize) {
  47310. var _this = this;
  47311. if (priority === void 0) { priority = 0; }
  47312. if (maximumSize === void 0) { maximumSize = 1024; }
  47313. _super.call(this, priority);
  47314. this.priority = priority;
  47315. this.maximumSize = maximumSize;
  47316. this.apply = function (scene) {
  47317. var allDone = true;
  47318. for (var index = 0; index < scene.textures.length; index++) {
  47319. var texture = scene.textures[index];
  47320. if (!texture.canRescale) {
  47321. continue;
  47322. }
  47323. var currentSize = texture.getSize();
  47324. var maxDimension = Math.max(currentSize.width, currentSize.height);
  47325. if (maxDimension > _this.maximumSize) {
  47326. texture.scale(0.5);
  47327. allDone = false;
  47328. }
  47329. }
  47330. return allDone;
  47331. };
  47332. }
  47333. return TextureOptimization;
  47334. })(SceneOptimization);
  47335. BABYLON.TextureOptimization = TextureOptimization;
  47336. var HardwareScalingOptimization = (function (_super) {
  47337. __extends(HardwareScalingOptimization, _super);
  47338. function HardwareScalingOptimization(priority, maximumScale) {
  47339. var _this = this;
  47340. if (priority === void 0) { priority = 0; }
  47341. if (maximumScale === void 0) { maximumScale = 2; }
  47342. _super.call(this, priority);
  47343. this.priority = priority;
  47344. this.maximumScale = maximumScale;
  47345. this._currentScale = 1;
  47346. this.apply = function (scene) {
  47347. _this._currentScale++;
  47348. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  47349. return _this._currentScale >= _this.maximumScale;
  47350. };
  47351. }
  47352. return HardwareScalingOptimization;
  47353. })(SceneOptimization);
  47354. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  47355. var ShadowsOptimization = (function (_super) {
  47356. __extends(ShadowsOptimization, _super);
  47357. function ShadowsOptimization() {
  47358. _super.apply(this, arguments);
  47359. this.apply = function (scene) {
  47360. scene.shadowsEnabled = false;
  47361. return true;
  47362. };
  47363. }
  47364. return ShadowsOptimization;
  47365. })(SceneOptimization);
  47366. BABYLON.ShadowsOptimization = ShadowsOptimization;
  47367. var PostProcessesOptimization = (function (_super) {
  47368. __extends(PostProcessesOptimization, _super);
  47369. function PostProcessesOptimization() {
  47370. _super.apply(this, arguments);
  47371. this.apply = function (scene) {
  47372. scene.postProcessesEnabled = false;
  47373. return true;
  47374. };
  47375. }
  47376. return PostProcessesOptimization;
  47377. })(SceneOptimization);
  47378. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  47379. var LensFlaresOptimization = (function (_super) {
  47380. __extends(LensFlaresOptimization, _super);
  47381. function LensFlaresOptimization() {
  47382. _super.apply(this, arguments);
  47383. this.apply = function (scene) {
  47384. scene.lensFlaresEnabled = false;
  47385. return true;
  47386. };
  47387. }
  47388. return LensFlaresOptimization;
  47389. })(SceneOptimization);
  47390. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  47391. var ParticlesOptimization = (function (_super) {
  47392. __extends(ParticlesOptimization, _super);
  47393. function ParticlesOptimization() {
  47394. _super.apply(this, arguments);
  47395. this.apply = function (scene) {
  47396. scene.particlesEnabled = false;
  47397. return true;
  47398. };
  47399. }
  47400. return ParticlesOptimization;
  47401. })(SceneOptimization);
  47402. BABYLON.ParticlesOptimization = ParticlesOptimization;
  47403. var RenderTargetsOptimization = (function (_super) {
  47404. __extends(RenderTargetsOptimization, _super);
  47405. function RenderTargetsOptimization() {
  47406. _super.apply(this, arguments);
  47407. this.apply = function (scene) {
  47408. scene.renderTargetsEnabled = false;
  47409. return true;
  47410. };
  47411. }
  47412. return RenderTargetsOptimization;
  47413. })(SceneOptimization);
  47414. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  47415. var MergeMeshesOptimization = (function (_super) {
  47416. __extends(MergeMeshesOptimization, _super);
  47417. function MergeMeshesOptimization() {
  47418. var _this = this;
  47419. _super.apply(this, arguments);
  47420. this._canBeMerged = function (abstractMesh) {
  47421. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  47422. return false;
  47423. }
  47424. var mesh = abstractMesh;
  47425. if (!mesh.isVisible || !mesh.isEnabled()) {
  47426. return false;
  47427. }
  47428. if (mesh.instances.length > 0) {
  47429. return false;
  47430. }
  47431. if (mesh.skeleton || mesh.hasLODLevels) {
  47432. return false;
  47433. }
  47434. if (mesh.parent) {
  47435. return false;
  47436. }
  47437. return true;
  47438. };
  47439. this.apply = function (scene, updateSelectionTree) {
  47440. var globalPool = scene.meshes.slice(0);
  47441. var globalLength = globalPool.length;
  47442. for (var index = 0; index < globalLength; index++) {
  47443. var currentPool = new Array();
  47444. var current = globalPool[index];
  47445. // Checks
  47446. if (!_this._canBeMerged(current)) {
  47447. continue;
  47448. }
  47449. currentPool.push(current);
  47450. // Find compatible meshes
  47451. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  47452. var otherMesh = globalPool[subIndex];
  47453. if (!_this._canBeMerged(otherMesh)) {
  47454. continue;
  47455. }
  47456. if (otherMesh.material !== current.material) {
  47457. continue;
  47458. }
  47459. if (otherMesh.checkCollisions !== current.checkCollisions) {
  47460. continue;
  47461. }
  47462. currentPool.push(otherMesh);
  47463. globalLength--;
  47464. globalPool.splice(subIndex, 1);
  47465. subIndex--;
  47466. }
  47467. if (currentPool.length < 2) {
  47468. continue;
  47469. }
  47470. // Merge meshes
  47471. BABYLON.Mesh.MergeMeshes(currentPool);
  47472. }
  47473. if (updateSelectionTree != undefined) {
  47474. if (updateSelectionTree) {
  47475. scene.createOrUpdateSelectionOctree();
  47476. }
  47477. }
  47478. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  47479. scene.createOrUpdateSelectionOctree();
  47480. }
  47481. return true;
  47482. };
  47483. }
  47484. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  47485. get: function () {
  47486. return MergeMeshesOptimization._UpdateSelectionTree;
  47487. },
  47488. set: function (value) {
  47489. MergeMeshesOptimization._UpdateSelectionTree = value;
  47490. },
  47491. enumerable: true,
  47492. configurable: true
  47493. });
  47494. MergeMeshesOptimization._UpdateSelectionTree = false;
  47495. return MergeMeshesOptimization;
  47496. })(SceneOptimization);
  47497. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  47498. // Options
  47499. var SceneOptimizerOptions = (function () {
  47500. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  47501. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  47502. if (trackerDuration === void 0) { trackerDuration = 2000; }
  47503. this.targetFrameRate = targetFrameRate;
  47504. this.trackerDuration = trackerDuration;
  47505. this.optimizations = new Array();
  47506. }
  47507. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  47508. var result = new SceneOptimizerOptions(targetFrameRate);
  47509. var priority = 0;
  47510. result.optimizations.push(new MergeMeshesOptimization(priority));
  47511. result.optimizations.push(new ShadowsOptimization(priority));
  47512. result.optimizations.push(new LensFlaresOptimization(priority));
  47513. // Next priority
  47514. priority++;
  47515. result.optimizations.push(new PostProcessesOptimization(priority));
  47516. result.optimizations.push(new ParticlesOptimization(priority));
  47517. // Next priority
  47518. priority++;
  47519. result.optimizations.push(new TextureOptimization(priority, 1024));
  47520. return result;
  47521. };
  47522. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  47523. var result = new SceneOptimizerOptions(targetFrameRate);
  47524. var priority = 0;
  47525. result.optimizations.push(new MergeMeshesOptimization(priority));
  47526. result.optimizations.push(new ShadowsOptimization(priority));
  47527. result.optimizations.push(new LensFlaresOptimization(priority));
  47528. // Next priority
  47529. priority++;
  47530. result.optimizations.push(new PostProcessesOptimization(priority));
  47531. result.optimizations.push(new ParticlesOptimization(priority));
  47532. // Next priority
  47533. priority++;
  47534. result.optimizations.push(new TextureOptimization(priority, 512));
  47535. // Next priority
  47536. priority++;
  47537. result.optimizations.push(new RenderTargetsOptimization(priority));
  47538. // Next priority
  47539. priority++;
  47540. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  47541. return result;
  47542. };
  47543. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  47544. var result = new SceneOptimizerOptions(targetFrameRate);
  47545. var priority = 0;
  47546. result.optimizations.push(new MergeMeshesOptimization(priority));
  47547. result.optimizations.push(new ShadowsOptimization(priority));
  47548. result.optimizations.push(new LensFlaresOptimization(priority));
  47549. // Next priority
  47550. priority++;
  47551. result.optimizations.push(new PostProcessesOptimization(priority));
  47552. result.optimizations.push(new ParticlesOptimization(priority));
  47553. // Next priority
  47554. priority++;
  47555. result.optimizations.push(new TextureOptimization(priority, 256));
  47556. // Next priority
  47557. priority++;
  47558. result.optimizations.push(new RenderTargetsOptimization(priority));
  47559. // Next priority
  47560. priority++;
  47561. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  47562. return result;
  47563. };
  47564. return SceneOptimizerOptions;
  47565. })();
  47566. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  47567. // Scene optimizer tool
  47568. var SceneOptimizer = (function () {
  47569. function SceneOptimizer() {
  47570. }
  47571. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  47572. // TODO: add an epsilon
  47573. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  47574. if (onSuccess) {
  47575. onSuccess();
  47576. }
  47577. return;
  47578. }
  47579. // Apply current level of optimizations
  47580. var allDone = true;
  47581. var noOptimizationApplied = true;
  47582. for (var index = 0; index < options.optimizations.length; index++) {
  47583. var optimization = options.optimizations[index];
  47584. if (optimization.priority === currentPriorityLevel) {
  47585. noOptimizationApplied = false;
  47586. allDone = allDone && optimization.apply(scene);
  47587. }
  47588. }
  47589. // If no optimization was applied, this is a failure :(
  47590. if (noOptimizationApplied) {
  47591. if (onFailure) {
  47592. onFailure();
  47593. }
  47594. return;
  47595. }
  47596. // If all optimizations were done, move to next level
  47597. if (allDone) {
  47598. currentPriorityLevel++;
  47599. }
  47600. // Let's the system running for a specific amount of time before checking FPS
  47601. scene.executeWhenReady(function () {
  47602. setTimeout(function () {
  47603. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  47604. }, options.trackerDuration);
  47605. });
  47606. };
  47607. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  47608. if (!options) {
  47609. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  47610. }
  47611. // Let's the system running for a specific amount of time before checking FPS
  47612. scene.executeWhenReady(function () {
  47613. setTimeout(function () {
  47614. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  47615. }, options.trackerDuration);
  47616. });
  47617. };
  47618. return SceneOptimizer;
  47619. })();
  47620. BABYLON.SceneOptimizer = SceneOptimizer;
  47621. })(BABYLON || (BABYLON = {}));
  47622. var BABYLON;
  47623. (function (BABYLON) {
  47624. var Internals;
  47625. (function (Internals) {
  47626. var MeshLODLevel = (function () {
  47627. function MeshLODLevel(distance, mesh) {
  47628. this.distance = distance;
  47629. this.mesh = mesh;
  47630. }
  47631. return MeshLODLevel;
  47632. })();
  47633. Internals.MeshLODLevel = MeshLODLevel;
  47634. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47635. })(BABYLON || (BABYLON = {}));
  47636. var BABYLON;
  47637. (function (BABYLON) {
  47638. var RawTexture = (function (_super) {
  47639. __extends(RawTexture, _super);
  47640. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  47641. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47642. if (invertY === void 0) { invertY = false; }
  47643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47644. _super.call(this, null, scene, !generateMipMaps, invertY);
  47645. this.format = format;
  47646. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  47647. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47648. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47649. }
  47650. RawTexture.prototype.update = function (data) {
  47651. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  47652. };
  47653. // Statics
  47654. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47655. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47656. if (invertY === void 0) { invertY = false; }
  47657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47658. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  47659. };
  47660. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47661. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47662. if (invertY === void 0) { invertY = false; }
  47663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47664. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47665. };
  47666. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47668. if (invertY === void 0) { invertY = false; }
  47669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47670. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47671. };
  47672. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47673. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47674. if (invertY === void 0) { invertY = false; }
  47675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47676. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  47677. };
  47678. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47680. if (invertY === void 0) { invertY = false; }
  47681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47682. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  47683. };
  47684. return RawTexture;
  47685. })(BABYLON.Texture);
  47686. BABYLON.RawTexture = RawTexture;
  47687. })(BABYLON || (BABYLON = {}));
  47688. var BABYLON;
  47689. (function (BABYLON) {
  47690. var IndexedVector2 = (function (_super) {
  47691. __extends(IndexedVector2, _super);
  47692. function IndexedVector2(original, index) {
  47693. _super.call(this, original.x, original.y);
  47694. this.index = index;
  47695. }
  47696. return IndexedVector2;
  47697. })(BABYLON.Vector2);
  47698. var PolygonPoints = (function () {
  47699. function PolygonPoints() {
  47700. this.elements = new Array();
  47701. }
  47702. PolygonPoints.prototype.add = function (originalPoints) {
  47703. var _this = this;
  47704. var result = new Array();
  47705. originalPoints.forEach(function (point) {
  47706. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  47707. var newPoint = new IndexedVector2(point, _this.elements.length);
  47708. result.push(newPoint);
  47709. _this.elements.push(newPoint);
  47710. }
  47711. });
  47712. return result;
  47713. };
  47714. PolygonPoints.prototype.computeBounds = function () {
  47715. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  47716. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  47717. this.elements.forEach(function (point) {
  47718. // x
  47719. if (point.x < lmin.x) {
  47720. lmin.x = point.x;
  47721. }
  47722. else if (point.x > lmax.x) {
  47723. lmax.x = point.x;
  47724. }
  47725. // y
  47726. if (point.y < lmin.y) {
  47727. lmin.y = point.y;
  47728. }
  47729. else if (point.y > lmax.y) {
  47730. lmax.y = point.y;
  47731. }
  47732. });
  47733. return {
  47734. min: lmin,
  47735. max: lmax,
  47736. width: lmax.x - lmin.x,
  47737. height: lmax.y - lmin.y
  47738. };
  47739. };
  47740. return PolygonPoints;
  47741. })();
  47742. var Polygon = (function () {
  47743. function Polygon() {
  47744. }
  47745. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  47746. return [
  47747. new BABYLON.Vector2(xmin, ymin),
  47748. new BABYLON.Vector2(xmax, ymin),
  47749. new BABYLON.Vector2(xmax, ymax),
  47750. new BABYLON.Vector2(xmin, ymax)
  47751. ];
  47752. };
  47753. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  47754. if (cx === void 0) { cx = 0; }
  47755. if (cy === void 0) { cy = 0; }
  47756. if (numberOfSides === void 0) { numberOfSides = 32; }
  47757. var result = new Array();
  47758. var angle = 0;
  47759. var increment = (Math.PI * 2) / numberOfSides;
  47760. for (var i = 0; i < numberOfSides; i++) {
  47761. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  47762. angle -= increment;
  47763. }
  47764. return result;
  47765. };
  47766. Polygon.Parse = function (input) {
  47767. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  47768. var i, result = [];
  47769. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  47770. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  47771. }
  47772. return result;
  47773. };
  47774. Polygon.StartingAt = function (x, y) {
  47775. return BABYLON.Path2.StartingAt(x, y);
  47776. };
  47777. return Polygon;
  47778. })();
  47779. BABYLON.Polygon = Polygon;
  47780. var PolygonMeshBuilder = (function () {
  47781. function PolygonMeshBuilder(name, contours, scene) {
  47782. this._points = new PolygonPoints();
  47783. this._outlinepoints = new PolygonPoints();
  47784. this._holes = [];
  47785. this._epoints = new Array();
  47786. this._eholes = new Array();
  47787. this._name = name;
  47788. this._scene = scene;
  47789. var points;
  47790. if (contours instanceof BABYLON.Path2) {
  47791. points = contours.getPoints();
  47792. }
  47793. else {
  47794. points = contours;
  47795. }
  47796. this._addToepoint(points);
  47797. this._points.add(points);
  47798. this._outlinepoints.add(points);
  47799. }
  47800. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  47801. for (var _i = 0; _i < points.length; _i++) {
  47802. var p = points[_i];
  47803. this._epoints.push(p.x, p.y);
  47804. }
  47805. };
  47806. PolygonMeshBuilder.prototype.addHole = function (hole) {
  47807. this._points.add(hole);
  47808. var holepoints = new PolygonPoints();
  47809. holepoints.add(hole);
  47810. this._holes.push(holepoints);
  47811. this._eholes.push(this._epoints.length / 2);
  47812. this._addToepoint(hole);
  47813. return this;
  47814. };
  47815. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  47816. var _this = this;
  47817. if (updatable === void 0) { updatable = false; }
  47818. var result = new BABYLON.Mesh(this._name, this._scene);
  47819. var normals = [];
  47820. var positions = [];
  47821. var uvs = [];
  47822. var bounds = this._points.computeBounds();
  47823. this._points.elements.forEach(function (p) {
  47824. normals.push(0, 1.0, 0);
  47825. positions.push(p.x, 0, p.y);
  47826. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  47827. });
  47828. var indices = [];
  47829. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  47830. for (var i = 0; i < res.length; i++) {
  47831. indices.push(res[i]);
  47832. }
  47833. if (depth > 0) {
  47834. var positionscount = (positions.length / 3); //get the current pointcount
  47835. this._points.elements.forEach(function (p) {
  47836. normals.push(0, -1.0, 0);
  47837. positions.push(p.x, -depth, p.y);
  47838. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  47839. });
  47840. var totalCount = indices.length;
  47841. for (var i = 0; i < totalCount; i += 3) {
  47842. var i0 = indices[i + 0];
  47843. var i1 = indices[i + 1];
  47844. var i2 = indices[i + 2];
  47845. indices.push(i2 + positionscount);
  47846. indices.push(i1 + positionscount);
  47847. indices.push(i0 + positionscount);
  47848. }
  47849. //Add the sides
  47850. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  47851. this._holes.forEach(function (hole) {
  47852. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  47853. });
  47854. }
  47855. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  47856. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  47857. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  47858. result.setIndices(indices);
  47859. return result;
  47860. };
  47861. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  47862. var StartIndex = positions.length / 3;
  47863. var ulength = 0;
  47864. for (var i = 0; i < points.elements.length; i++) {
  47865. var p = points.elements[i];
  47866. var p1;
  47867. if ((i + 1) > points.elements.length - 1) {
  47868. p1 = points.elements[0];
  47869. }
  47870. else {
  47871. p1 = points.elements[i + 1];
  47872. }
  47873. positions.push(p.x, 0, p.y);
  47874. positions.push(p.x, -depth, p.y);
  47875. positions.push(p1.x, 0, p1.y);
  47876. positions.push(p1.x, -depth, p1.y);
  47877. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  47878. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  47879. var v3 = v2.subtract(v1);
  47880. var v4 = new BABYLON.Vector3(0, 1, 0);
  47881. var vn = BABYLON.Vector3.Cross(v3, v4);
  47882. vn = vn.normalize();
  47883. uvs.push(ulength / bounds.width, 0);
  47884. uvs.push(ulength / bounds.width, 1);
  47885. ulength += v3.length();
  47886. uvs.push((ulength / bounds.width), 0);
  47887. uvs.push((ulength / bounds.width), 1);
  47888. if (!flip) {
  47889. normals.push(-vn.x, -vn.y, -vn.z);
  47890. normals.push(-vn.x, -vn.y, -vn.z);
  47891. normals.push(-vn.x, -vn.y, -vn.z);
  47892. normals.push(-vn.x, -vn.y, -vn.z);
  47893. indices.push(StartIndex);
  47894. indices.push(StartIndex + 1);
  47895. indices.push(StartIndex + 2);
  47896. indices.push(StartIndex + 1);
  47897. indices.push(StartIndex + 3);
  47898. indices.push(StartIndex + 2);
  47899. }
  47900. else {
  47901. normals.push(vn.x, vn.y, vn.z);
  47902. normals.push(vn.x, vn.y, vn.z);
  47903. normals.push(vn.x, vn.y, vn.z);
  47904. normals.push(vn.x, vn.y, vn.z);
  47905. indices.push(StartIndex);
  47906. indices.push(StartIndex + 2);
  47907. indices.push(StartIndex + 1);
  47908. indices.push(StartIndex + 1);
  47909. indices.push(StartIndex + 2);
  47910. indices.push(StartIndex + 3);
  47911. }
  47912. StartIndex += 4;
  47913. }
  47914. ;
  47915. };
  47916. return PolygonMeshBuilder;
  47917. })();
  47918. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  47919. })(BABYLON || (BABYLON = {}));
  47920. var BABYLON;
  47921. (function (BABYLON) {
  47922. var Octree = (function () {
  47923. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  47924. if (maxDepth === void 0) { maxDepth = 2; }
  47925. this.maxDepth = maxDepth;
  47926. this.dynamicContent = new Array();
  47927. this._maxBlockCapacity = maxBlockCapacity || 64;
  47928. this._selectionContent = new BABYLON.SmartArray(1024);
  47929. this._creationFunc = creationFunc;
  47930. }
  47931. // Methods
  47932. Octree.prototype.update = function (worldMin, worldMax, entries) {
  47933. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  47934. };
  47935. Octree.prototype.addMesh = function (entry) {
  47936. for (var index = 0; index < this.blocks.length; index++) {
  47937. var block = this.blocks[index];
  47938. block.addEntry(entry);
  47939. }
  47940. };
  47941. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  47942. this._selectionContent.reset();
  47943. for (var index = 0; index < this.blocks.length; index++) {
  47944. var block = this.blocks[index];
  47945. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  47946. }
  47947. if (allowDuplicate) {
  47948. this._selectionContent.concat(this.dynamicContent);
  47949. }
  47950. else {
  47951. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  47952. }
  47953. return this._selectionContent;
  47954. };
  47955. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  47956. this._selectionContent.reset();
  47957. for (var index = 0; index < this.blocks.length; index++) {
  47958. var block = this.blocks[index];
  47959. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  47960. }
  47961. if (allowDuplicate) {
  47962. this._selectionContent.concat(this.dynamicContent);
  47963. }
  47964. else {
  47965. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  47966. }
  47967. return this._selectionContent;
  47968. };
  47969. Octree.prototype.intersectsRay = function (ray) {
  47970. this._selectionContent.reset();
  47971. for (var index = 0; index < this.blocks.length; index++) {
  47972. var block = this.blocks[index];
  47973. block.intersectsRay(ray, this._selectionContent);
  47974. }
  47975. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  47976. return this._selectionContent;
  47977. };
  47978. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  47979. target.blocks = new Array();
  47980. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  47981. // Segmenting space
  47982. for (var x = 0; x < 2; x++) {
  47983. for (var y = 0; y < 2; y++) {
  47984. for (var z = 0; z < 2; z++) {
  47985. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  47986. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  47987. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  47988. block.addEntries(entries);
  47989. target.blocks.push(block);
  47990. }
  47991. }
  47992. }
  47993. };
  47994. Octree.CreationFuncForMeshes = function (entry, block) {
  47995. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  47996. block.entries.push(entry);
  47997. }
  47998. };
  47999. Octree.CreationFuncForSubMeshes = function (entry, block) {
  48000. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48001. block.entries.push(entry);
  48002. }
  48003. };
  48004. return Octree;
  48005. })();
  48006. BABYLON.Octree = Octree;
  48007. })(BABYLON || (BABYLON = {}));
  48008. var BABYLON;
  48009. (function (BABYLON) {
  48010. var OctreeBlock = (function () {
  48011. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  48012. this.entries = new Array();
  48013. this._boundingVectors = new Array();
  48014. this._capacity = capacity;
  48015. this._depth = depth;
  48016. this._maxDepth = maxDepth;
  48017. this._creationFunc = creationFunc;
  48018. this._minPoint = minPoint;
  48019. this._maxPoint = maxPoint;
  48020. this._boundingVectors.push(minPoint.clone());
  48021. this._boundingVectors.push(maxPoint.clone());
  48022. this._boundingVectors.push(minPoint.clone());
  48023. this._boundingVectors[2].x = maxPoint.x;
  48024. this._boundingVectors.push(minPoint.clone());
  48025. this._boundingVectors[3].y = maxPoint.y;
  48026. this._boundingVectors.push(minPoint.clone());
  48027. this._boundingVectors[4].z = maxPoint.z;
  48028. this._boundingVectors.push(maxPoint.clone());
  48029. this._boundingVectors[5].z = minPoint.z;
  48030. this._boundingVectors.push(maxPoint.clone());
  48031. this._boundingVectors[6].x = minPoint.x;
  48032. this._boundingVectors.push(maxPoint.clone());
  48033. this._boundingVectors[7].y = minPoint.y;
  48034. }
  48035. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  48036. // Property
  48037. get: function () {
  48038. return this._capacity;
  48039. },
  48040. enumerable: true,
  48041. configurable: true
  48042. });
  48043. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  48044. get: function () {
  48045. return this._minPoint;
  48046. },
  48047. enumerable: true,
  48048. configurable: true
  48049. });
  48050. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  48051. get: function () {
  48052. return this._maxPoint;
  48053. },
  48054. enumerable: true,
  48055. configurable: true
  48056. });
  48057. // Methods
  48058. OctreeBlock.prototype.addEntry = function (entry) {
  48059. if (this.blocks) {
  48060. for (var index = 0; index < this.blocks.length; index++) {
  48061. var block = this.blocks[index];
  48062. block.addEntry(entry);
  48063. }
  48064. return;
  48065. }
  48066. this._creationFunc(entry, this);
  48067. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  48068. this.createInnerBlocks();
  48069. }
  48070. };
  48071. OctreeBlock.prototype.addEntries = function (entries) {
  48072. for (var index = 0; index < entries.length; index++) {
  48073. var mesh = entries[index];
  48074. this.addEntry(mesh);
  48075. }
  48076. };
  48077. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  48078. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  48079. if (this.blocks) {
  48080. for (var index = 0; index < this.blocks.length; index++) {
  48081. var block = this.blocks[index];
  48082. block.select(frustumPlanes, selection, allowDuplicate);
  48083. }
  48084. return;
  48085. }
  48086. if (allowDuplicate) {
  48087. selection.concat(this.entries);
  48088. }
  48089. else {
  48090. selection.concatWithNoDuplicate(this.entries);
  48091. }
  48092. }
  48093. };
  48094. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  48095. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  48096. if (this.blocks) {
  48097. for (var index = 0; index < this.blocks.length; index++) {
  48098. var block = this.blocks[index];
  48099. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  48100. }
  48101. return;
  48102. }
  48103. if (allowDuplicate) {
  48104. selection.concat(this.entries);
  48105. }
  48106. else {
  48107. selection.concatWithNoDuplicate(this.entries);
  48108. }
  48109. }
  48110. };
  48111. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  48112. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  48113. if (this.blocks) {
  48114. for (var index = 0; index < this.blocks.length; index++) {
  48115. var block = this.blocks[index];
  48116. block.intersectsRay(ray, selection);
  48117. }
  48118. return;
  48119. }
  48120. selection.concatWithNoDuplicate(this.entries);
  48121. }
  48122. };
  48123. OctreeBlock.prototype.createInnerBlocks = function () {
  48124. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  48125. };
  48126. return OctreeBlock;
  48127. })();
  48128. BABYLON.OctreeBlock = OctreeBlock;
  48129. })(BABYLON || (BABYLON = {}));
  48130. var BABYLON;
  48131. (function (BABYLON) {
  48132. var BlurPostProcess = (function (_super) {
  48133. __extends(BlurPostProcess, _super);
  48134. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48135. var _this = this;
  48136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48137. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  48138. this.direction = direction;
  48139. this.blurWidth = blurWidth;
  48140. this.onApplyObservable.add(function (effect) {
  48141. effect.setFloat2("screenSize", _this.width, _this.height);
  48142. effect.setVector2("direction", _this.direction);
  48143. effect.setFloat("blurWidth", _this.blurWidth);
  48144. });
  48145. }
  48146. return BlurPostProcess;
  48147. })(BABYLON.PostProcess);
  48148. BABYLON.BlurPostProcess = BlurPostProcess;
  48149. })(BABYLON || (BABYLON = {}));
  48150. var BABYLON;
  48151. (function (BABYLON) {
  48152. var RefractionPostProcess = (function (_super) {
  48153. __extends(RefractionPostProcess, _super);
  48154. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48155. var _this = this;
  48156. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  48157. this.color = color;
  48158. this.depth = depth;
  48159. this.colorLevel = colorLevel;
  48160. this.onActivateObservable.add(function (cam) {
  48161. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48162. });
  48163. this.onApplyObservable.add(function (effect) {
  48164. effect.setColor3("baseColor", _this.color);
  48165. effect.setFloat("depth", _this.depth);
  48166. effect.setFloat("colorLevel", _this.colorLevel);
  48167. effect.setTexture("refractionSampler", _this._refRexture);
  48168. });
  48169. }
  48170. // Methods
  48171. RefractionPostProcess.prototype.dispose = function (camera) {
  48172. if (this._refRexture) {
  48173. this._refRexture.dispose();
  48174. }
  48175. _super.prototype.dispose.call(this, camera);
  48176. };
  48177. return RefractionPostProcess;
  48178. })(BABYLON.PostProcess);
  48179. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48180. })(BABYLON || (BABYLON = {}));
  48181. var BABYLON;
  48182. (function (BABYLON) {
  48183. var BlackAndWhitePostProcess = (function (_super) {
  48184. __extends(BlackAndWhitePostProcess, _super);
  48185. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48186. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  48187. }
  48188. return BlackAndWhitePostProcess;
  48189. })(BABYLON.PostProcess);
  48190. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48191. })(BABYLON || (BABYLON = {}));
  48192. var BABYLON;
  48193. (function (BABYLON) {
  48194. var ConvolutionPostProcess = (function (_super) {
  48195. __extends(ConvolutionPostProcess, _super);
  48196. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48197. var _this = this;
  48198. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  48199. this.kernel = kernel;
  48200. this.onApply = function (effect) {
  48201. effect.setFloat2("screenSize", _this.width, _this.height);
  48202. effect.setArray("kernel", _this.kernel);
  48203. };
  48204. }
  48205. // Statics
  48206. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48207. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48208. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48209. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48210. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48211. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48212. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48213. return ConvolutionPostProcess;
  48214. })(BABYLON.PostProcess);
  48215. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48216. })(BABYLON || (BABYLON = {}));
  48217. var BABYLON;
  48218. (function (BABYLON) {
  48219. var FilterPostProcess = (function (_super) {
  48220. __extends(FilterPostProcess, _super);
  48221. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48222. var _this = this;
  48223. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  48224. this.kernelMatrix = kernelMatrix;
  48225. this.onApply = function (effect) {
  48226. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48227. };
  48228. }
  48229. return FilterPostProcess;
  48230. })(BABYLON.PostProcess);
  48231. BABYLON.FilterPostProcess = FilterPostProcess;
  48232. })(BABYLON || (BABYLON = {}));
  48233. var BABYLON;
  48234. (function (BABYLON) {
  48235. var FxaaPostProcess = (function (_super) {
  48236. __extends(FxaaPostProcess, _super);
  48237. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48238. var _this = this;
  48239. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  48240. this.onSizeChangedObservable.add(function () {
  48241. _this.texelWidth = 1.0 / _this.width;
  48242. _this.texelHeight = 1.0 / _this.height;
  48243. });
  48244. this.onApplyObservable.add(function (effect) {
  48245. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48246. });
  48247. }
  48248. return FxaaPostProcess;
  48249. })(BABYLON.PostProcess);
  48250. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48251. })(BABYLON || (BABYLON = {}));
  48252. var BABYLON;
  48253. (function (BABYLON) {
  48254. var StereoscopicInterlacePostProcess = (function (_super) {
  48255. __extends(StereoscopicInterlacePostProcess, _super);
  48256. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  48257. var _this = this;
  48258. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  48259. this._passedProcess = rigCameras[0]._rigPostProcess;
  48260. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  48261. this.onSizeChangedObservable.add(function () {
  48262. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  48263. });
  48264. this.onApplyObservable.add(function (effect) {
  48265. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  48266. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  48267. });
  48268. }
  48269. return StereoscopicInterlacePostProcess;
  48270. })(BABYLON.PostProcess);
  48271. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  48272. })(BABYLON || (BABYLON = {}));
  48273. var BABYLON;
  48274. (function (BABYLON) {
  48275. var LensFlare = (function () {
  48276. function LensFlare(size, position, color, imgUrl, system) {
  48277. this.size = size;
  48278. this.position = position;
  48279. this.dispose = function () {
  48280. if (this.texture) {
  48281. this.texture.dispose();
  48282. }
  48283. // Remove from scene
  48284. var index = this._system.lensFlares.indexOf(this);
  48285. this._system.lensFlares.splice(index, 1);
  48286. };
  48287. this.color = color || new BABYLON.Color3(1, 1, 1);
  48288. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  48289. this._system = system;
  48290. system.lensFlares.push(this);
  48291. }
  48292. return LensFlare;
  48293. })();
  48294. BABYLON.LensFlare = LensFlare;
  48295. })(BABYLON || (BABYLON = {}));
  48296. var BABYLON;
  48297. (function (BABYLON) {
  48298. var LensFlareSystem = (function () {
  48299. function LensFlareSystem(name, emitter, scene) {
  48300. this.name = name;
  48301. this.lensFlares = new Array();
  48302. this.borderLimit = 300;
  48303. this.layerMask = 0x0FFFFFFF;
  48304. this._vertexBuffers = {};
  48305. this._isEnabled = true;
  48306. this._scene = scene;
  48307. this._emitter = emitter;
  48308. this.id = name;
  48309. scene.lensFlareSystems.push(this);
  48310. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  48311. var engine = scene.getEngine();
  48312. // VBO
  48313. var vertices = [];
  48314. vertices.push(1, 1);
  48315. vertices.push(-1, 1);
  48316. vertices.push(-1, -1);
  48317. vertices.push(1, -1);
  48318. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  48319. // Indices
  48320. var indices = [];
  48321. indices.push(0);
  48322. indices.push(1);
  48323. indices.push(2);
  48324. indices.push(0);
  48325. indices.push(2);
  48326. indices.push(3);
  48327. this._indexBuffer = engine.createIndexBuffer(indices);
  48328. // Effects
  48329. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  48330. }
  48331. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  48332. get: function () {
  48333. return this._isEnabled;
  48334. },
  48335. set: function (value) {
  48336. this._isEnabled = value;
  48337. },
  48338. enumerable: true,
  48339. configurable: true
  48340. });
  48341. LensFlareSystem.prototype.getScene = function () {
  48342. return this._scene;
  48343. };
  48344. LensFlareSystem.prototype.getEmitter = function () {
  48345. return this._emitter;
  48346. };
  48347. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  48348. this._emitter = newEmitter;
  48349. };
  48350. LensFlareSystem.prototype.getEmitterPosition = function () {
  48351. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  48352. };
  48353. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  48354. var position = this.getEmitterPosition();
  48355. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  48356. this._positionX = position.x;
  48357. this._positionY = position.y;
  48358. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  48359. if (position.z > 0) {
  48360. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  48361. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  48362. return true;
  48363. }
  48364. }
  48365. return false;
  48366. };
  48367. LensFlareSystem.prototype._isVisible = function () {
  48368. if (!this._isEnabled) {
  48369. return false;
  48370. }
  48371. var emitterPosition = this.getEmitterPosition();
  48372. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  48373. var distance = direction.length();
  48374. direction.normalize();
  48375. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  48376. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  48377. return !pickInfo.hit || pickInfo.distance > distance;
  48378. };
  48379. LensFlareSystem.prototype.render = function () {
  48380. if (!this._effect.isReady())
  48381. return false;
  48382. var engine = this._scene.getEngine();
  48383. var viewport = this._scene.activeCamera.viewport;
  48384. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  48385. // Position
  48386. if (!this.computeEffectivePosition(globalViewport)) {
  48387. return false;
  48388. }
  48389. // Visibility
  48390. if (!this._isVisible()) {
  48391. return false;
  48392. }
  48393. // Intensity
  48394. var awayX;
  48395. var awayY;
  48396. if (this._positionX < this.borderLimit + globalViewport.x) {
  48397. awayX = this.borderLimit + globalViewport.x - this._positionX;
  48398. }
  48399. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  48400. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  48401. }
  48402. else {
  48403. awayX = 0;
  48404. }
  48405. if (this._positionY < this.borderLimit + globalViewport.y) {
  48406. awayY = this.borderLimit + globalViewport.y - this._positionY;
  48407. }
  48408. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  48409. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  48410. }
  48411. else {
  48412. awayY = 0;
  48413. }
  48414. var away = (awayX > awayY) ? awayX : awayY;
  48415. if (away > this.borderLimit) {
  48416. away = this.borderLimit;
  48417. }
  48418. var intensity = 1.0 - (away / this.borderLimit);
  48419. if (intensity < 0) {
  48420. return false;
  48421. }
  48422. if (intensity > 1.0) {
  48423. intensity = 1.0;
  48424. }
  48425. // Position
  48426. var centerX = globalViewport.x + globalViewport.width / 2;
  48427. var centerY = globalViewport.y + globalViewport.height / 2;
  48428. var distX = centerX - this._positionX;
  48429. var distY = centerY - this._positionY;
  48430. // Effects
  48431. engine.enableEffect(this._effect);
  48432. engine.setState(false);
  48433. engine.setDepthBuffer(false);
  48434. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48435. // VBOs
  48436. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  48437. // Flares
  48438. for (var index = 0; index < this.lensFlares.length; index++) {
  48439. var flare = this.lensFlares[index];
  48440. var x = centerX - (distX * flare.position);
  48441. var y = centerY - (distY * flare.position);
  48442. var cw = flare.size;
  48443. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  48444. var cx = 2 * (x / globalViewport.width) - 1.0;
  48445. var cy = 1.0 - 2 * (y / globalViewport.height);
  48446. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  48447. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  48448. // Texture
  48449. this._effect.setTexture("textureSampler", flare.texture);
  48450. // Color
  48451. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  48452. // Draw order
  48453. engine.draw(true, 0, 6);
  48454. }
  48455. engine.setDepthBuffer(true);
  48456. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48457. return true;
  48458. };
  48459. LensFlareSystem.prototype.dispose = function () {
  48460. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  48461. if (vertexBuffer) {
  48462. vertexBuffer.dispose();
  48463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  48464. }
  48465. if (this._indexBuffer) {
  48466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48467. this._indexBuffer = null;
  48468. }
  48469. while (this.lensFlares.length) {
  48470. this.lensFlares[0].dispose();
  48471. }
  48472. // Remove from scene
  48473. var index = this._scene.lensFlareSystems.indexOf(this);
  48474. this._scene.lensFlareSystems.splice(index, 1);
  48475. };
  48476. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  48477. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  48478. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  48479. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  48480. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  48481. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  48482. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  48483. var parsedFlare = parsedLensFlareSystem.flares[index];
  48484. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  48485. }
  48486. return lensFlareSystem;
  48487. };
  48488. LensFlareSystem.prototype.serialize = function () {
  48489. var serializationObject = {};
  48490. serializationObject.id = this.id;
  48491. serializationObject.name = this.name;
  48492. serializationObject.emitterId = this.getEmitter().id;
  48493. serializationObject.borderLimit = this.borderLimit;
  48494. serializationObject.flares = [];
  48495. for (var index = 0; index < this.lensFlares.length; index++) {
  48496. var flare = this.lensFlares[index];
  48497. serializationObject.flares.push({
  48498. size: flare.size,
  48499. position: flare.position,
  48500. color: flare.color.asArray(),
  48501. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  48502. });
  48503. }
  48504. return serializationObject;
  48505. };
  48506. return LensFlareSystem;
  48507. })();
  48508. BABYLON.LensFlareSystem = LensFlareSystem;
  48509. })(BABYLON || (BABYLON = {}));
  48510. var BABYLON;
  48511. (function (BABYLON) {
  48512. // We're mainly based on the logic defined into the FreeCamera code
  48513. var DeviceOrientationCamera = (function (_super) {
  48514. __extends(DeviceOrientationCamera, _super);
  48515. //-- end properties for backward compatibility for inputs
  48516. function DeviceOrientationCamera(name, position, scene) {
  48517. _super.call(this, name, position, scene);
  48518. this.inputs.addDeviceOrientation();
  48519. }
  48520. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  48521. //-- Begin properties for backward compatibility for inputs
  48522. get: function () {
  48523. return 0;
  48524. },
  48525. set: function (value) {
  48526. },
  48527. enumerable: true,
  48528. configurable: true
  48529. });
  48530. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  48531. get: function () {
  48532. return 0;
  48533. },
  48534. set: function (value) {
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. DeviceOrientationCamera.prototype.getTypeName = function () {
  48540. return "DeviceOrientationCamera";
  48541. };
  48542. return DeviceOrientationCamera;
  48543. })(BABYLON.FreeCamera);
  48544. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  48545. })(BABYLON || (BABYLON = {}));
  48546. var BABYLON;
  48547. (function (BABYLON) {
  48548. // We're mainly based on the logic defined into the FreeCamera code
  48549. var UniversalCamera = (function (_super) {
  48550. __extends(UniversalCamera, _super);
  48551. //-- end properties for backward compatibility for inputs
  48552. function UniversalCamera(name, position, scene) {
  48553. _super.call(this, name, position, scene);
  48554. this.inputs.addGamepad();
  48555. }
  48556. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  48557. //-- Begin properties for backward compatibility for inputs
  48558. get: function () {
  48559. var gamepad = this.inputs.attached["gamepad"];
  48560. if (gamepad)
  48561. return gamepad.gamepadAngularSensibility;
  48562. },
  48563. set: function (value) {
  48564. var gamepad = this.inputs.attached["gamepad"];
  48565. if (gamepad)
  48566. gamepad.gamepadAngularSensibility = value;
  48567. },
  48568. enumerable: true,
  48569. configurable: true
  48570. });
  48571. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  48572. get: function () {
  48573. var gamepad = this.inputs.attached["gamepad"];
  48574. if (gamepad)
  48575. return gamepad.gamepadMoveSensibility;
  48576. },
  48577. set: function (value) {
  48578. var gamepad = this.inputs.attached["gamepad"];
  48579. if (gamepad)
  48580. gamepad.gamepadMoveSensibility = value;
  48581. },
  48582. enumerable: true,
  48583. configurable: true
  48584. });
  48585. UniversalCamera.prototype.getTypeName = function () {
  48586. return "UniversalCamera";
  48587. };
  48588. return UniversalCamera;
  48589. })(BABYLON.TouchCamera);
  48590. BABYLON.UniversalCamera = UniversalCamera;
  48591. })(BABYLON || (BABYLON = {}));
  48592. var BABYLON;
  48593. (function (BABYLON) {
  48594. var Gamepads = (function () {
  48595. function Gamepads(ongamedpadconnected) {
  48596. var _this = this;
  48597. this.babylonGamepads = [];
  48598. this.oneGamepadConnected = false;
  48599. this.isMonitoring = false;
  48600. this.gamepadEventSupported = 'GamepadEvent' in window;
  48601. this.gamepadSupportAvailable = (navigator.getGamepads ||
  48602. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  48603. this._callbackGamepadConnected = ongamedpadconnected;
  48604. if (this.gamepadSupportAvailable) {
  48605. // Checking if the gamepad connected event is supported (like in Firefox)
  48606. if (this.gamepadEventSupported) {
  48607. this._onGamepadConnectedEvent = function (evt) {
  48608. _this._onGamepadConnected(evt);
  48609. };
  48610. this._onGamepadDisonnectedEvent = function (evt) {
  48611. _this._onGamepadDisconnected(evt);
  48612. };
  48613. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48614. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48615. }
  48616. else {
  48617. this._startMonitoringGamepads();
  48618. }
  48619. }
  48620. }
  48621. Gamepads.prototype.dispose = function () {
  48622. if (Gamepads.gamepadDOMInfo) {
  48623. document.body.removeChild(Gamepads.gamepadDOMInfo);
  48624. }
  48625. if (this._onGamepadConnectedEvent) {
  48626. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  48627. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  48628. this._onGamepadConnectedEvent = null;
  48629. this._onGamepadDisonnectedEvent = null;
  48630. }
  48631. };
  48632. Gamepads.prototype._onGamepadConnected = function (evt) {
  48633. var newGamepad = this._addNewGamepad(evt.gamepad);
  48634. if (this._callbackGamepadConnected)
  48635. this._callbackGamepadConnected(newGamepad);
  48636. this._startMonitoringGamepads();
  48637. };
  48638. Gamepads.prototype._addNewGamepad = function (gamepad) {
  48639. if (!this.oneGamepadConnected) {
  48640. this.oneGamepadConnected = true;
  48641. if (Gamepads.gamepadDOMInfo) {
  48642. document.body.removeChild(Gamepads.gamepadDOMInfo);
  48643. Gamepads.gamepadDOMInfo = null;
  48644. }
  48645. }
  48646. var newGamepad;
  48647. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  48648. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  48649. }
  48650. else {
  48651. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  48652. }
  48653. this.babylonGamepads.push(newGamepad);
  48654. return newGamepad;
  48655. };
  48656. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  48657. // Remove the gamepad from the list of gamepads to monitor.
  48658. for (var i in this.babylonGamepads) {
  48659. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  48660. this.babylonGamepads.splice(+i, 1);
  48661. break;
  48662. }
  48663. }
  48664. // If no gamepads are left, stop the polling loop.
  48665. if (this.babylonGamepads.length == 0) {
  48666. this._stopMonitoringGamepads();
  48667. }
  48668. };
  48669. Gamepads.prototype._startMonitoringGamepads = function () {
  48670. if (!this.isMonitoring) {
  48671. this.isMonitoring = true;
  48672. this._checkGamepadsStatus();
  48673. }
  48674. };
  48675. Gamepads.prototype._stopMonitoringGamepads = function () {
  48676. this.isMonitoring = false;
  48677. };
  48678. Gamepads.prototype._checkGamepadsStatus = function () {
  48679. var _this = this;
  48680. // updating gamepad objects
  48681. this._updateGamepadObjects();
  48682. for (var i in this.babylonGamepads) {
  48683. this.babylonGamepads[i].update();
  48684. }
  48685. if (this.isMonitoring) {
  48686. if (window.requestAnimationFrame) {
  48687. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48688. }
  48689. else if (window.mozRequestAnimationFrame) {
  48690. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48691. }
  48692. else if (window.webkitRequestAnimationFrame) {
  48693. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  48694. }
  48695. }
  48696. };
  48697. // This function is called only on Chrome, which does not yet support
  48698. // connection/disconnection events, but requires you to monitor
  48699. // an array for changes.
  48700. Gamepads.prototype._updateGamepadObjects = function () {
  48701. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  48702. for (var i = 0; i < gamepads.length; i++) {
  48703. if (gamepads[i]) {
  48704. if (!(gamepads[i].index in this.babylonGamepads)) {
  48705. var newGamepad = this._addNewGamepad(gamepads[i]);
  48706. if (this._callbackGamepadConnected) {
  48707. this._callbackGamepadConnected(newGamepad);
  48708. }
  48709. }
  48710. else {
  48711. this.babylonGamepads[i].browserGamepad = gamepads[i];
  48712. }
  48713. }
  48714. }
  48715. };
  48716. return Gamepads;
  48717. })();
  48718. BABYLON.Gamepads = Gamepads;
  48719. var StickValues = (function () {
  48720. function StickValues(x, y) {
  48721. this.x = x;
  48722. this.y = y;
  48723. }
  48724. return StickValues;
  48725. })();
  48726. BABYLON.StickValues = StickValues;
  48727. var Gamepad = (function () {
  48728. function Gamepad(id, index, browserGamepad) {
  48729. this.id = id;
  48730. this.index = index;
  48731. this.browserGamepad = browserGamepad;
  48732. if (this.browserGamepad.axes.length >= 2) {
  48733. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  48734. }
  48735. if (this.browserGamepad.axes.length >= 4) {
  48736. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  48737. }
  48738. }
  48739. Gamepad.prototype.onleftstickchanged = function (callback) {
  48740. this._onleftstickchanged = callback;
  48741. };
  48742. Gamepad.prototype.onrightstickchanged = function (callback) {
  48743. this._onrightstickchanged = callback;
  48744. };
  48745. Object.defineProperty(Gamepad.prototype, "leftStick", {
  48746. get: function () {
  48747. return this._leftStick;
  48748. },
  48749. set: function (newValues) {
  48750. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  48751. this._onleftstickchanged(newValues);
  48752. }
  48753. this._leftStick = newValues;
  48754. },
  48755. enumerable: true,
  48756. configurable: true
  48757. });
  48758. Object.defineProperty(Gamepad.prototype, "rightStick", {
  48759. get: function () {
  48760. return this._rightStick;
  48761. },
  48762. set: function (newValues) {
  48763. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  48764. this._onrightstickchanged(newValues);
  48765. }
  48766. this._rightStick = newValues;
  48767. },
  48768. enumerable: true,
  48769. configurable: true
  48770. });
  48771. Gamepad.prototype.update = function () {
  48772. if (this._leftStick) {
  48773. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  48774. }
  48775. if (this._rightStick) {
  48776. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  48777. }
  48778. };
  48779. return Gamepad;
  48780. })();
  48781. BABYLON.Gamepad = Gamepad;
  48782. var GenericPad = (function (_super) {
  48783. __extends(GenericPad, _super);
  48784. function GenericPad(id, index, gamepad) {
  48785. _super.call(this, id, index, gamepad);
  48786. this.id = id;
  48787. this.index = index;
  48788. this.gamepad = gamepad;
  48789. this._buttons = new Array(gamepad.buttons.length);
  48790. }
  48791. GenericPad.prototype.onbuttondown = function (callback) {
  48792. this._onbuttondown = callback;
  48793. };
  48794. GenericPad.prototype.onbuttonup = function (callback) {
  48795. this._onbuttonup = callback;
  48796. };
  48797. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  48798. if (newValue !== currentValue) {
  48799. if (this._onbuttondown && newValue === 1) {
  48800. this._onbuttondown(buttonIndex);
  48801. }
  48802. if (this._onbuttonup && newValue === 0) {
  48803. this._onbuttonup(buttonIndex);
  48804. }
  48805. }
  48806. return newValue;
  48807. };
  48808. GenericPad.prototype.update = function () {
  48809. _super.prototype.update.call(this);
  48810. for (var index = 0; index < this._buttons.length; index++) {
  48811. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  48812. }
  48813. };
  48814. return GenericPad;
  48815. })(Gamepad);
  48816. BABYLON.GenericPad = GenericPad;
  48817. (function (Xbox360Button) {
  48818. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  48819. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  48820. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  48821. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  48822. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  48823. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  48824. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  48825. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  48826. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  48827. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  48828. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  48829. var Xbox360Button = BABYLON.Xbox360Button;
  48830. (function (Xbox360Dpad) {
  48831. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  48832. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  48833. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  48834. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  48835. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  48836. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  48837. var Xbox360Pad = (function (_super) {
  48838. __extends(Xbox360Pad, _super);
  48839. function Xbox360Pad() {
  48840. _super.apply(this, arguments);
  48841. this._leftTrigger = 0;
  48842. this._rightTrigger = 0;
  48843. this._buttonA = 0;
  48844. this._buttonB = 0;
  48845. this._buttonX = 0;
  48846. this._buttonY = 0;
  48847. this._buttonBack = 0;
  48848. this._buttonStart = 0;
  48849. this._buttonLB = 0;
  48850. this._buttonRB = 0;
  48851. this._buttonLeftStick = 0;
  48852. this._buttonRightStick = 0;
  48853. this._dPadUp = 0;
  48854. this._dPadDown = 0;
  48855. this._dPadLeft = 0;
  48856. this._dPadRight = 0;
  48857. }
  48858. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  48859. this._onlefttriggerchanged = callback;
  48860. };
  48861. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  48862. this._onrighttriggerchanged = callback;
  48863. };
  48864. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  48865. get: function () {
  48866. return this._leftTrigger;
  48867. },
  48868. set: function (newValue) {
  48869. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  48870. this._onlefttriggerchanged(newValue);
  48871. }
  48872. this._leftTrigger = newValue;
  48873. },
  48874. enumerable: true,
  48875. configurable: true
  48876. });
  48877. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  48878. get: function () {
  48879. return this._rightTrigger;
  48880. },
  48881. set: function (newValue) {
  48882. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  48883. this._onrighttriggerchanged(newValue);
  48884. }
  48885. this._rightTrigger = newValue;
  48886. },
  48887. enumerable: true,
  48888. configurable: true
  48889. });
  48890. Xbox360Pad.prototype.onbuttondown = function (callback) {
  48891. this._onbuttondown = callback;
  48892. };
  48893. Xbox360Pad.prototype.onbuttonup = function (callback) {
  48894. this._onbuttonup = callback;
  48895. };
  48896. Xbox360Pad.prototype.ondpaddown = function (callback) {
  48897. this._ondpaddown = callback;
  48898. };
  48899. Xbox360Pad.prototype.ondpadup = function (callback) {
  48900. this._ondpadup = callback;
  48901. };
  48902. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  48903. if (newValue !== currentValue) {
  48904. if (this._onbuttondown && newValue === 1) {
  48905. this._onbuttondown(buttonType);
  48906. }
  48907. if (this._onbuttonup && newValue === 0) {
  48908. this._onbuttonup(buttonType);
  48909. }
  48910. }
  48911. return newValue;
  48912. };
  48913. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  48914. if (newValue !== currentValue) {
  48915. if (this._ondpaddown && newValue === 1) {
  48916. this._ondpaddown(buttonType);
  48917. }
  48918. if (this._ondpadup && newValue === 0) {
  48919. this._ondpadup(buttonType);
  48920. }
  48921. }
  48922. return newValue;
  48923. };
  48924. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  48925. get: function () {
  48926. return this._buttonA;
  48927. },
  48928. set: function (value) {
  48929. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  48930. },
  48931. enumerable: true,
  48932. configurable: true
  48933. });
  48934. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  48935. get: function () {
  48936. return this._buttonB;
  48937. },
  48938. set: function (value) {
  48939. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  48940. },
  48941. enumerable: true,
  48942. configurable: true
  48943. });
  48944. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  48945. get: function () {
  48946. return this._buttonX;
  48947. },
  48948. set: function (value) {
  48949. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  48950. },
  48951. enumerable: true,
  48952. configurable: true
  48953. });
  48954. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  48955. get: function () {
  48956. return this._buttonY;
  48957. },
  48958. set: function (value) {
  48959. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  48960. },
  48961. enumerable: true,
  48962. configurable: true
  48963. });
  48964. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  48965. get: function () {
  48966. return this._buttonStart;
  48967. },
  48968. set: function (value) {
  48969. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  48975. get: function () {
  48976. return this._buttonBack;
  48977. },
  48978. set: function (value) {
  48979. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  48980. },
  48981. enumerable: true,
  48982. configurable: true
  48983. });
  48984. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  48985. get: function () {
  48986. return this._buttonLB;
  48987. },
  48988. set: function (value) {
  48989. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  48995. get: function () {
  48996. return this._buttonRB;
  48997. },
  48998. set: function (value) {
  48999. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49000. },
  49001. enumerable: true,
  49002. configurable: true
  49003. });
  49004. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49005. get: function () {
  49006. return this._buttonLeftStick;
  49007. },
  49008. set: function (value) {
  49009. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49010. },
  49011. enumerable: true,
  49012. configurable: true
  49013. });
  49014. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49015. get: function () {
  49016. return this._buttonRightStick;
  49017. },
  49018. set: function (value) {
  49019. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49025. get: function () {
  49026. return this._dPadUp;
  49027. },
  49028. set: function (value) {
  49029. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49030. },
  49031. enumerable: true,
  49032. configurable: true
  49033. });
  49034. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49035. get: function () {
  49036. return this._dPadDown;
  49037. },
  49038. set: function (value) {
  49039. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49040. },
  49041. enumerable: true,
  49042. configurable: true
  49043. });
  49044. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49045. get: function () {
  49046. return this._dPadLeft;
  49047. },
  49048. set: function (value) {
  49049. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49050. },
  49051. enumerable: true,
  49052. configurable: true
  49053. });
  49054. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49055. get: function () {
  49056. return this._dPadRight;
  49057. },
  49058. set: function (value) {
  49059. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49060. },
  49061. enumerable: true,
  49062. configurable: true
  49063. });
  49064. Xbox360Pad.prototype.update = function () {
  49065. _super.prototype.update.call(this);
  49066. this.buttonA = this.browserGamepad.buttons[0].value;
  49067. this.buttonB = this.browserGamepad.buttons[1].value;
  49068. this.buttonX = this.browserGamepad.buttons[2].value;
  49069. this.buttonY = this.browserGamepad.buttons[3].value;
  49070. this.buttonLB = this.browserGamepad.buttons[4].value;
  49071. this.buttonRB = this.browserGamepad.buttons[5].value;
  49072. this.leftTrigger = this.browserGamepad.buttons[6].value;
  49073. this.rightTrigger = this.browserGamepad.buttons[7].value;
  49074. this.buttonBack = this.browserGamepad.buttons[8].value;
  49075. this.buttonStart = this.browserGamepad.buttons[9].value;
  49076. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  49077. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  49078. this.dPadUp = this.browserGamepad.buttons[12].value;
  49079. this.dPadDown = this.browserGamepad.buttons[13].value;
  49080. this.dPadLeft = this.browserGamepad.buttons[14].value;
  49081. this.dPadRight = this.browserGamepad.buttons[15].value;
  49082. };
  49083. return Xbox360Pad;
  49084. })(Gamepad);
  49085. BABYLON.Xbox360Pad = Xbox360Pad;
  49086. })(BABYLON || (BABYLON = {}));
  49087. var BABYLON;
  49088. (function (BABYLON) {
  49089. // We're mainly based on the logic defined into the FreeCamera code
  49090. var GamepadCamera = (function (_super) {
  49091. __extends(GamepadCamera, _super);
  49092. //-- end properties for backward compatibility for inputs
  49093. function GamepadCamera(name, position, scene) {
  49094. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  49095. _super.call(this, name, position, scene);
  49096. }
  49097. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49098. //-- Begin properties for backward compatibility for inputs
  49099. get: function () {
  49100. var gamepad = this.inputs.attached["gamepad"];
  49101. if (gamepad)
  49102. return gamepad.gamepadAngularSensibility;
  49103. },
  49104. set: function (value) {
  49105. var gamepad = this.inputs.attached["gamepad"];
  49106. if (gamepad)
  49107. gamepad.gamepadAngularSensibility = value;
  49108. },
  49109. enumerable: true,
  49110. configurable: true
  49111. });
  49112. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  49113. get: function () {
  49114. var gamepad = this.inputs.attached["gamepad"];
  49115. if (gamepad)
  49116. return gamepad.gamepadMoveSensibility;
  49117. },
  49118. set: function (value) {
  49119. var gamepad = this.inputs.attached["gamepad"];
  49120. if (gamepad)
  49121. gamepad.gamepadMoveSensibility = value;
  49122. },
  49123. enumerable: true,
  49124. configurable: true
  49125. });
  49126. GamepadCamera.prototype.getTypeName = function () {
  49127. return "GamepadCamera";
  49128. };
  49129. return GamepadCamera;
  49130. })(BABYLON.UniversalCamera);
  49131. BABYLON.GamepadCamera = GamepadCamera;
  49132. })(BABYLON || (BABYLON = {}));
  49133. var BABYLON;
  49134. (function (BABYLON) {
  49135. var Analyser = (function () {
  49136. function Analyser(scene) {
  49137. this.SMOOTHING = 0.75;
  49138. this.FFT_SIZE = 512;
  49139. this.BARGRAPHAMPLITUDE = 256;
  49140. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49141. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49142. this._scene = scene;
  49143. this._audioEngine = BABYLON.Engine.audioEngine;
  49144. if (this._audioEngine.canUseWebAudio) {
  49145. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49146. this._webAudioAnalyser.minDecibels = -140;
  49147. this._webAudioAnalyser.maxDecibels = 0;
  49148. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49149. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49150. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49151. }
  49152. }
  49153. Analyser.prototype.getFrequencyBinCount = function () {
  49154. if (this._audioEngine.canUseWebAudio) {
  49155. return this._webAudioAnalyser.frequencyBinCount;
  49156. }
  49157. else {
  49158. return 0;
  49159. }
  49160. };
  49161. Analyser.prototype.getByteFrequencyData = function () {
  49162. if (this._audioEngine.canUseWebAudio) {
  49163. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49164. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49165. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49166. }
  49167. return this._byteFreqs;
  49168. };
  49169. Analyser.prototype.getByteTimeDomainData = function () {
  49170. if (this._audioEngine.canUseWebAudio) {
  49171. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49172. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49173. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49174. }
  49175. return this._byteTime;
  49176. };
  49177. Analyser.prototype.getFloatFrequencyData = function () {
  49178. if (this._audioEngine.canUseWebAudio) {
  49179. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49180. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49181. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49182. }
  49183. return this._floatFreqs;
  49184. };
  49185. Analyser.prototype.drawDebugCanvas = function () {
  49186. var _this = this;
  49187. if (this._audioEngine.canUseWebAudio) {
  49188. if (!this._debugCanvas) {
  49189. this._debugCanvas = document.createElement("canvas");
  49190. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49191. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49192. this._debugCanvas.style.position = "absolute";
  49193. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49194. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49195. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49196. document.body.appendChild(this._debugCanvas);
  49197. this._registerFunc = function () {
  49198. _this.drawDebugCanvas();
  49199. };
  49200. this._scene.registerBeforeRender(this._registerFunc);
  49201. }
  49202. if (this._registerFunc) {
  49203. var workingArray = this.getByteFrequencyData();
  49204. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49205. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49206. // Draw the frequency domain chart.
  49207. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49208. var value = workingArray[i];
  49209. var percent = value / this.BARGRAPHAMPLITUDE;
  49210. var height = this.DEBUGCANVASSIZE.height * percent;
  49211. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49212. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49213. var hue = i / this.getFrequencyBinCount() * 360;
  49214. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49215. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49216. }
  49217. }
  49218. }
  49219. };
  49220. Analyser.prototype.stopDebugCanvas = function () {
  49221. if (this._debugCanvas) {
  49222. this._scene.unregisterBeforeRender(this._registerFunc);
  49223. this._registerFunc = null;
  49224. document.body.removeChild(this._debugCanvas);
  49225. this._debugCanvas = null;
  49226. this._debugCanvasContext = null;
  49227. }
  49228. };
  49229. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49230. if (this._audioEngine.canUseWebAudio) {
  49231. inputAudioNode.connect(this._webAudioAnalyser);
  49232. this._webAudioAnalyser.connect(outputAudioNode);
  49233. }
  49234. };
  49235. Analyser.prototype.dispose = function () {
  49236. if (this._audioEngine.canUseWebAudio) {
  49237. this._webAudioAnalyser.disconnect();
  49238. }
  49239. };
  49240. return Analyser;
  49241. })();
  49242. BABYLON.Analyser = Analyser;
  49243. })(BABYLON || (BABYLON = {}));
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. var DepthRenderer = (function () {
  49247. function DepthRenderer(scene, type) {
  49248. var _this = this;
  49249. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  49250. this._viewMatrix = BABYLON.Matrix.Zero();
  49251. this._projectionMatrix = BABYLON.Matrix.Zero();
  49252. this._transformMatrix = BABYLON.Matrix.Zero();
  49253. this._worldViewProjection = BABYLON.Matrix.Zero();
  49254. this._scene = scene;
  49255. var engine = scene.getEngine();
  49256. // Render target
  49257. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  49258. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49259. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49260. this._depthMap.refreshRate = 1;
  49261. this._depthMap.renderParticles = false;
  49262. this._depthMap.renderList = null;
  49263. // set default depth value to 1.0 (far away)
  49264. this._depthMap.onClearObservable.add(function (engine) {
  49265. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  49266. });
  49267. // Custom render function
  49268. var renderSubMesh = function (subMesh) {
  49269. var mesh = subMesh.getRenderingMesh();
  49270. var scene = _this._scene;
  49271. var engine = scene.getEngine();
  49272. // Culling
  49273. engine.setState(subMesh.getMaterial().backFaceCulling);
  49274. // Managing instances
  49275. var batch = mesh._getInstancesRenderList(subMesh._id);
  49276. if (batch.mustReturn) {
  49277. return;
  49278. }
  49279. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  49280. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49281. engine.enableEffect(_this._effect);
  49282. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  49283. var material = subMesh.getMaterial();
  49284. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49285. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  49286. // Alpha test
  49287. if (material && material.needAlphaTesting()) {
  49288. var alphaTexture = material.getAlphaTestTexture();
  49289. _this._effect.setTexture("diffuseSampler", alphaTexture);
  49290. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49291. }
  49292. // Bones
  49293. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49294. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49295. }
  49296. // Draw
  49297. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49298. }
  49299. };
  49300. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  49301. var index;
  49302. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49303. renderSubMesh(opaqueSubMeshes.data[index]);
  49304. }
  49305. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49306. renderSubMesh(alphaTestSubMeshes.data[index]);
  49307. }
  49308. };
  49309. }
  49310. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  49311. var material = subMesh.getMaterial();
  49312. if (material.disableDepthWrite) {
  49313. return false;
  49314. }
  49315. var defines = [];
  49316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49317. var mesh = subMesh.getMesh();
  49318. var scene = mesh.getScene();
  49319. // Alpha test
  49320. if (material && material.needAlphaTesting()) {
  49321. defines.push("#define ALPHATEST");
  49322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49323. attribs.push(BABYLON.VertexBuffer.UVKind);
  49324. defines.push("#define UV1");
  49325. }
  49326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49327. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49328. defines.push("#define UV2");
  49329. }
  49330. }
  49331. // Bones
  49332. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49333. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49334. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49335. if (mesh.numBoneInfluencers > 4) {
  49336. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49337. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49338. }
  49339. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49340. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49341. }
  49342. else {
  49343. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49344. }
  49345. // Instances
  49346. if (useInstances) {
  49347. defines.push("#define INSTANCES");
  49348. attribs.push("world0");
  49349. attribs.push("world1");
  49350. attribs.push("world2");
  49351. attribs.push("world3");
  49352. }
  49353. // Get correct effect
  49354. var join = defines.join("\n");
  49355. if (this._cachedDefines !== join) {
  49356. this._cachedDefines = join;
  49357. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  49358. }
  49359. return this._effect.isReady();
  49360. };
  49361. DepthRenderer.prototype.getDepthMap = function () {
  49362. return this._depthMap;
  49363. };
  49364. // Methods
  49365. DepthRenderer.prototype.dispose = function () {
  49366. this._depthMap.dispose();
  49367. };
  49368. return DepthRenderer;
  49369. })();
  49370. BABYLON.DepthRenderer = DepthRenderer;
  49371. })(BABYLON || (BABYLON = {}));
  49372. var BABYLON;
  49373. (function (BABYLON) {
  49374. var SSAORenderingPipeline = (function (_super) {
  49375. __extends(SSAORenderingPipeline, _super);
  49376. /**
  49377. * @constructor
  49378. * @param {string} name - The rendering pipeline name
  49379. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49380. * @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 }
  49381. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49382. */
  49383. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49384. var _this = this;
  49385. _super.call(this, scene.getEngine(), name);
  49386. // Members
  49387. /**
  49388. * The PassPostProcess id in the pipeline that contains the original scene color
  49389. * @type {string}
  49390. */
  49391. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49392. /**
  49393. * The SSAO PostProcess id in the pipeline
  49394. * @type {string}
  49395. */
  49396. this.SSAORenderEffect = "SSAORenderEffect";
  49397. /**
  49398. * The horizontal blur PostProcess id in the pipeline
  49399. * @type {string}
  49400. */
  49401. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49402. /**
  49403. * The vertical blur PostProcess id in the pipeline
  49404. * @type {string}
  49405. */
  49406. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49407. /**
  49408. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49409. * @type {string}
  49410. */
  49411. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49412. /**
  49413. * The output strength of the SSAO post-process. Default value is 1.0.
  49414. * @type {number}
  49415. */
  49416. this.totalStrength = 1.0;
  49417. /**
  49418. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49419. * @type {number}
  49420. */
  49421. this.radius = 0.0001;
  49422. /**
  49423. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49424. * Must not be equal to fallOff and superior to fallOff.
  49425. * Default value is 0.975
  49426. * @type {number}
  49427. */
  49428. this.area = 0.0075;
  49429. /**
  49430. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49431. * Must not be equal to area and inferior to area.
  49432. * Default value is 0.0
  49433. * @type {number}
  49434. */
  49435. this.fallOff = 0.000001;
  49436. /**
  49437. * The base color of the SSAO post-process
  49438. * The final result is "base + ssao" between [0, 1]
  49439. * @type {number}
  49440. */
  49441. this.base = 0.5;
  49442. this._firstUpdate = true;
  49443. this._scene = scene;
  49444. // Set up assets
  49445. this._createRandomTexture();
  49446. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49447. var ssaoRatio = ratio.ssaoRatio || ratio;
  49448. var combineRatio = ratio.combineRatio || ratio;
  49449. this._ratio = {
  49450. ssaoRatio: ssaoRatio,
  49451. combineRatio: combineRatio
  49452. };
  49453. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49454. this._createSSAOPostProcess(ssaoRatio);
  49455. this._createBlurPostProcess(ssaoRatio);
  49456. this._createSSAOCombinePostProcess(combineRatio);
  49457. // Set up pipeline
  49458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49463. // Finish
  49464. scene.postProcessRenderPipelineManager.addPipeline(this);
  49465. if (cameras)
  49466. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49467. }
  49468. // Public Methods
  49469. /**
  49470. * Returns the horizontal blur PostProcess
  49471. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  49472. */
  49473. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  49474. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  49475. return null;
  49476. };
  49477. /**
  49478. * Returns the vertical blur PostProcess
  49479. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  49480. */
  49481. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  49482. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  49483. return null;
  49484. };
  49485. /**
  49486. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49487. */
  49488. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49489. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49490. for (var i = 0; i < this._scene.cameras.length; i++) {
  49491. var camera = this._scene.cameras[i];
  49492. this._originalColorPostProcess.dispose(camera);
  49493. this._ssaoPostProcess.dispose(camera);
  49494. this._blurHPostProcess.dispose(camera);
  49495. this._blurVPostProcess.dispose(camera);
  49496. this._ssaoCombinePostProcess.dispose(camera);
  49497. }
  49498. this._randomTexture.dispose();
  49499. if (disableDepthRender)
  49500. this._scene.disableDepthRenderer();
  49501. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49502. };
  49503. // Private Methods
  49504. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49505. var _this = this;
  49506. /*
  49507. var samplerOffsets = [
  49508. -8.0, -6.0, -4.0, -2.0,
  49509. 0.0,
  49510. 2.0, 4.0, 6.0, 8.0
  49511. ];
  49512. */
  49513. var samples = 16;
  49514. var samplerOffsets = [];
  49515. for (var i = -8; i < 8; i++) {
  49516. samplerOffsets.push(i * 2);
  49517. }
  49518. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  49519. this._blurHPostProcess.onApply = function (effect) {
  49520. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49521. effect.setTexture("depthSampler", _this._depthTexture);
  49522. if (_this._firstUpdate) {
  49523. effect.setArray("samplerOffsets", samplerOffsets);
  49524. }
  49525. };
  49526. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  49527. this._blurVPostProcess.onApply = function (effect) {
  49528. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49529. effect.setTexture("depthSampler", _this._depthTexture);
  49530. if (_this._firstUpdate) {
  49531. effect.setArray("samplerOffsets", samplerOffsets);
  49532. _this._firstUpdate = false;
  49533. }
  49534. };
  49535. };
  49536. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49537. var _this = this;
  49538. var numSamples = 16;
  49539. var sampleSphere = [
  49540. 0.5381, 0.1856, -0.4319,
  49541. 0.1379, 0.2486, 0.4430,
  49542. 0.3371, 0.5679, -0.0057,
  49543. -0.6999, -0.0451, -0.0019,
  49544. 0.0689, -0.1598, -0.8547,
  49545. 0.0560, 0.0069, -0.1843,
  49546. -0.0146, 0.1402, 0.0762,
  49547. 0.0100, -0.1924, -0.0344,
  49548. -0.3577, -0.5301, -0.4358,
  49549. -0.3169, 0.1063, 0.0158,
  49550. 0.0103, -0.5869, 0.0046,
  49551. -0.0897, -0.4940, 0.3287,
  49552. 0.7119, -0.0154, -0.0918,
  49553. -0.0533, 0.0596, -0.5411,
  49554. 0.0352, -0.0631, 0.5460,
  49555. -0.4776, 0.2847, -0.0271
  49556. ];
  49557. var samplesFactor = 1.0 / numSamples;
  49558. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49559. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49560. "area", "fallOff", "base", "range", "viewport"
  49561. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49562. var viewport = new BABYLON.Vector2(0, 0);
  49563. this._ssaoPostProcess.onApply = function (effect) {
  49564. if (_this._firstUpdate) {
  49565. effect.setArray3("sampleSphere", sampleSphere);
  49566. effect.setFloat("samplesFactor", samplesFactor);
  49567. effect.setFloat("randTextureTiles", 4.0);
  49568. }
  49569. effect.setFloat("totalStrength", _this.totalStrength);
  49570. effect.setFloat("radius", _this.radius);
  49571. effect.setFloat("area", _this.area);
  49572. effect.setFloat("fallOff", _this.fallOff);
  49573. effect.setFloat("base", _this.base);
  49574. effect.setTexture("textureSampler", _this._depthTexture);
  49575. effect.setTexture("randomSampler", _this._randomTexture);
  49576. };
  49577. };
  49578. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49579. var _this = this;
  49580. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49581. this._ssaoCombinePostProcess.onApply = function (effect) {
  49582. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49583. };
  49584. };
  49585. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49586. var size = 512;
  49587. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49588. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49589. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49590. var context = this._randomTexture.getContext();
  49591. var rand = function (min, max) {
  49592. return Math.random() * (max - min) + min;
  49593. };
  49594. var randVector = BABYLON.Vector3.Zero();
  49595. for (var x = 0; x < size; x++) {
  49596. for (var y = 0; y < size; y++) {
  49597. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49598. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49599. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49600. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49601. context.fillRect(x, y, 1, 1);
  49602. }
  49603. }
  49604. this._randomTexture.update(false);
  49605. };
  49606. __decorate([
  49607. BABYLON.serialize()
  49608. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49609. __decorate([
  49610. BABYLON.serialize()
  49611. ], SSAORenderingPipeline.prototype, "radius", void 0);
  49612. __decorate([
  49613. BABYLON.serialize()
  49614. ], SSAORenderingPipeline.prototype, "area", void 0);
  49615. __decorate([
  49616. BABYLON.serialize()
  49617. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  49618. __decorate([
  49619. BABYLON.serialize()
  49620. ], SSAORenderingPipeline.prototype, "base", void 0);
  49621. __decorate([
  49622. BABYLON.serialize()
  49623. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  49624. return SSAORenderingPipeline;
  49625. })(BABYLON.PostProcessRenderPipeline);
  49626. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  49627. })(BABYLON || (BABYLON = {}));
  49628. var BABYLON;
  49629. (function (BABYLON) {
  49630. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  49631. var VolumetricLightScatteringPostProcess = (function (_super) {
  49632. __extends(VolumetricLightScatteringPostProcess, _super);
  49633. /**
  49634. * @constructor
  49635. * @param {string} name - The post-process name
  49636. * @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)
  49637. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  49638. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  49639. * @param {number} samples - The post-process quality, default 100
  49640. * @param {number} samplingMode - The post-process filtering mode
  49641. * @param {BABYLON.Engine} engine - The babylon engine
  49642. * @param {boolean} reusable - If the post-process is reusable
  49643. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  49644. */
  49645. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  49646. var _this = this;
  49647. if (samples === void 0) { samples = 100; }
  49648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49649. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  49650. this._screenCoordinates = BABYLON.Vector2.Zero();
  49651. /**
  49652. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  49653. * @type {Vector3}
  49654. */
  49655. this.customMeshPosition = BABYLON.Vector3.Zero();
  49656. /**
  49657. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  49658. * @type {boolean}
  49659. */
  49660. this.useCustomMeshPosition = false;
  49661. /**
  49662. * If the post-process should inverse the light scattering direction
  49663. * @type {boolean}
  49664. */
  49665. this.invert = true;
  49666. /**
  49667. * Array containing the excluded meshes not rendered in the internal pass
  49668. */
  49669. this.excludedMeshes = new Array();
  49670. /**
  49671. * Controls the overall intensity of the post-process
  49672. * @type {number}
  49673. */
  49674. this.exposure = 0.3;
  49675. /**
  49676. * Dissipates each sample's contribution in range [0, 1]
  49677. * @type {number}
  49678. */
  49679. this.decay = 0.96815;
  49680. /**
  49681. * Controls the overall intensity of each sample
  49682. * @type {number}
  49683. */
  49684. this.weight = 0.58767;
  49685. /**
  49686. * Controls the density of each sample
  49687. * @type {number}
  49688. */
  49689. this.density = 0.926;
  49690. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  49691. var engine = scene.getEngine();
  49692. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  49693. // Configure mesh
  49694. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  49695. // Configure
  49696. this._createPass(scene, ratio.passRatio || ratio);
  49697. this.onActivate = function (camera) {
  49698. if (!_this.isSupported) {
  49699. _this.dispose(camera);
  49700. }
  49701. _this.onActivate = null;
  49702. };
  49703. this.onApplyObservable.add(function (effect) {
  49704. _this._updateMeshScreenCoordinates(scene);
  49705. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  49706. effect.setFloat("exposure", _this.exposure);
  49707. effect.setFloat("decay", _this.decay);
  49708. effect.setFloat("weight", _this.weight);
  49709. effect.setFloat("density", _this.density);
  49710. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  49711. });
  49712. }
  49713. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  49714. get: function () {
  49715. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  49716. return false;
  49717. },
  49718. set: function (useDiffuseColor) {
  49719. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  49720. },
  49721. enumerable: true,
  49722. configurable: true
  49723. });
  49724. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  49725. var mesh = subMesh.getMesh();
  49726. // Render this.mesh as default
  49727. if (mesh === this.mesh) {
  49728. return mesh.material.isReady(mesh);
  49729. }
  49730. var defines = [];
  49731. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49732. var material = subMesh.getMaterial();
  49733. var needUV = false;
  49734. // Alpha test
  49735. if (material) {
  49736. if (material.needAlphaTesting()) {
  49737. defines.push("#define ALPHATEST");
  49738. }
  49739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49740. attribs.push(BABYLON.VertexBuffer.UVKind);
  49741. defines.push("#define UV1");
  49742. }
  49743. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49744. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49745. defines.push("#define UV2");
  49746. }
  49747. }
  49748. // Bones
  49749. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49752. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49753. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49754. }
  49755. else {
  49756. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49757. }
  49758. // Instances
  49759. if (useInstances) {
  49760. defines.push("#define INSTANCES");
  49761. attribs.push("world0");
  49762. attribs.push("world1");
  49763. attribs.push("world2");
  49764. attribs.push("world3");
  49765. }
  49766. // Get correct effect
  49767. var join = defines.join("\n");
  49768. if (this._cachedDefines !== join) {
  49769. this._cachedDefines = join;
  49770. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  49771. }
  49772. return this._volumetricLightScatteringPass.isReady();
  49773. };
  49774. /**
  49775. * Sets the new light position for light scattering effect
  49776. * @param {BABYLON.Vector3} The new custom light position
  49777. */
  49778. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  49779. this.customMeshPosition = position;
  49780. };
  49781. /**
  49782. * Returns the light position for light scattering effect
  49783. * @return {BABYLON.Vector3} The custom light position
  49784. */
  49785. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  49786. return this.customMeshPosition;
  49787. };
  49788. /**
  49789. * Disposes the internal assets and detaches the post-process from the camera
  49790. */
  49791. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  49792. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  49793. if (rttIndex !== -1) {
  49794. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  49795. }
  49796. this._volumetricLightScatteringRTT.dispose();
  49797. _super.prototype.dispose.call(this, camera);
  49798. };
  49799. /**
  49800. * Returns the render target texture used by the post-process
  49801. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  49802. */
  49803. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  49804. return this._volumetricLightScatteringRTT;
  49805. };
  49806. // Private methods
  49807. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  49808. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  49809. return true;
  49810. }
  49811. return false;
  49812. };
  49813. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  49814. var _this = this;
  49815. var engine = scene.getEngine();
  49816. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49817. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49818. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49819. this._volumetricLightScatteringRTT.renderList = null;
  49820. this._volumetricLightScatteringRTT.renderParticles = false;
  49821. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  49822. // Custom render function for submeshes
  49823. var renderSubMesh = function (subMesh) {
  49824. var mesh = subMesh.getRenderingMesh();
  49825. if (_this._meshExcluded(mesh)) {
  49826. return;
  49827. }
  49828. var scene = mesh.getScene();
  49829. var engine = scene.getEngine();
  49830. // Culling
  49831. engine.setState(subMesh.getMaterial().backFaceCulling);
  49832. // Managing instances
  49833. var batch = mesh._getInstancesRenderList(subMesh._id);
  49834. if (batch.mustReturn) {
  49835. return;
  49836. }
  49837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  49838. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49839. var effect = _this._volumetricLightScatteringPass;
  49840. if (mesh === _this.mesh) {
  49841. effect = subMesh.getMaterial().getEffect();
  49842. }
  49843. engine.enableEffect(effect);
  49844. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  49845. if (mesh === _this.mesh) {
  49846. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  49847. }
  49848. else {
  49849. var material = subMesh.getMaterial();
  49850. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  49851. // Alpha test
  49852. if (material && material.needAlphaTesting()) {
  49853. var alphaTexture = material.getAlphaTestTexture();
  49854. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  49855. if (alphaTexture) {
  49856. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49857. }
  49858. }
  49859. // Bones
  49860. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49861. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49862. }
  49863. }
  49864. // Draw
  49865. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  49866. }
  49867. };
  49868. // Render target texture callbacks
  49869. var savedSceneClearColor;
  49870. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  49871. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  49872. savedSceneClearColor = scene.clearColor;
  49873. scene.clearColor = sceneClearColor;
  49874. });
  49875. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  49876. scene.clearColor = savedSceneClearColor;
  49877. });
  49878. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  49879. var engine = scene.getEngine();
  49880. var index;
  49881. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49882. renderSubMesh(opaqueSubMeshes.data[index]);
  49883. }
  49884. engine.setAlphaTesting(true);
  49885. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49886. renderSubMesh(alphaTestSubMeshes.data[index]);
  49887. }
  49888. engine.setAlphaTesting(false);
  49889. if (transparentSubMeshes.length) {
  49890. // Sort sub meshes
  49891. for (index = 0; index < transparentSubMeshes.length; index++) {
  49892. var submesh = transparentSubMeshes.data[index];
  49893. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  49894. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  49895. }
  49896. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  49897. sortedArray.sort(function (a, b) {
  49898. // Alpha index first
  49899. if (a._alphaIndex > b._alphaIndex) {
  49900. return 1;
  49901. }
  49902. if (a._alphaIndex < b._alphaIndex) {
  49903. return -1;
  49904. }
  49905. // Then distance to camera
  49906. if (a._distanceToCamera < b._distanceToCamera) {
  49907. return 1;
  49908. }
  49909. if (a._distanceToCamera > b._distanceToCamera) {
  49910. return -1;
  49911. }
  49912. return 0;
  49913. });
  49914. // Render sub meshes
  49915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49916. for (index = 0; index < sortedArray.length; index++) {
  49917. renderSubMesh(sortedArray[index]);
  49918. }
  49919. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49920. }
  49921. };
  49922. };
  49923. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  49924. var transform = scene.getTransformMatrix();
  49925. var meshPosition;
  49926. if (this.useCustomMeshPosition) {
  49927. meshPosition = this.customMeshPosition;
  49928. }
  49929. else if (this.attachedNode) {
  49930. meshPosition = this.attachedNode.position;
  49931. }
  49932. else {
  49933. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  49934. }
  49935. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  49936. this._screenCoordinates.x = pos.x / this._viewPort.width;
  49937. this._screenCoordinates.y = pos.y / this._viewPort.height;
  49938. if (this.invert)
  49939. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  49940. };
  49941. // Static methods
  49942. /**
  49943. * Creates a default mesh for the Volumeric Light Scattering post-process
  49944. * @param {string} The mesh name
  49945. * @param {BABYLON.Scene} The scene where to create the mesh
  49946. * @return {BABYLON.Mesh} the default mesh
  49947. */
  49948. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  49949. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  49950. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  49951. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  49952. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  49953. mesh.material = material;
  49954. return mesh;
  49955. };
  49956. __decorate([
  49957. BABYLON.serializeAsVector3()
  49958. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  49959. __decorate([
  49960. BABYLON.serialize()
  49961. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  49962. __decorate([
  49963. BABYLON.serialize()
  49964. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  49965. __decorate([
  49966. BABYLON.serializeAsMeshReference()
  49967. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  49968. __decorate([
  49969. BABYLON.serialize()
  49970. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  49971. __decorate([
  49972. BABYLON.serialize()
  49973. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  49974. __decorate([
  49975. BABYLON.serialize()
  49976. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  49977. __decorate([
  49978. BABYLON.serialize()
  49979. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  49980. __decorate([
  49981. BABYLON.serialize()
  49982. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  49983. return VolumetricLightScatteringPostProcess;
  49984. })(BABYLON.PostProcess);
  49985. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  49986. })(BABYLON || (BABYLON = {}));
  49987. // BABYLON.JS Chromatic Aberration GLSL Shader
  49988. // Author: Olivier Guyot
  49989. // Separates very slightly R, G and B colors on the edges of the screen
  49990. // Inspired by Francois Tarlier & Martins Upitis
  49991. var BABYLON;
  49992. (function (BABYLON) {
  49993. var LensRenderingPipeline = (function (_super) {
  49994. __extends(LensRenderingPipeline, _super);
  49995. /**
  49996. * @constructor
  49997. *
  49998. * Effect parameters are as follow:
  49999. * {
  50000. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50001. * edge_blur: number; // from 0 to x (1 for realism)
  50002. * distortion: number; // from 0 to x (1 for realism)
  50003. * grain_amount: number; // from 0 to 1
  50004. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50005. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50006. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50007. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50008. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50009. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50010. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50011. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50012. * }
  50013. * Note: if an effect parameter is unset, effect is disabled
  50014. *
  50015. * @param {string} name - The rendering pipeline name
  50016. * @param {object} parameters - An object containing all parameters (see above)
  50017. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50018. * @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)
  50019. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50020. */
  50021. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50022. var _this = this;
  50023. if (ratio === void 0) { ratio = 1.0; }
  50024. _super.call(this, scene.getEngine(), name);
  50025. // Lens effects can be of the following:
  50026. // - chromatic aberration (slight shift of RGB colors)
  50027. // - blur on the edge of the lens
  50028. // - lens distortion
  50029. // - depth-of-field blur & highlights enhancing
  50030. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50031. // - grain effect (noise or custom texture)
  50032. // Two additional texture samplers are needed:
  50033. // - depth map (for depth-of-field)
  50034. // - grain texture
  50035. /**
  50036. * The chromatic aberration PostProcess id in the pipeline
  50037. * @type {string}
  50038. */
  50039. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50040. /**
  50041. * The highlights enhancing PostProcess id in the pipeline
  50042. * @type {string}
  50043. */
  50044. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50045. /**
  50046. * The depth-of-field PostProcess id in the pipeline
  50047. * @type {string}
  50048. */
  50049. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50050. this._scene = scene;
  50051. // Fetch texture samplers
  50052. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50053. if (parameters.grain_texture) {
  50054. this._grainTexture = parameters.grain_texture;
  50055. }
  50056. else {
  50057. this._createGrainTexture();
  50058. }
  50059. // save parameters
  50060. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50061. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50062. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50063. this._distortion = parameters.distortion ? parameters.distortion : 0;
  50064. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50065. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50066. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50067. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50068. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50069. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50070. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50071. // Create effects
  50072. this._createChromaticAberrationPostProcess(ratio);
  50073. this._createHighlightsPostProcess(ratio);
  50074. this._createDepthOfFieldPostProcess(ratio / 4);
  50075. // Set up pipeline
  50076. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50079. if (this._highlightsGain === -1) {
  50080. this._disableEffect(this.HighlightsEnhancingEffect, null);
  50081. }
  50082. // Finish
  50083. scene.postProcessRenderPipelineManager.addPipeline(this);
  50084. if (cameras) {
  50085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50086. }
  50087. }
  50088. // public methods (self explanatory)
  50089. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50090. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50091. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50092. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50093. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50094. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50095. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50096. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50097. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50098. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50099. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50100. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50101. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  50102. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  50103. };
  50104. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  50105. this._highlightsPostProcess.updateEffect();
  50106. };
  50107. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  50108. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  50109. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  50110. this._highlightsGain = amount;
  50111. };
  50112. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  50113. if (this._highlightsGain === -1) {
  50114. this._highlightsGain = 1.0;
  50115. }
  50116. this._highlightsThreshold = amount;
  50117. };
  50118. LensRenderingPipeline.prototype.disableHighlights = function () {
  50119. this._highlightsGain = -1;
  50120. };
  50121. /**
  50122. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  50123. */
  50124. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50125. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50126. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50127. this._chromaticAberrationPostProcess = undefined;
  50128. this._highlightsPostProcess = undefined;
  50129. this._depthOfFieldPostProcess = undefined;
  50130. this._grainTexture.dispose();
  50131. if (disableDepthRender)
  50132. this._scene.disableDepthRenderer();
  50133. };
  50134. // colors shifting and distortion
  50135. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  50136. var _this = this;
  50137. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  50138. [], // samplers
  50139. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50140. this._chromaticAberrationPostProcess.onApply = function (effect) {
  50141. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  50142. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50143. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50144. };
  50145. };
  50146. // highlights enhancing
  50147. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  50148. var _this = this;
  50149. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  50150. [], // samplers
  50151. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  50152. this._highlightsPostProcess.onApply = function (effect) {
  50153. effect.setFloat('gain', _this._highlightsGain);
  50154. effect.setFloat('threshold', _this._highlightsThreshold);
  50155. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  50156. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50157. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50158. };
  50159. };
  50160. // colors shifting and distortion
  50161. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  50162. var _this = this;
  50163. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  50164. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  50165. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  50166. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50167. this._depthOfFieldPostProcess.onApply = function (effect) {
  50168. effect.setTexture("depthSampler", _this._depthTexture);
  50169. effect.setTexture("grainSampler", _this._grainTexture);
  50170. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  50171. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  50172. effect.setFloat('grain_amount', _this._grainAmount);
  50173. effect.setBool('blur_noise', _this._blurNoise);
  50174. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  50175. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  50176. effect.setFloat('distortion', _this._distortion);
  50177. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  50178. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  50179. effect.setFloat('aperture', _this._dofAperture);
  50180. effect.setFloat('darken', _this._dofDarken);
  50181. effect.setFloat('edge_blur', _this._edgeBlur);
  50182. effect.setBool('highlights', (_this._highlightsGain !== -1));
  50183. effect.setFloat('near', _this._scene.activeCamera.minZ);
  50184. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  50185. };
  50186. };
  50187. // creates a black and white random noise texture, 512x512
  50188. LensRenderingPipeline.prototype._createGrainTexture = function () {
  50189. var size = 512;
  50190. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50191. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50192. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50193. var context = this._grainTexture.getContext();
  50194. var rand = function (min, max) {
  50195. return Math.random() * (max - min) + min;
  50196. };
  50197. var value;
  50198. for (var x = 0; x < size; x++) {
  50199. for (var y = 0; y < size; y++) {
  50200. value = Math.floor(rand(0.42, 0.58) * 255);
  50201. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  50202. context.fillRect(x, y, 1, 1);
  50203. }
  50204. }
  50205. this._grainTexture.update(false);
  50206. };
  50207. return LensRenderingPipeline;
  50208. })(BABYLON.PostProcessRenderPipeline);
  50209. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  50210. })(BABYLON || (BABYLON = {}));
  50211. //
  50212. // This post-process allows the modification of rendered colors by using
  50213. // a 'look-up table' (LUT). This effect is also called Color Grading.
  50214. //
  50215. // The object needs to be provided an url to a texture containing the color
  50216. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  50217. // Use an image editing software to tweak the LUT to match your needs.
  50218. //
  50219. // For an example of a color LUT, see here:
  50220. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  50221. // For explanations on color grading, see here:
  50222. // http://udn.epicgames.com/Three/ColorGrading.html
  50223. //
  50224. var BABYLON;
  50225. (function (BABYLON) {
  50226. var ColorCorrectionPostProcess = (function (_super) {
  50227. __extends(ColorCorrectionPostProcess, _super);
  50228. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  50229. var _this = this;
  50230. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  50231. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50232. this._colorTableTexture.anisotropicFilteringLevel = 1;
  50233. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50234. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50235. this.onApply = function (effect) {
  50236. effect.setTexture("colorTable", _this._colorTableTexture);
  50237. };
  50238. }
  50239. return ColorCorrectionPostProcess;
  50240. })(BABYLON.PostProcess);
  50241. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  50242. })(BABYLON || (BABYLON = {}));
  50243. var BABYLON;
  50244. (function (BABYLON) {
  50245. var AnaglyphFreeCamera = (function (_super) {
  50246. __extends(AnaglyphFreeCamera, _super);
  50247. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  50248. _super.call(this, name, position, scene);
  50249. this.interaxialDistance = interaxialDistance;
  50250. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  50251. }
  50252. AnaglyphFreeCamera.prototype.getTypeName = function () {
  50253. return "AnaglyphFreeCamera";
  50254. };
  50255. return AnaglyphFreeCamera;
  50256. })(BABYLON.FreeCamera);
  50257. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  50258. var AnaglyphArcRotateCamera = (function (_super) {
  50259. __extends(AnaglyphArcRotateCamera, _super);
  50260. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  50261. _super.call(this, name, alpha, beta, radius, target, scene);
  50262. this.interaxialDistance = interaxialDistance;
  50263. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  50264. }
  50265. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  50266. return "AnaglyphArcRotateCamera";
  50267. };
  50268. return AnaglyphArcRotateCamera;
  50269. })(BABYLON.ArcRotateCamera);
  50270. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  50271. var AnaglyphGamepadCamera = (function (_super) {
  50272. __extends(AnaglyphGamepadCamera, _super);
  50273. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  50274. _super.call(this, name, position, scene);
  50275. this.interaxialDistance = interaxialDistance;
  50276. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  50277. }
  50278. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  50279. return "AnaglyphGamepadCamera";
  50280. };
  50281. return AnaglyphGamepadCamera;
  50282. })(BABYLON.GamepadCamera);
  50283. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  50284. var AnaglyphUniversalCamera = (function (_super) {
  50285. __extends(AnaglyphUniversalCamera, _super);
  50286. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  50287. _super.call(this, name, position, scene);
  50288. this.interaxialDistance = interaxialDistance;
  50289. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  50290. }
  50291. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  50292. return "AnaglyphUniversalCamera";
  50293. };
  50294. return AnaglyphUniversalCamera;
  50295. })(BABYLON.UniversalCamera);
  50296. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  50297. var StereoscopicFreeCamera = (function (_super) {
  50298. __extends(StereoscopicFreeCamera, _super);
  50299. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  50300. _super.call(this, name, position, scene);
  50301. this.interaxialDistance = interaxialDistance;
  50302. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  50303. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  50304. }
  50305. StereoscopicFreeCamera.prototype.getTypeName = function () {
  50306. return "StereoscopicFreeCamera";
  50307. };
  50308. return StereoscopicFreeCamera;
  50309. })(BABYLON.FreeCamera);
  50310. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  50311. var StereoscopicArcRotateCamera = (function (_super) {
  50312. __extends(StereoscopicArcRotateCamera, _super);
  50313. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  50314. _super.call(this, name, alpha, beta, radius, target, scene);
  50315. this.interaxialDistance = interaxialDistance;
  50316. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  50317. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  50318. }
  50319. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  50320. return "StereoscopicArcRotateCamera";
  50321. };
  50322. return StereoscopicArcRotateCamera;
  50323. })(BABYLON.ArcRotateCamera);
  50324. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  50325. var StereoscopicGamepadCamera = (function (_super) {
  50326. __extends(StereoscopicGamepadCamera, _super);
  50327. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  50328. _super.call(this, name, position, scene);
  50329. this.interaxialDistance = interaxialDistance;
  50330. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  50331. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  50332. }
  50333. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  50334. return "StereoscopicGamepadCamera";
  50335. };
  50336. return StereoscopicGamepadCamera;
  50337. })(BABYLON.GamepadCamera);
  50338. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  50339. var StereoscopicUniversalCamera = (function (_super) {
  50340. __extends(StereoscopicUniversalCamera, _super);
  50341. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  50342. _super.call(this, name, position, scene);
  50343. this.interaxialDistance = interaxialDistance;
  50344. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  50345. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  50346. }
  50347. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  50348. return "StereoscopicUniversalCamera";
  50349. };
  50350. return StereoscopicUniversalCamera;
  50351. })(BABYLON.UniversalCamera);
  50352. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  50353. })(BABYLON || (BABYLON = {}));
  50354. var BABYLON;
  50355. (function (BABYLON) {
  50356. var HDRRenderingPipeline = (function (_super) {
  50357. __extends(HDRRenderingPipeline, _super);
  50358. /**
  50359. * @constructor
  50360. * @param {string} name - The rendering pipeline name
  50361. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50362. * @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)
  50363. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  50364. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50365. */
  50366. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  50367. var _this = this;
  50368. if (originalPostProcess === void 0) { originalPostProcess = null; }
  50369. _super.call(this, scene.getEngine(), name);
  50370. /**
  50371. * Public members
  50372. */
  50373. // Gaussian Blur
  50374. /**
  50375. * Gaussian blur coefficient
  50376. * @type {number}
  50377. */
  50378. this.gaussCoeff = 0.3;
  50379. /**
  50380. * Gaussian blur mean
  50381. * @type {number}
  50382. */
  50383. this.gaussMean = 1.0;
  50384. /**
  50385. * Gaussian blur standard deviation
  50386. * @type {number}
  50387. */
  50388. this.gaussStandDev = 0.8;
  50389. /**
  50390. * Gaussian blur multiplier. Multiplies the blur effect
  50391. * @type {number}
  50392. */
  50393. this.gaussMultiplier = 4.0;
  50394. // HDR
  50395. /**
  50396. * Exposure, controls the overall intensity of the pipeline
  50397. * @type {number}
  50398. */
  50399. this.exposure = 1.0;
  50400. /**
  50401. * Minimum luminance that the post-process can output. Luminance is >= 0
  50402. * @type {number}
  50403. */
  50404. this.minimumLuminance = 1.0;
  50405. /**
  50406. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  50407. * @type {number}
  50408. */
  50409. this.maximumLuminance = 1e20;
  50410. /**
  50411. * Increase rate for luminance: eye adaptation speed to dark
  50412. * @type {number}
  50413. */
  50414. this.luminanceIncreaserate = 0.5;
  50415. /**
  50416. * Decrease rate for luminance: eye adaptation speed to bright
  50417. * @type {number}
  50418. */
  50419. this.luminanceDecreaseRate = 0.5;
  50420. // Bright pass
  50421. /**
  50422. * Minimum luminance needed to compute HDR
  50423. * @type {number}
  50424. */
  50425. this.brightThreshold = 0.8;
  50426. this._needUpdate = true;
  50427. this._scene = scene;
  50428. // Bright pass
  50429. this._createBrightPassPostProcess(scene, ratio);
  50430. // Down sample X4
  50431. this._createDownSampleX4PostProcess(scene, ratio);
  50432. // Create gaussian blur post-processes
  50433. this._createGaussianBlurPostProcess(scene, ratio);
  50434. // Texture adder
  50435. this._createTextureAdderPostProcess(scene, ratio);
  50436. // Luminance generator
  50437. this._createLuminanceGeneratorPostProcess(scene);
  50438. // HDR
  50439. this._createHDRPostProcess(scene, ratio);
  50440. // Pass postprocess
  50441. if (originalPostProcess === null) {
  50442. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50443. }
  50444. else {
  50445. this._originalPostProcess = originalPostProcess;
  50446. }
  50447. // Configure pipeline
  50448. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  50449. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  50450. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  50451. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  50452. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  50453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  50454. var addDownSamplerPostProcess = function (id) {
  50455. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  50456. };
  50457. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  50458. addDownSamplerPostProcess(i);
  50459. }
  50460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  50461. // Finish
  50462. scene.postProcessRenderPipelineManager.addPipeline(this);
  50463. if (cameras !== null) {
  50464. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50465. }
  50466. this.update();
  50467. }
  50468. /**
  50469. * Tells the pipeline to update its post-processes
  50470. */
  50471. HDRRenderingPipeline.prototype.update = function () {
  50472. this._needUpdate = true;
  50473. };
  50474. /**
  50475. * Returns the current calculated luminance
  50476. */
  50477. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  50478. return this._hdrCurrentLuminance;
  50479. };
  50480. /**
  50481. * Returns the currently drawn luminance
  50482. */
  50483. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  50484. return this._hdrOutputLuminance;
  50485. };
  50486. /**
  50487. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  50488. */
  50489. HDRRenderingPipeline.prototype.dispose = function () {
  50490. this._originalPostProcess = undefined;
  50491. this._brightPassPostProcess = undefined;
  50492. this._downSampleX4PostProcess = undefined;
  50493. this._guassianBlurHPostProcess = undefined;
  50494. this._guassianBlurVPostProcess = undefined;
  50495. this._textureAdderPostProcess = undefined;
  50496. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  50497. this._downSamplePostProcesses[i] = undefined;
  50498. }
  50499. this._hdrPostProcess = undefined;
  50500. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50501. };
  50502. /**
  50503. * Creates the HDR post-process and computes the luminance adaptation
  50504. */
  50505. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  50506. var _this = this;
  50507. var hdrLastLuminance = 0.0;
  50508. this._hdrOutputLuminance = -1.0;
  50509. this._hdrCurrentLuminance = 1.0;
  50510. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  50511. this._hdrPostProcess.onApply = function (effect) {
  50512. if (_this._hdrOutputLuminance < 0.0) {
  50513. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  50514. }
  50515. else {
  50516. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  50517. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  50518. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  50519. }
  50520. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  50521. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  50522. }
  50523. else {
  50524. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  50525. }
  50526. }
  50527. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  50528. hdrLastLuminance += scene.getEngine().getDeltaTime();
  50529. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  50530. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  50531. effect.setFloat("exposure", _this.exposure);
  50532. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  50533. _this._needUpdate = false;
  50534. };
  50535. };
  50536. /**
  50537. * Texture Adder post-process
  50538. */
  50539. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50540. var _this = this;
  50541. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  50542. this._textureAdderPostProcess.onApply = function (effect) {
  50543. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  50544. };
  50545. };
  50546. /**
  50547. * Down sample X4 post-process
  50548. */
  50549. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50550. var _this = this;
  50551. var downSampleX4Offsets = new Array(32);
  50552. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  50553. this._downSampleX4PostProcess.onApply = function (effect) {
  50554. if (_this._needUpdate) {
  50555. var id = 0;
  50556. for (var i = -2; i < 2; i++) {
  50557. for (var j = -2; j < 2; j++) {
  50558. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  50559. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  50560. id += 2;
  50561. }
  50562. }
  50563. }
  50564. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50565. };
  50566. };
  50567. /**
  50568. * Bright pass post-process
  50569. */
  50570. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50571. var _this = this;
  50572. var brightOffsets = new Array(8);
  50573. var brightPassCallback = function (effect) {
  50574. if (_this._needUpdate) {
  50575. var sU = (1.0 / _this._brightPassPostProcess.width);
  50576. var sV = (1.0 / _this._brightPassPostProcess.height);
  50577. brightOffsets[0] = -0.5 * sU;
  50578. brightOffsets[1] = 0.5 * sV;
  50579. brightOffsets[2] = 0.5 * sU;
  50580. brightOffsets[3] = 0.5 * sV;
  50581. brightOffsets[4] = -0.5 * sU;
  50582. brightOffsets[5] = -0.5 * sV;
  50583. brightOffsets[6] = 0.5 * sU;
  50584. brightOffsets[7] = -0.5 * sV;
  50585. }
  50586. effect.setArray2("dsOffsets", brightOffsets);
  50587. effect.setFloat("brightThreshold", _this.brightThreshold);
  50588. };
  50589. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  50590. this._brightPassPostProcess.onApply = brightPassCallback;
  50591. };
  50592. /**
  50593. * Luminance generator. Creates the luminance post-process and down sample post-processes
  50594. */
  50595. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  50596. var _this = this;
  50597. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  50598. var luminanceOffsets = new Array(8);
  50599. var downSampleOffsets = new Array(18);
  50600. var halfDestPixelSize;
  50601. this._downSamplePostProcesses = new Array(lumSteps);
  50602. // Utils for luminance
  50603. var luminanceUpdateSourceOffsets = function (width, height) {
  50604. var sU = (1.0 / width);
  50605. var sV = (1.0 / height);
  50606. luminanceOffsets[0] = -0.5 * sU;
  50607. luminanceOffsets[1] = 0.5 * sV;
  50608. luminanceOffsets[2] = 0.5 * sU;
  50609. luminanceOffsets[3] = 0.5 * sV;
  50610. luminanceOffsets[4] = -0.5 * sU;
  50611. luminanceOffsets[5] = -0.5 * sV;
  50612. luminanceOffsets[6] = 0.5 * sU;
  50613. luminanceOffsets[7] = -0.5 * sV;
  50614. };
  50615. var luminanceUpdateDestOffsets = function (width, height) {
  50616. var id = 0;
  50617. for (var x = -1; x < 2; x++) {
  50618. for (var y = -1; y < 2; y++) {
  50619. downSampleOffsets[id] = (x) / width;
  50620. downSampleOffsets[id + 1] = (y) / height;
  50621. id += 2;
  50622. }
  50623. }
  50624. };
  50625. // Luminance callback
  50626. var luminanceCallback = function (effect) {
  50627. if (_this._needUpdate) {
  50628. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  50629. }
  50630. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  50631. effect.setArray2("lumOffsets", luminanceOffsets);
  50632. };
  50633. // Down sample callbacks
  50634. var downSampleCallback = function (indice) {
  50635. var i = indice;
  50636. return function (effect) {
  50637. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  50638. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  50639. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  50640. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  50641. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  50642. effect.setArray2("dsOffsets", downSampleOffsets);
  50643. };
  50644. };
  50645. var downSampleAfterRenderCallback = function (effect) {
  50646. // Unpack result
  50647. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50648. 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);
  50649. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50650. };
  50651. // Create luminance post-process
  50652. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  50653. 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);
  50654. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  50655. // Create down sample post-processes
  50656. for (var i = lumSteps - 2; i >= 0; i--) {
  50657. var length = Math.pow(3, i);
  50658. ratio = { width: length, height: length };
  50659. var defines = "#define DOWN_SAMPLE\n";
  50660. if (i === 0) {
  50661. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  50662. }
  50663. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  50664. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  50665. if (i === 0) {
  50666. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  50667. }
  50668. }
  50669. };
  50670. /**
  50671. * Gaussian blur post-processes. Horizontal and Vertical
  50672. */
  50673. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  50674. var _this = this;
  50675. var blurOffsetsW = new Array(9);
  50676. var blurOffsetsH = new Array(9);
  50677. var blurWeights = new Array(9);
  50678. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  50679. // Utils for gaussian blur
  50680. var calculateBlurOffsets = function (height) {
  50681. var lastOutputDimensions = {
  50682. width: scene.getEngine().getRenderWidth(),
  50683. height: scene.getEngine().getRenderHeight()
  50684. };
  50685. for (var i = 0; i < 9; i++) {
  50686. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  50687. if (height) {
  50688. blurOffsetsH[i] = value;
  50689. }
  50690. else {
  50691. blurOffsetsW[i] = value;
  50692. }
  50693. }
  50694. };
  50695. var calculateWeights = function () {
  50696. var x = 0.0;
  50697. for (var i = 0; i < 9; i++) {
  50698. x = (i - 4.0) / 4.0;
  50699. 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));
  50700. }
  50701. };
  50702. // Callback
  50703. var gaussianBlurCallback = function (height) {
  50704. return function (effect) {
  50705. if (_this._needUpdate) {
  50706. calculateWeights();
  50707. calculateBlurOffsets(height);
  50708. }
  50709. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  50710. effect.setArray("blurWeights", blurWeights);
  50711. effect.setFloat("multiplier", _this.gaussMultiplier);
  50712. };
  50713. };
  50714. // Create horizontal gaussian blur post-processes
  50715. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  50716. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  50717. // Create vertical gaussian blur post-process
  50718. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  50719. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  50720. };
  50721. // Luminance generator
  50722. HDRRenderingPipeline.LUM_STEPS = 6;
  50723. return HDRRenderingPipeline;
  50724. })(BABYLON.PostProcessRenderPipeline);
  50725. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  50726. })(BABYLON || (BABYLON = {}));
  50727. var BABYLON;
  50728. (function (BABYLON) {
  50729. var FaceAdjacencies = (function () {
  50730. function FaceAdjacencies() {
  50731. this.edges = new Array();
  50732. this.edgesConnectedCount = 0;
  50733. }
  50734. return FaceAdjacencies;
  50735. })();
  50736. var EdgesRenderer = (function () {
  50737. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  50738. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  50739. if (epsilon === void 0) { epsilon = 0.95; }
  50740. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  50741. this.edgesWidthScalerForOrthographic = 1000.0;
  50742. this.edgesWidthScalerForPerspective = 50.0;
  50743. this._linesPositions = new Array();
  50744. this._linesNormals = new Array();
  50745. this._linesIndices = new Array();
  50746. this._buffers = {};
  50747. this._checkVerticesInsteadOfIndices = false;
  50748. this._source = source;
  50749. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  50750. this._epsilon = epsilon;
  50751. this._prepareRessources();
  50752. this._generateEdgesLines();
  50753. }
  50754. EdgesRenderer.prototype._prepareRessources = function () {
  50755. if (this._lineShader) {
  50756. return;
  50757. }
  50758. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  50759. attributes: ["position", "normal"],
  50760. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  50761. });
  50762. this._lineShader.disableDepthWrite = true;
  50763. this._lineShader.backFaceCulling = false;
  50764. };
  50765. EdgesRenderer.prototype.dispose = function () {
  50766. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  50767. if (buffer) {
  50768. buffer.dispose();
  50769. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  50770. }
  50771. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  50772. if (buffer) {
  50773. buffer.dispose();
  50774. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  50775. }
  50776. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  50777. this._lineShader.dispose();
  50778. };
  50779. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  50780. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  50781. return 0;
  50782. }
  50783. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  50784. return 1;
  50785. }
  50786. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  50787. return 2;
  50788. }
  50789. return -1;
  50790. };
  50791. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  50792. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  50793. return 0;
  50794. }
  50795. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  50796. return 1;
  50797. }
  50798. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  50799. return 2;
  50800. }
  50801. return -1;
  50802. };
  50803. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  50804. var needToCreateLine;
  50805. if (edge === undefined) {
  50806. needToCreateLine = true;
  50807. }
  50808. else {
  50809. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  50810. needToCreateLine = dotProduct < this._epsilon;
  50811. }
  50812. if (needToCreateLine) {
  50813. var offset = this._linesPositions.length / 3;
  50814. var normal = p0.subtract(p1);
  50815. normal.normalize();
  50816. // Positions
  50817. this._linesPositions.push(p0.x);
  50818. this._linesPositions.push(p0.y);
  50819. this._linesPositions.push(p0.z);
  50820. this._linesPositions.push(p0.x);
  50821. this._linesPositions.push(p0.y);
  50822. this._linesPositions.push(p0.z);
  50823. this._linesPositions.push(p1.x);
  50824. this._linesPositions.push(p1.y);
  50825. this._linesPositions.push(p1.z);
  50826. this._linesPositions.push(p1.x);
  50827. this._linesPositions.push(p1.y);
  50828. this._linesPositions.push(p1.z);
  50829. // Normals
  50830. this._linesNormals.push(p1.x);
  50831. this._linesNormals.push(p1.y);
  50832. this._linesNormals.push(p1.z);
  50833. this._linesNormals.push(-1);
  50834. this._linesNormals.push(p1.x);
  50835. this._linesNormals.push(p1.y);
  50836. this._linesNormals.push(p1.z);
  50837. this._linesNormals.push(1);
  50838. this._linesNormals.push(p0.x);
  50839. this._linesNormals.push(p0.y);
  50840. this._linesNormals.push(p0.z);
  50841. this._linesNormals.push(-1);
  50842. this._linesNormals.push(p0.x);
  50843. this._linesNormals.push(p0.y);
  50844. this._linesNormals.push(p0.z);
  50845. this._linesNormals.push(1);
  50846. // Indices
  50847. this._linesIndices.push(offset);
  50848. this._linesIndices.push(offset + 1);
  50849. this._linesIndices.push(offset + 2);
  50850. this._linesIndices.push(offset);
  50851. this._linesIndices.push(offset + 2);
  50852. this._linesIndices.push(offset + 3);
  50853. }
  50854. };
  50855. EdgesRenderer.prototype._generateEdgesLines = function () {
  50856. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50857. var indices = this._source.getIndices();
  50858. // First let's find adjacencies
  50859. var adjacencies = new Array();
  50860. var faceNormals = new Array();
  50861. var index;
  50862. var faceAdjacencies;
  50863. // Prepare faces
  50864. for (index = 0; index < indices.length; index += 3) {
  50865. faceAdjacencies = new FaceAdjacencies();
  50866. var p0Index = indices[index];
  50867. var p1Index = indices[index + 1];
  50868. var p2Index = indices[index + 2];
  50869. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  50870. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  50871. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  50872. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  50873. faceNormal.normalize();
  50874. faceNormals.push(faceNormal);
  50875. adjacencies.push(faceAdjacencies);
  50876. }
  50877. // Scan
  50878. for (index = 0; index < adjacencies.length; index++) {
  50879. faceAdjacencies = adjacencies[index];
  50880. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  50881. var otherFaceAdjacencies = adjacencies[otherIndex];
  50882. if (faceAdjacencies.edgesConnectedCount === 3) {
  50883. break;
  50884. }
  50885. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  50886. continue;
  50887. }
  50888. var otherP0 = indices[otherIndex * 3];
  50889. var otherP1 = indices[otherIndex * 3 + 1];
  50890. var otherP2 = indices[otherIndex * 3 + 2];
  50891. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  50892. var otherEdgeIndex;
  50893. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  50894. continue;
  50895. }
  50896. switch (edgeIndex) {
  50897. case 0:
  50898. if (this._checkVerticesInsteadOfIndices) {
  50899. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  50900. }
  50901. else {
  50902. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  50903. }
  50904. break;
  50905. case 1:
  50906. if (this._checkVerticesInsteadOfIndices) {
  50907. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  50908. }
  50909. else {
  50910. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  50911. }
  50912. break;
  50913. case 2:
  50914. if (this._checkVerticesInsteadOfIndices) {
  50915. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  50916. }
  50917. else {
  50918. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  50919. }
  50920. break;
  50921. }
  50922. if (otherEdgeIndex === -1) {
  50923. continue;
  50924. }
  50925. faceAdjacencies.edges[edgeIndex] = otherIndex;
  50926. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  50927. faceAdjacencies.edgesConnectedCount++;
  50928. otherFaceAdjacencies.edgesConnectedCount++;
  50929. if (faceAdjacencies.edgesConnectedCount === 3) {
  50930. break;
  50931. }
  50932. }
  50933. }
  50934. }
  50935. // Create lines
  50936. for (index = 0; index < adjacencies.length; index++) {
  50937. // 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
  50938. var current = adjacencies[index];
  50939. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  50940. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  50941. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  50942. }
  50943. // Merge into a single mesh
  50944. var engine = this._source.getScene().getEngine();
  50945. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  50946. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  50947. this._ib = engine.createIndexBuffer(this._linesIndices);
  50948. this._indicesCount = this._linesIndices.length;
  50949. };
  50950. EdgesRenderer.prototype.render = function () {
  50951. if (!this._lineShader.isReady()) {
  50952. return;
  50953. }
  50954. var scene = this._source.getScene();
  50955. var engine = scene.getEngine();
  50956. this._lineShader._preBind();
  50957. // VBOs
  50958. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  50959. scene.resetCachedMaterial();
  50960. this._lineShader.setColor4("color", this._source.edgesColor);
  50961. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  50962. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  50963. }
  50964. else {
  50965. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  50966. }
  50967. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  50968. this._lineShader.bind(this._source.getWorldMatrix());
  50969. // Draw order
  50970. engine.draw(true, 0, this._indicesCount);
  50971. this._lineShader.unbind();
  50972. engine.setDepthWrite(true);
  50973. };
  50974. return EdgesRenderer;
  50975. })();
  50976. BABYLON.EdgesRenderer = EdgesRenderer;
  50977. })(BABYLON || (BABYLON = {}));
  50978. var BABYLON;
  50979. (function (BABYLON) {
  50980. (function (TonemappingOperator) {
  50981. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  50982. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  50983. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  50984. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  50985. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  50986. var TonemappingOperator = BABYLON.TonemappingOperator;
  50987. ;
  50988. var TonemapPostProcess = (function (_super) {
  50989. __extends(TonemapPostProcess, _super);
  50990. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  50991. var _this = this;
  50992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50993. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50994. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  50995. this._operator = _operator;
  50996. this.exposureAdjustment = exposureAdjustment;
  50997. var defines = "#define ";
  50998. if (this._operator === TonemappingOperator.Hable)
  50999. defines += "HABLE_TONEMAPPING";
  51000. else if (this._operator === TonemappingOperator.Reinhard)
  51001. defines += "REINHARD_TONEMAPPING";
  51002. else if (this._operator === TonemappingOperator.HejiDawson)
  51003. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51004. else if (this._operator === TonemappingOperator.Photographic)
  51005. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51006. //sadly a second call to create the effect.
  51007. this.updateEffect(defines);
  51008. this.onApply = function (effect) {
  51009. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51010. };
  51011. }
  51012. return TonemapPostProcess;
  51013. })(BABYLON.PostProcess);
  51014. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51015. })(BABYLON || (BABYLON = {}));
  51016. var BABYLON;
  51017. (function (BABYLON) {
  51018. var ReflectionProbe = (function () {
  51019. function ReflectionProbe(name, size, scene, generateMipMaps) {
  51020. var _this = this;
  51021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51022. this.name = name;
  51023. this._viewMatrix = BABYLON.Matrix.Identity();
  51024. this._target = BABYLON.Vector3.Zero();
  51025. this._add = BABYLON.Vector3.Zero();
  51026. this.invertYAxis = false;
  51027. this.position = BABYLON.Vector3.Zero();
  51028. this._scene = scene;
  51029. this._scene.reflectionProbes.push(this);
  51030. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  51031. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  51032. switch (faceIndex) {
  51033. case 0:
  51034. _this._add.copyFromFloats(1, 0, 0);
  51035. break;
  51036. case 1:
  51037. _this._add.copyFromFloats(-1, 0, 0);
  51038. break;
  51039. case 2:
  51040. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  51041. break;
  51042. case 3:
  51043. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  51044. break;
  51045. case 4:
  51046. _this._add.copyFromFloats(0, 0, 1);
  51047. break;
  51048. case 5:
  51049. _this._add.copyFromFloats(0, 0, -1);
  51050. break;
  51051. }
  51052. if (_this._attachedMesh) {
  51053. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  51054. }
  51055. _this.position.addToRef(_this._add, _this._target);
  51056. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  51057. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  51058. });
  51059. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  51060. scene.updateTransformMatrix(true);
  51061. });
  51062. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  51063. }
  51064. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  51065. get: function () {
  51066. return this._renderTargetTexture.refreshRate;
  51067. },
  51068. set: function (value) {
  51069. this._renderTargetTexture.refreshRate = value;
  51070. },
  51071. enumerable: true,
  51072. configurable: true
  51073. });
  51074. ReflectionProbe.prototype.getScene = function () {
  51075. return this._scene;
  51076. };
  51077. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  51078. get: function () {
  51079. return this._renderTargetTexture;
  51080. },
  51081. enumerable: true,
  51082. configurable: true
  51083. });
  51084. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  51085. get: function () {
  51086. return this._renderTargetTexture.renderList;
  51087. },
  51088. enumerable: true,
  51089. configurable: true
  51090. });
  51091. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  51092. this._attachedMesh = mesh;
  51093. };
  51094. ReflectionProbe.prototype.dispose = function () {
  51095. var index = this._scene.reflectionProbes.indexOf(this);
  51096. if (index !== -1) {
  51097. // Remove from the scene if found
  51098. this._scene.reflectionProbes.splice(index, 1);
  51099. }
  51100. if (this._renderTargetTexture) {
  51101. this._renderTargetTexture.dispose();
  51102. this._renderTargetTexture = null;
  51103. }
  51104. };
  51105. return ReflectionProbe;
  51106. })();
  51107. BABYLON.ReflectionProbe = ReflectionProbe;
  51108. })(BABYLON || (BABYLON = {}));
  51109. var BABYLON;
  51110. (function (BABYLON) {
  51111. var SolidParticle = (function () {
  51112. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  51113. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  51114. this.position = BABYLON.Vector3.Zero(); // position
  51115. this.rotation = BABYLON.Vector3.Zero(); // rotation
  51116. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  51117. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  51118. this.velocity = BABYLON.Vector3.Zero(); // velocity
  51119. this.alive = true; // alive
  51120. this.isVisible = true; // visibility
  51121. this.idx = particleIndex;
  51122. this._pos = positionIndex;
  51123. this._model = model;
  51124. this.shapeId = shapeId;
  51125. this.idxInShape = idxInShape;
  51126. }
  51127. Object.defineProperty(SolidParticle.prototype, "scale", {
  51128. //legacy support, changed scale to scaling
  51129. get: function () {
  51130. return this.scaling;
  51131. },
  51132. set: function (scale) {
  51133. this.scaling = scale;
  51134. },
  51135. enumerable: true,
  51136. configurable: true
  51137. });
  51138. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51139. //legacy support, changed quaternion to rotationQuaternion
  51140. get: function () {
  51141. return this.rotationQuaternion;
  51142. },
  51143. set: function (q) {
  51144. this.rotationQuaternion = q;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. return SolidParticle;
  51150. })();
  51151. BABYLON.SolidParticle = SolidParticle;
  51152. var ModelShape = (function () {
  51153. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  51154. this.shapeID = id;
  51155. this._shape = shape;
  51156. this._shapeUV = shapeUV;
  51157. this._positionFunction = posFunction;
  51158. this._vertexFunction = vtxFunction;
  51159. }
  51160. return ModelShape;
  51161. })();
  51162. BABYLON.ModelShape = ModelShape;
  51163. })(BABYLON || (BABYLON = {}));
  51164. var BABYLON;
  51165. (function (BABYLON) {
  51166. /**
  51167. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51168. */
  51169. var SolidParticleSystem = (function () {
  51170. /**
  51171. * Creates a SPS (Solid Particle System) object.
  51172. * `name` (String) is the SPS name, this will be the underlying mesh name.
  51173. * `scene` (Scene) is the scene in which the SPS is added.
  51174. * `updatable` (default true) : if the SPS must be updatable or immutable.
  51175. * `isPickable` (default false) : if the solid particles must be pickable.
  51176. */
  51177. function SolidParticleSystem(name, scene, options) {
  51178. // public members
  51179. /**
  51180. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51181. * Example : var p = SPS.particles[i];
  51182. */
  51183. this.particles = new Array();
  51184. /**
  51185. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51186. */
  51187. this.nbParticles = 0;
  51188. /**
  51189. * If the particles must ever face the camera (default false). Useful for planar particles.
  51190. */
  51191. this.billboard = false;
  51192. /**
  51193. * This a counter ofr your own usage. It's not set by any SPS functions.
  51194. */
  51195. this.counter = 0;
  51196. /**
  51197. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51198. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51199. */
  51200. this.vars = {};
  51201. this._positions = new Array();
  51202. this._indices = new Array();
  51203. this._normals = new Array();
  51204. this._colors = new Array();
  51205. this._uvs = new Array();
  51206. this._index = 0; // indices index
  51207. this._updatable = true;
  51208. this._pickable = false;
  51209. this._isVisibilityBoxLocked = false;
  51210. this._alwaysVisible = false;
  51211. this._shapeCounter = 0;
  51212. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  51213. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51214. this._computeParticleColor = true;
  51215. this._computeParticleTexture = true;
  51216. this._computeParticleRotation = true;
  51217. this._computeParticleVertex = false;
  51218. this._computeBoundingBox = false;
  51219. this._cam_axisZ = BABYLON.Vector3.Zero();
  51220. this._cam_axisY = BABYLON.Vector3.Zero();
  51221. this._cam_axisX = BABYLON.Vector3.Zero();
  51222. this._axisX = BABYLON.Axis.X;
  51223. this._axisY = BABYLON.Axis.Y;
  51224. this._axisZ = BABYLON.Axis.Z;
  51225. this._fakeCamPos = BABYLON.Vector3.Zero();
  51226. this._rotMatrix = new BABYLON.Matrix();
  51227. this._invertMatrix = new BABYLON.Matrix();
  51228. this._rotated = BABYLON.Vector3.Zero();
  51229. this._quaternion = new BABYLON.Quaternion();
  51230. this._vertex = BABYLON.Vector3.Zero();
  51231. this._normal = BABYLON.Vector3.Zero();
  51232. this._yaw = 0.0;
  51233. this._pitch = 0.0;
  51234. this._roll = 0.0;
  51235. this._halfroll = 0.0;
  51236. this._halfpitch = 0.0;
  51237. this._halfyaw = 0.0;
  51238. this._sinRoll = 0.0;
  51239. this._cosRoll = 0.0;
  51240. this._sinPitch = 0.0;
  51241. this._cosPitch = 0.0;
  51242. this._sinYaw = 0.0;
  51243. this._cosYaw = 0.0;
  51244. this._w = 0.0;
  51245. this._minimum = BABYLON.Tmp.Vector3[0];
  51246. this._maximum = BABYLON.Tmp.Vector3[1];
  51247. this.name = name;
  51248. this._scene = scene;
  51249. this._camera = scene.activeCamera;
  51250. this._pickable = options ? options.isPickable : false;
  51251. if (options && options.updatable) {
  51252. this._updatable = options.updatable;
  51253. }
  51254. else {
  51255. this._updatable = true;
  51256. }
  51257. if (this._pickable) {
  51258. this.pickedParticles = [];
  51259. }
  51260. }
  51261. /**
  51262. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51263. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51264. */
  51265. SolidParticleSystem.prototype.buildMesh = function () {
  51266. if (this.nbParticles === 0) {
  51267. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51268. this.addShape(triangle, 1);
  51269. triangle.dispose();
  51270. }
  51271. this._positions32 = new Float32Array(this._positions);
  51272. this._uvs32 = new Float32Array(this._uvs);
  51273. this._colors32 = new Float32Array(this._colors);
  51274. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  51275. this._normals32 = new Float32Array(this._normals);
  51276. this._fixedNormal32 = new Float32Array(this._normals);
  51277. var vertexData = new BABYLON.VertexData();
  51278. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51279. vertexData.indices = this._indices;
  51280. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51281. if (this._uvs32) {
  51282. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51283. ;
  51284. }
  51285. if (this._colors32) {
  51286. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51287. }
  51288. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51289. vertexData.applyToMesh(mesh, this._updatable);
  51290. this.mesh = mesh;
  51291. this.mesh.isPickable = this._pickable;
  51292. // free memory
  51293. this._positions = null;
  51294. this._normals = null;
  51295. this._uvs = null;
  51296. this._colors = null;
  51297. if (!this._updatable) {
  51298. this.particles.length = 0;
  51299. }
  51300. return mesh;
  51301. };
  51302. /**
  51303. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51304. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51305. * Thus the particles generated from `digest()` have their property `position` set yet.
  51306. * `mesh` ( Mesh ) is the mesh to be digested
  51307. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  51308. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51309. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51310. */
  51311. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51312. var size = (options && options.facetNb) || 1;
  51313. var number = (options && options.number);
  51314. var delta = (options && options.delta) || 0;
  51315. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51316. var meshInd = mesh.getIndices();
  51317. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51318. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51319. var f = 0; // facet counter
  51320. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51321. // compute size from number
  51322. if (number) {
  51323. number = (number > totalFacets) ? totalFacets : number;
  51324. size = Math.round(totalFacets / number);
  51325. delta = 0;
  51326. }
  51327. else {
  51328. size = (size > totalFacets) ? totalFacets : size;
  51329. }
  51330. var facetPos = []; // submesh positions
  51331. var facetInd = []; // submesh indices
  51332. var facetUV = []; // submesh UV
  51333. var facetCol = []; // submesh colors
  51334. var barycenter = BABYLON.Tmp.Vector3[0];
  51335. var rand;
  51336. var sizeO = size;
  51337. while (f < totalFacets) {
  51338. size = sizeO + Math.floor((1 + delta) * Math.random());
  51339. if (f > totalFacets - size) {
  51340. size = totalFacets - f;
  51341. }
  51342. // reset temp arrays
  51343. facetPos.length = 0;
  51344. facetInd.length = 0;
  51345. facetUV.length = 0;
  51346. facetCol.length = 0;
  51347. // iterate over "size" facets
  51348. var fi = 0;
  51349. for (var j = f * 3; j < (f + size) * 3; j++) {
  51350. facetInd.push(fi);
  51351. var i = meshInd[j];
  51352. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51353. if (meshUV) {
  51354. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51355. }
  51356. if (meshCol) {
  51357. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51358. }
  51359. fi++;
  51360. }
  51361. // create a model shape for each single particle
  51362. var idx = this.nbParticles;
  51363. var shape = this._posToShape(facetPos);
  51364. var shapeUV = this._uvsToShapeUV(facetUV);
  51365. // compute the barycenter of the shape
  51366. var v;
  51367. for (v = 0; v < shape.length; v++) {
  51368. barycenter.addInPlace(shape[v]);
  51369. }
  51370. barycenter.scaleInPlace(1 / shape.length);
  51371. // shift the shape from its barycenter to the origin
  51372. for (v = 0; v < shape.length; v++) {
  51373. shape[v].subtractInPlace(barycenter);
  51374. }
  51375. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  51376. // add the particle in the SPS
  51377. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  51378. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  51379. // initialize the particle position
  51380. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51381. this._index += shape.length;
  51382. idx++;
  51383. this.nbParticles++;
  51384. this._shapeCounter++;
  51385. f += size;
  51386. }
  51387. return this;
  51388. };
  51389. //reset copy
  51390. SolidParticleSystem.prototype._resetCopy = function () {
  51391. this._copy.position.x = 0;
  51392. this._copy.position.y = 0;
  51393. this._copy.position.z = 0;
  51394. this._copy.rotation.x = 0;
  51395. this._copy.rotation.y = 0;
  51396. this._copy.rotation.z = 0;
  51397. this._copy.rotationQuaternion = null;
  51398. this._copy.scaling.x = 1;
  51399. this._copy.scaling.y = 1;
  51400. this._copy.scaling.z = 1;
  51401. this._copy.uvs.x = 0;
  51402. this._copy.uvs.y = 0;
  51403. this._copy.uvs.z = 1;
  51404. this._copy.uvs.w = 1;
  51405. this._copy.color = null;
  51406. };
  51407. // _meshBuilder : inserts the shape model in the global SPS mesh
  51408. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  51409. var i;
  51410. var u = 0;
  51411. var c = 0;
  51412. this._resetCopy();
  51413. if (options && options.positionFunction) {
  51414. options.positionFunction(this._copy, idx, idxInShape);
  51415. }
  51416. if (this._copy.rotationQuaternion) {
  51417. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51418. }
  51419. else {
  51420. this._yaw = this._copy.rotation.y;
  51421. this._pitch = this._copy.rotation.x;
  51422. this._roll = this._copy.rotation.z;
  51423. this._quaternionRotationYPR();
  51424. }
  51425. this._quaternionToRotationMatrix();
  51426. for (i = 0; i < shape.length; i++) {
  51427. this._vertex.x = shape[i].x;
  51428. this._vertex.y = shape[i].y;
  51429. this._vertex.z = shape[i].z;
  51430. if (options && options.vertexFunction) {
  51431. options.vertexFunction(this._copy, this._vertex, i);
  51432. }
  51433. this._vertex.x *= this._copy.scaling.x;
  51434. this._vertex.y *= this._copy.scaling.y;
  51435. this._vertex.z *= this._copy.scaling.z;
  51436. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51437. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51438. if (meshUV) {
  51439. 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);
  51440. u += 2;
  51441. }
  51442. if (this._copy.color) {
  51443. this._color = this._copy.color;
  51444. }
  51445. else if (meshCol && meshCol[c]) {
  51446. this._color.r = meshCol[c];
  51447. this._color.g = meshCol[c + 1];
  51448. this._color.b = meshCol[c + 2];
  51449. this._color.a = meshCol[c + 3];
  51450. }
  51451. else {
  51452. this._color.r = 1;
  51453. this._color.g = 1;
  51454. this._color.b = 1;
  51455. this._color.a = 1;
  51456. }
  51457. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51458. c += 4;
  51459. }
  51460. for (i = 0; i < meshInd.length; i++) {
  51461. indices.push(p + meshInd[i]);
  51462. }
  51463. if (this._pickable) {
  51464. var nbfaces = meshInd.length / 3;
  51465. for (i = 0; i < nbfaces; i++) {
  51466. this.pickedParticles.push({ idx: idx, faceId: i });
  51467. }
  51468. }
  51469. };
  51470. // returns a shape array from positions array
  51471. SolidParticleSystem.prototype._posToShape = function (positions) {
  51472. var shape = [];
  51473. for (var i = 0; i < positions.length; i += 3) {
  51474. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51475. }
  51476. return shape;
  51477. };
  51478. // returns a shapeUV array from a Vector4 uvs
  51479. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51480. var shapeUV = [];
  51481. if (uvs) {
  51482. for (var i = 0; i < uvs.length; i++)
  51483. shapeUV.push(uvs[i]);
  51484. }
  51485. return shapeUV;
  51486. };
  51487. // adds a new particle object in the particles array
  51488. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  51489. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  51490. };
  51491. /**
  51492. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51493. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51494. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  51495. * `nb` (positive integer) the number of particles to be created from this model
  51496. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  51497. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  51498. */
  51499. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51500. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51501. var meshInd = mesh.getIndices();
  51502. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51503. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51504. var shape = this._posToShape(meshPos);
  51505. var shapeUV = this._uvsToShapeUV(meshUV);
  51506. var posfunc = options ? options.positionFunction : null;
  51507. var vtxfunc = options ? options.vertexFunction : null;
  51508. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  51509. // particles
  51510. var idx = this.nbParticles;
  51511. for (var i = 0; i < nb; i++) {
  51512. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  51513. if (this._updatable) {
  51514. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  51515. }
  51516. this._index += shape.length;
  51517. idx++;
  51518. }
  51519. this.nbParticles += nb;
  51520. this._shapeCounter++;
  51521. return this._shapeCounter - 1;
  51522. };
  51523. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51524. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51525. this._resetCopy();
  51526. if (particle._model._positionFunction) {
  51527. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51528. }
  51529. if (this._copy.rotationQuaternion) {
  51530. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51531. }
  51532. else {
  51533. this._yaw = this._copy.rotation.y;
  51534. this._pitch = this._copy.rotation.x;
  51535. this._roll = this._copy.rotation.z;
  51536. this._quaternionRotationYPR();
  51537. }
  51538. this._quaternionToRotationMatrix();
  51539. this._shape = particle._model._shape;
  51540. for (var pt = 0; pt < this._shape.length; pt++) {
  51541. this._vertex.x = this._shape[pt].x;
  51542. this._vertex.y = this._shape[pt].y;
  51543. this._vertex.z = this._shape[pt].z;
  51544. if (particle._model._vertexFunction) {
  51545. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51546. }
  51547. this._vertex.x *= this._copy.scaling.x;
  51548. this._vertex.y *= this._copy.scaling.y;
  51549. this._vertex.z *= this._copy.scaling.z;
  51550. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51551. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51552. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51553. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51554. }
  51555. particle.position.x = 0;
  51556. particle.position.y = 0;
  51557. particle.position.z = 0;
  51558. particle.rotation.x = 0;
  51559. particle.rotation.y = 0;
  51560. particle.rotation.z = 0;
  51561. particle.rotationQuaternion = null;
  51562. particle.scaling.x = 1;
  51563. particle.scaling.y = 1;
  51564. particle.scaling.z = 1;
  51565. };
  51566. /**
  51567. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51568. */
  51569. SolidParticleSystem.prototype.rebuildMesh = function () {
  51570. for (var p = 0; p < this.particles.length; p++) {
  51571. this._rebuildParticle(this.particles[p]);
  51572. }
  51573. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51574. };
  51575. /**
  51576. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51577. * This method calls `updateParticle()` for each particle of the SPS.
  51578. * For an animated SPS, it is usually called within the render loop.
  51579. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51580. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51581. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51582. */
  51583. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51584. if (start === void 0) { start = 0; }
  51585. if (end === void 0) { end = this.nbParticles - 1; }
  51586. if (update === void 0) { update = true; }
  51587. if (!this._updatable) {
  51588. return;
  51589. }
  51590. // custom beforeUpdate
  51591. this.beforeUpdateParticles(start, end, update);
  51592. this._cam_axisX.x = 1;
  51593. this._cam_axisX.y = 0;
  51594. this._cam_axisX.z = 0;
  51595. this._cam_axisY.x = 0;
  51596. this._cam_axisY.y = 1;
  51597. this._cam_axisY.z = 0;
  51598. this._cam_axisZ.x = 0;
  51599. this._cam_axisZ.y = 0;
  51600. this._cam_axisZ.z = 1;
  51601. // if the particles will always face the camera
  51602. if (this.billboard) {
  51603. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  51604. this._yaw = this.mesh.rotation.y;
  51605. this._pitch = this.mesh.rotation.x;
  51606. this._roll = this.mesh.rotation.z;
  51607. this._quaternionRotationYPR();
  51608. this._quaternionToRotationMatrix();
  51609. this._rotMatrix.invertToRef(this._invertMatrix);
  51610. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  51611. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  51612. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  51613. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  51614. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  51615. this._cam_axisY.normalize();
  51616. this._cam_axisX.normalize();
  51617. this._cam_axisZ.normalize();
  51618. }
  51619. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51620. var idx = 0;
  51621. var index = 0;
  51622. var colidx = 0;
  51623. var colorIndex = 0;
  51624. var uvidx = 0;
  51625. var uvIndex = 0;
  51626. var pt = 0;
  51627. if (this._computeBoundingBox) {
  51628. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51629. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51630. }
  51631. // particle loop
  51632. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  51633. for (var p = start; p <= end; p++) {
  51634. this._particle = this.particles[p];
  51635. this._shape = this._particle._model._shape;
  51636. this._shapeUV = this._particle._model._shapeUV;
  51637. // call to custom user function to update the particle properties
  51638. this.updateParticle(this._particle);
  51639. if (this._particle.isVisible) {
  51640. // particle rotation matrix
  51641. if (this.billboard) {
  51642. this._particle.rotation.x = 0.0;
  51643. this._particle.rotation.y = 0.0;
  51644. }
  51645. if (this._computeParticleRotation) {
  51646. if (this._particle.rotationQuaternion) {
  51647. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51648. }
  51649. else {
  51650. this._yaw = this._particle.rotation.y;
  51651. this._pitch = this._particle.rotation.x;
  51652. this._roll = this._particle.rotation.z;
  51653. this._quaternionRotationYPR();
  51654. }
  51655. this._quaternionToRotationMatrix();
  51656. }
  51657. // particle vertex loop
  51658. for (pt = 0; pt < this._shape.length; pt++) {
  51659. idx = index + pt * 3;
  51660. colidx = colorIndex + pt * 4;
  51661. uvidx = uvIndex + pt * 2;
  51662. this._vertex.x = this._shape[pt].x;
  51663. this._vertex.y = this._shape[pt].y;
  51664. this._vertex.z = this._shape[pt].z;
  51665. if (this._computeParticleVertex) {
  51666. this.updateParticleVertex(this._particle, this._vertex, pt);
  51667. }
  51668. // positions
  51669. this._vertex.x *= this._particle.scaling.x;
  51670. this._vertex.y *= this._particle.scaling.y;
  51671. this._vertex.z *= this._particle.scaling.z;
  51672. 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];
  51673. 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;
  51674. 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;
  51675. 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;
  51676. 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;
  51677. 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;
  51678. 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;
  51679. if (this._computeBoundingBox) {
  51680. if (this._positions32[idx] < this._minimum.x) {
  51681. this._minimum.x = this._positions32[idx];
  51682. }
  51683. if (this._positions32[idx] > this._maximum.x) {
  51684. this._maximum.x = this._positions32[idx];
  51685. }
  51686. if (this._positions32[idx + 1] < this._minimum.y) {
  51687. this._minimum.y = this._positions32[idx + 1];
  51688. }
  51689. if (this._positions32[idx + 1] > this._maximum.y) {
  51690. this._maximum.y = this._positions32[idx + 1];
  51691. }
  51692. if (this._positions32[idx + 2] < this._minimum.z) {
  51693. this._minimum.z = this._positions32[idx + 2];
  51694. }
  51695. if (this._positions32[idx + 2] > this._maximum.z) {
  51696. this._maximum.z = this._positions32[idx + 2];
  51697. }
  51698. }
  51699. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  51700. if (!this._computeParticleVertex && !this.billboard) {
  51701. this._normal.x = this._fixedNormal32[idx];
  51702. this._normal.y = this._fixedNormal32[idx + 1];
  51703. this._normal.z = this._fixedNormal32[idx + 2];
  51704. 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];
  51705. 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;
  51706. 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;
  51707. 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;
  51708. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51709. 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;
  51710. 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;
  51711. }
  51712. if (this._computeParticleColor) {
  51713. this._colors32[colidx] = this._particle.color.r;
  51714. this._colors32[colidx + 1] = this._particle.color.g;
  51715. this._colors32[colidx + 2] = this._particle.color.b;
  51716. this._colors32[colidx + 3] = this._particle.color.a;
  51717. }
  51718. if (this._computeParticleTexture) {
  51719. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51720. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51721. }
  51722. }
  51723. }
  51724. else {
  51725. for (pt = 0; pt < this._shape.length; pt++) {
  51726. idx = index + pt * 3;
  51727. colidx = colorIndex + pt * 4;
  51728. uvidx = uvIndex + pt * 2;
  51729. this._positions32[idx] = this._camera.position.x;
  51730. this._positions32[idx + 1] = this._camera.position.y;
  51731. this._positions32[idx + 2] = this._camera.position.z;
  51732. this._normals32[idx] = 0.0;
  51733. this._normals32[idx + 1] = 0.0;
  51734. this._normals32[idx + 2] = 0.0;
  51735. if (this._computeParticleColor) {
  51736. this._colors32[colidx] = this._particle.color.r;
  51737. this._colors32[colidx + 1] = this._particle.color.g;
  51738. this._colors32[colidx + 2] = this._particle.color.b;
  51739. this._colors32[colidx + 3] = this._particle.color.a;
  51740. }
  51741. if (this._computeParticleTexture) {
  51742. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51743. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51744. }
  51745. }
  51746. }
  51747. // increment indexes for the next particle
  51748. index = idx + 3;
  51749. colorIndex = colidx + 4;
  51750. uvIndex = uvidx + 2;
  51751. }
  51752. // if the VBO must be updated
  51753. if (update) {
  51754. if (this._computeParticleColor) {
  51755. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  51756. }
  51757. if (this._computeParticleTexture) {
  51758. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  51759. }
  51760. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51761. if (!this.mesh.areNormalsFrozen) {
  51762. if (this._computeParticleVertex || this.billboard) {
  51763. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  51764. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  51765. for (var i = 0; i < this._normals32.length; i++) {
  51766. this._fixedNormal32[i] = this._normals32[i];
  51767. }
  51768. }
  51769. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  51770. }
  51771. }
  51772. if (this._computeBoundingBox) {
  51773. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  51774. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  51775. }
  51776. this.afterUpdateParticles(start, end, update);
  51777. };
  51778. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  51779. this._halfroll = this._roll * 0.5;
  51780. this._halfpitch = this._pitch * 0.5;
  51781. this._halfyaw = this._yaw * 0.5;
  51782. this._sinRoll = Math.sin(this._halfroll);
  51783. this._cosRoll = Math.cos(this._halfroll);
  51784. this._sinPitch = Math.sin(this._halfpitch);
  51785. this._cosPitch = Math.cos(this._halfpitch);
  51786. this._sinYaw = Math.sin(this._halfyaw);
  51787. this._cosYaw = Math.cos(this._halfyaw);
  51788. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  51789. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  51790. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  51791. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  51792. };
  51793. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  51794. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  51795. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  51796. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  51797. this._rotMatrix.m[3] = 0;
  51798. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  51799. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  51800. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  51801. this._rotMatrix.m[7] = 0;
  51802. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  51803. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  51804. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  51805. this._rotMatrix.m[11] = 0;
  51806. this._rotMatrix.m[12] = 0;
  51807. this._rotMatrix.m[13] = 0;
  51808. this._rotMatrix.m[14] = 0;
  51809. this._rotMatrix.m[15] = 1.0;
  51810. };
  51811. /**
  51812. * Disposes the SPS
  51813. */
  51814. SolidParticleSystem.prototype.dispose = function () {
  51815. this.mesh.dispose();
  51816. this.vars = null;
  51817. // drop references to internal big arrays for the GC
  51818. this._positions = null;
  51819. this._indices = null;
  51820. this._normals = null;
  51821. this._uvs = null;
  51822. this._colors = null;
  51823. this._positions32 = null;
  51824. this._normals32 = null;
  51825. this._fixedNormal32 = null;
  51826. this._uvs32 = null;
  51827. this._colors32 = null;
  51828. this.pickedParticles = null;
  51829. };
  51830. /**
  51831. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  51832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51833. */
  51834. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  51835. if (!this._isVisibilityBoxLocked) {
  51836. this.mesh.refreshBoundingInfo();
  51837. }
  51838. };
  51839. /**
  51840. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  51841. * @param size the size (float) of the visibility box
  51842. * note : this doesn't lock the SPS mesh bounding box.
  51843. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51844. */
  51845. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  51846. var vis = size / 2;
  51847. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  51848. };
  51849. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  51850. // getter and setter
  51851. get: function () {
  51852. return this._alwaysVisible;
  51853. },
  51854. /**
  51855. * Sets the SPS as always visible or not
  51856. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51857. */
  51858. set: function (val) {
  51859. this._alwaysVisible = val;
  51860. this.mesh.alwaysSelectAsActiveMesh = val;
  51861. },
  51862. enumerable: true,
  51863. configurable: true
  51864. });
  51865. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  51866. get: function () {
  51867. return this._isVisibilityBoxLocked;
  51868. },
  51869. /**
  51870. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  51871. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  51872. */
  51873. set: function (val) {
  51874. this._isVisibilityBoxLocked = val;
  51875. this.mesh.getBoundingInfo().isLocked = val;
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  51881. // getters
  51882. get: function () {
  51883. return this._computeParticleRotation;
  51884. },
  51885. // Optimizer setters
  51886. /**
  51887. * Tells to `setParticles()` to compute the particle rotations or not.
  51888. * Default value : true. The SPS is faster when it's set to false.
  51889. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  51890. */
  51891. set: function (val) {
  51892. this._computeParticleRotation = val;
  51893. },
  51894. enumerable: true,
  51895. configurable: true
  51896. });
  51897. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  51898. get: function () {
  51899. return this._computeParticleColor;
  51900. },
  51901. /**
  51902. * Tells to `setParticles()` to compute the particle colors or not.
  51903. * Default value : true. The SPS is faster when it's set to false.
  51904. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  51905. */
  51906. set: function (val) {
  51907. this._computeParticleColor = val;
  51908. },
  51909. enumerable: true,
  51910. configurable: true
  51911. });
  51912. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  51913. get: function () {
  51914. return this._computeParticleTexture;
  51915. },
  51916. /**
  51917. * Tells to `setParticles()` to compute the particle textures or not.
  51918. * Default value : true. The SPS is faster when it's set to false.
  51919. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  51920. */
  51921. set: function (val) {
  51922. this._computeParticleTexture = val;
  51923. },
  51924. enumerable: true,
  51925. configurable: true
  51926. });
  51927. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  51928. get: function () {
  51929. return this._computeParticleVertex;
  51930. },
  51931. /**
  51932. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  51933. * Default value : false. The SPS is faster when it's set to false.
  51934. * Note : the particle custom vertex positions aren't stored values.
  51935. */
  51936. set: function (val) {
  51937. this._computeParticleVertex = val;
  51938. },
  51939. enumerable: true,
  51940. configurable: true
  51941. });
  51942. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  51943. get: function () {
  51944. return this._computeBoundingBox;
  51945. },
  51946. /**
  51947. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  51948. */
  51949. set: function (val) {
  51950. this._computeBoundingBox = val;
  51951. },
  51952. enumerable: true,
  51953. configurable: true
  51954. });
  51955. // =======================================================================
  51956. // Particle behavior logic
  51957. // these following methods may be overwritten by the user to fit his needs
  51958. /**
  51959. * This function does nothing. It may be overwritten to set all the particle first values.
  51960. * The SPS doesn't call this function, you may have to call it by your own.
  51961. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51962. */
  51963. SolidParticleSystem.prototype.initParticles = function () {
  51964. };
  51965. /**
  51966. * This function does nothing. It may be overwritten to recycle a particle.
  51967. * The SPS doesn't call this function, you may have to call it by your own.
  51968. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51969. */
  51970. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  51971. return particle;
  51972. };
  51973. /**
  51974. * Updates a particle : this function should be overwritten by the user.
  51975. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  51976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51977. * ex : just set a particle position or velocity and recycle conditions
  51978. */
  51979. SolidParticleSystem.prototype.updateParticle = function (particle) {
  51980. return particle;
  51981. };
  51982. /**
  51983. * Updates a vertex of a particle : it can be overwritten by the user.
  51984. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  51985. * @param particle the current particle
  51986. * @param vertex the current index of the current particle
  51987. * @param pt the index of the current vertex in the particle shape
  51988. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  51989. * ex : just set a vertex particle position
  51990. */
  51991. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  51992. return vertex;
  51993. };
  51994. /**
  51995. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  51996. * This does nothing and may be overwritten by the user.
  51997. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51998. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51999. * @param update the boolean update value actually passed to setParticles()
  52000. */
  52001. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52002. };
  52003. /**
  52004. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52005. * This will be passed three parameters.
  52006. * This does nothing and may be overwritten by the user.
  52007. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52008. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52009. * @param update the boolean update value actually passed to setParticles()
  52010. */
  52011. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52012. };
  52013. return SolidParticleSystem;
  52014. })();
  52015. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52016. })(BABYLON || (BABYLON = {}));
  52017. var BABYLON;
  52018. (function (BABYLON) {
  52019. var Internals;
  52020. (function (Internals) {
  52021. var FileFaceOrientation = (function () {
  52022. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  52023. this.name = name;
  52024. this.worldAxisForNormal = worldAxisForNormal;
  52025. this.worldAxisForFileX = worldAxisForFileX;
  52026. this.worldAxisForFileY = worldAxisForFileY;
  52027. }
  52028. return FileFaceOrientation;
  52029. })();
  52030. ;
  52031. /**
  52032. * Helper class dealing with the extraction of spherical polynomial dataArray
  52033. * from a cube map.
  52034. */
  52035. var CubeMapToSphericalPolynomialTools = (function () {
  52036. function CubeMapToSphericalPolynomialTools() {
  52037. }
  52038. /**
  52039. * Converts a cubemap to the according Spherical Polynomial data.
  52040. * This extracts the first 3 orders only as they are the only one used in the lighting.
  52041. *
  52042. * @param cubeInfo The Cube map to extract the information from.
  52043. * @return The Spherical Polynomial data.
  52044. */
  52045. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  52046. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  52047. var totalSolidAngle = 0.0;
  52048. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  52049. var du = 2.0 / cubeInfo.size;
  52050. var dv = du;
  52051. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  52052. var minUV = du * 0.5 - 1.0;
  52053. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52054. var fileFace = this.FileFaces[faceIndex];
  52055. var dataArray = cubeInfo[fileFace.name];
  52056. var v = minUV;
  52057. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  52058. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  52059. // Because SP is still linear, so summation is fine in that basis.
  52060. for (var y = 0; y < cubeInfo.size; y++) {
  52061. var u = minUV;
  52062. for (var x = 0; x < cubeInfo.size; x++) {
  52063. // World direction (not normalised)
  52064. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  52065. worldDirection.normalize();
  52066. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  52067. if (1) {
  52068. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  52069. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  52070. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  52071. var color = new BABYLON.Color3(r, g, b);
  52072. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  52073. }
  52074. else {
  52075. if (faceIndex == 0) {
  52076. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  52077. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  52078. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  52079. }
  52080. else if (faceIndex == 1) {
  52081. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  52082. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  52083. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  52084. }
  52085. else if (faceIndex == 2) {
  52086. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  52087. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  52088. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  52089. }
  52090. else if (faceIndex == 3) {
  52091. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  52092. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  52093. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  52094. }
  52095. else if (faceIndex == 4) {
  52096. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  52097. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  52098. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  52099. }
  52100. else if (faceIndex == 5) {
  52101. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  52102. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  52103. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  52104. }
  52105. 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]);
  52106. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  52107. }
  52108. totalSolidAngle += deltaSolidAngle;
  52109. u += du;
  52110. }
  52111. v += dv;
  52112. }
  52113. }
  52114. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  52115. var correction = correctSolidAngle / totalSolidAngle;
  52116. sphericalHarmonics.scale(correction);
  52117. // Additionally scale by pi -- audit needed
  52118. sphericalHarmonics.scale(1.0 / Math.PI);
  52119. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  52120. };
  52121. CubeMapToSphericalPolynomialTools.FileFaces = [
  52122. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  52123. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  52124. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  52125. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  52126. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  52127. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  52128. ];
  52129. return CubeMapToSphericalPolynomialTools;
  52130. })();
  52131. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  52132. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52133. })(BABYLON || (BABYLON = {}));
  52134. var BABYLON;
  52135. (function (BABYLON) {
  52136. var Internals;
  52137. (function (Internals) {
  52138. /**
  52139. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  52140. */
  52141. var PanoramaToCubeMapTools = (function () {
  52142. function PanoramaToCubeMapTools() {
  52143. }
  52144. /**
  52145. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  52146. *
  52147. * @param float32Array The source data.
  52148. * @param inputWidth The width of the input panorama.
  52149. * @param inputhHeight The height of the input panorama.
  52150. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  52151. * @return The cubemap data
  52152. */
  52153. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  52154. if (!float32Array) {
  52155. throw "ConvertPanoramaToCubemap: input cannot be null";
  52156. }
  52157. if (float32Array.length != inputWidth * inputHeight * 3) {
  52158. throw "ConvertPanoramaToCubemap: input size is wrong";
  52159. }
  52160. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  52161. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  52162. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  52163. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  52164. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  52165. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  52166. return {
  52167. front: textureFront,
  52168. back: textureBack,
  52169. left: textureLeft,
  52170. right: textureRight,
  52171. up: textureUp,
  52172. down: textureDown,
  52173. size: size
  52174. };
  52175. };
  52176. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  52177. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  52178. var textureArray = new Float32Array(buffer);
  52179. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  52180. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  52181. var dy = 1 / texSize;
  52182. var fy = 0;
  52183. for (var y = 0; y < texSize; y++) {
  52184. var xv1 = faceData[0];
  52185. var xv2 = faceData[2];
  52186. for (var x = 0; x < texSize; x++) {
  52187. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  52188. v.normalize();
  52189. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  52190. // 3 channels per pixels
  52191. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  52192. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  52193. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  52194. xv1 = xv1.add(rotDX1);
  52195. xv2 = xv2.add(rotDX2);
  52196. }
  52197. fy += dy;
  52198. }
  52199. return textureArray;
  52200. };
  52201. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  52202. var theta = Math.atan2(vDir.z, vDir.x);
  52203. var phi = Math.acos(vDir.y);
  52204. while (theta < -Math.PI)
  52205. theta += 2 * Math.PI;
  52206. while (theta > Math.PI)
  52207. theta -= 2 * Math.PI;
  52208. var dx = theta / Math.PI;
  52209. var dy = phi / Math.PI;
  52210. // recenter.
  52211. dx = dx * 0.5 + 0.5;
  52212. var px = Math.round(dx * inputWidth);
  52213. if (px < 0)
  52214. px = 0;
  52215. else if (px >= inputWidth)
  52216. px = inputWidth - 1;
  52217. var py = Math.round(dy * inputHeight);
  52218. if (py < 0)
  52219. py = 0;
  52220. else if (py >= inputHeight)
  52221. py = inputHeight - 1;
  52222. var inputY = (inputHeight - py - 1);
  52223. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  52224. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  52225. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  52226. return {
  52227. r: r,
  52228. g: g,
  52229. b: b
  52230. };
  52231. };
  52232. PanoramaToCubeMapTools.FACE_FRONT = [
  52233. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  52234. new BABYLON.Vector3(1.0, -1.0, -1.0),
  52235. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  52236. new BABYLON.Vector3(1.0, 1.0, -1.0)
  52237. ];
  52238. PanoramaToCubeMapTools.FACE_BACK = [
  52239. new BABYLON.Vector3(1.0, -1.0, 1.0),
  52240. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  52241. new BABYLON.Vector3(1.0, 1.0, 1.0),
  52242. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  52243. ];
  52244. PanoramaToCubeMapTools.FACE_RIGHT = [
  52245. new BABYLON.Vector3(1.0, -1.0, -1.0),
  52246. new BABYLON.Vector3(1.0, -1.0, 1.0),
  52247. new BABYLON.Vector3(1.0, 1.0, -1.0),
  52248. new BABYLON.Vector3(1.0, 1.0, 1.0)
  52249. ];
  52250. PanoramaToCubeMapTools.FACE_LEFT = [
  52251. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  52252. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  52253. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  52254. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  52255. ];
  52256. PanoramaToCubeMapTools.FACE_DOWN = [
  52257. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  52258. new BABYLON.Vector3(1.0, 1.0, -1.0),
  52259. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  52260. new BABYLON.Vector3(1.0, 1.0, 1.0)
  52261. ];
  52262. PanoramaToCubeMapTools.FACE_UP = [
  52263. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  52264. new BABYLON.Vector3(1.0, -1.0, 1.0),
  52265. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  52266. new BABYLON.Vector3(1.0, -1.0, -1.0)
  52267. ];
  52268. return PanoramaToCubeMapTools;
  52269. })();
  52270. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  52271. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52272. })(BABYLON || (BABYLON = {}));
  52273. var BABYLON;
  52274. (function (BABYLON) {
  52275. var Internals;
  52276. (function (Internals) {
  52277. ;
  52278. /**
  52279. * This groups tools to convert HDR texture to native colors array.
  52280. */
  52281. var HDRTools = (function () {
  52282. function HDRTools() {
  52283. }
  52284. HDRTools.Ldexp = function (mantissa, exponent) {
  52285. if (exponent > 1023) {
  52286. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  52287. }
  52288. if (exponent < -1074) {
  52289. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  52290. }
  52291. return mantissa * Math.pow(2, exponent);
  52292. };
  52293. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  52294. if (exponent > 0) {
  52295. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  52296. float32array[index + 0] = red * exponent;
  52297. float32array[index + 1] = green * exponent;
  52298. float32array[index + 2] = blue * exponent;
  52299. }
  52300. else {
  52301. float32array[index + 0] = 0;
  52302. float32array[index + 1] = 0;
  52303. float32array[index + 2] = 0;
  52304. }
  52305. };
  52306. HDRTools.readStringLine = function (uint8array, startIndex) {
  52307. var line = "";
  52308. var character = "";
  52309. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  52310. character = String.fromCharCode(uint8array[i]);
  52311. if (character == "\n") {
  52312. break;
  52313. }
  52314. line += character;
  52315. }
  52316. return line;
  52317. };
  52318. /**
  52319. * Reads header information from an RGBE texture stored in a native array.
  52320. * More information on this format are available here:
  52321. * https://en.wikipedia.org/wiki/RGBE_image_format
  52322. *
  52323. * @param uint8array The binary file stored in native array.
  52324. * @return The header information.
  52325. */
  52326. HDRTools.RGBE_ReadHeader = function (uint8array) {
  52327. var height = 0;
  52328. var width = 0;
  52329. var line = this.readStringLine(uint8array, 0);
  52330. if (line[0] != '#' || line[1] != '?') {
  52331. throw "Bad HDR Format.";
  52332. }
  52333. var endOfHeader = false;
  52334. var findFormat = false;
  52335. var lineIndex = 0;
  52336. do {
  52337. lineIndex += (line.length + 1);
  52338. line = this.readStringLine(uint8array, lineIndex);
  52339. if (line == "FORMAT=32-bit_rle_rgbe") {
  52340. findFormat = true;
  52341. }
  52342. else if (line.length == 0) {
  52343. endOfHeader = true;
  52344. }
  52345. } while (!endOfHeader);
  52346. if (!findFormat) {
  52347. throw "HDR Bad header format, unsupported FORMAT";
  52348. }
  52349. lineIndex += (line.length + 1);
  52350. line = this.readStringLine(uint8array, lineIndex);
  52351. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  52352. var match = sizeRegexp.exec(line);
  52353. // TODO. Support +Y and -X if needed.
  52354. if (match.length < 3) {
  52355. throw "HDR Bad header format, no size";
  52356. }
  52357. width = parseInt(match[2]);
  52358. height = parseInt(match[1]);
  52359. if (width < 8 || width > 0x7fff) {
  52360. throw "HDR Bad header format, unsupported size";
  52361. }
  52362. lineIndex += (line.length + 1);
  52363. return {
  52364. height: height,
  52365. width: width,
  52366. dataPosition: lineIndex
  52367. };
  52368. };
  52369. /**
  52370. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  52371. * This RGBE texture needs to store the information as a panorama.
  52372. *
  52373. * More information on this format are available here:
  52374. * https://en.wikipedia.org/wiki/RGBE_image_format
  52375. *
  52376. * @param buffer The binary file stored in an array buffer.
  52377. * @param size The expected size of the extracted cubemap.
  52378. * @return The Cube Map information.
  52379. */
  52380. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  52381. var uint8array = new Uint8Array(buffer);
  52382. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  52383. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  52384. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  52385. return cubeMapData;
  52386. };
  52387. /**
  52388. * Returns the pixels data extracted from an RGBE texture.
  52389. * This pixels will be stored left to right up to down in the R G B order in one array.
  52390. *
  52391. * More information on this format are available here:
  52392. * https://en.wikipedia.org/wiki/RGBE_image_format
  52393. *
  52394. * @param uint8array The binary file stored in an array buffer.
  52395. * @param hdrInfo The header information of the file.
  52396. * @return The pixels data in RGB right to left up to down order.
  52397. */
  52398. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  52399. // Keep for multi format supports.
  52400. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  52401. };
  52402. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  52403. var num_scanlines = hdrInfo.height;
  52404. var scanline_width = hdrInfo.width;
  52405. var a, b, c, d, count;
  52406. var dataIndex = hdrInfo.dataPosition;
  52407. var index = 0, endIndex = 0, i = 0;
  52408. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  52409. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  52410. // 3 channels of 4 bytes per pixel in float.
  52411. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  52412. var resultArray = new Float32Array(resultBuffer);
  52413. // read in each successive scanline
  52414. while (num_scanlines > 0) {
  52415. a = uint8array[dataIndex++];
  52416. b = uint8array[dataIndex++];
  52417. c = uint8array[dataIndex++];
  52418. d = uint8array[dataIndex++];
  52419. if (a != 2 || b != 2 || (c & 0x80)) {
  52420. // this file is not run length encoded
  52421. throw "HDR Bad header format, not RLE";
  52422. }
  52423. if (((c << 8) | d) != scanline_width) {
  52424. throw "HDR Bad header format, wrong scan line width";
  52425. }
  52426. index = 0;
  52427. // read each of the four channels for the scanline into the buffer
  52428. for (i = 0; i < 4; i++) {
  52429. endIndex = (i + 1) * scanline_width;
  52430. while (index < endIndex) {
  52431. a = uint8array[dataIndex++];
  52432. b = uint8array[dataIndex++];
  52433. if (a > 128) {
  52434. // a run of the same value
  52435. count = a - 128;
  52436. if ((count == 0) || (count > endIndex - index)) {
  52437. throw "HDR Bad Format, bad scanline data (run)";
  52438. }
  52439. while (count-- > 0) {
  52440. scanLineArray[index++] = b;
  52441. }
  52442. }
  52443. else {
  52444. // a non-run
  52445. count = a;
  52446. if ((count == 0) || (count > endIndex - index)) {
  52447. throw "HDR Bad Format, bad scanline data (non-run)";
  52448. }
  52449. scanLineArray[index++] = b;
  52450. if (--count > 0) {
  52451. for (var j = 0; j < count; j++) {
  52452. scanLineArray[index++] = uint8array[dataIndex++];
  52453. }
  52454. }
  52455. }
  52456. }
  52457. }
  52458. // now convert data from buffer into floats
  52459. for (i = 0; i < scanline_width; i++) {
  52460. a = scanLineArray[i];
  52461. b = scanLineArray[i + scanline_width];
  52462. c = scanLineArray[i + 2 * scanline_width];
  52463. d = scanLineArray[i + 3 * scanline_width];
  52464. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  52465. }
  52466. num_scanlines--;
  52467. }
  52468. return resultArray;
  52469. };
  52470. return HDRTools;
  52471. })();
  52472. Internals.HDRTools = HDRTools;
  52473. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52474. })(BABYLON || (BABYLON = {}));
  52475. //_______________________________________________________________
  52476. // Extracted from CubeMapGen:
  52477. // https://code.google.com/archive/p/cubemapgen/
  52478. //
  52479. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  52480. //_______________________________________________________________
  52481. var BABYLON;
  52482. (function (BABYLON) {
  52483. var Internals;
  52484. (function (Internals) {
  52485. /**
  52486. * The bounding box information used during the conversion process.
  52487. */
  52488. var CMGBoundinBox = (function () {
  52489. function CMGBoundinBox() {
  52490. this.min = new BABYLON.Vector3(0, 0, 0);
  52491. this.max = new BABYLON.Vector3(0, 0, 0);
  52492. this.clear();
  52493. }
  52494. CMGBoundinBox.prototype.clear = function () {
  52495. this.min.x = CMGBoundinBox.MAX;
  52496. this.min.y = CMGBoundinBox.MAX;
  52497. this.min.z = CMGBoundinBox.MAX;
  52498. this.max.x = CMGBoundinBox.MIN;
  52499. this.max.y = CMGBoundinBox.MIN;
  52500. this.max.z = CMGBoundinBox.MIN;
  52501. };
  52502. CMGBoundinBox.prototype.augment = function (x, y, z) {
  52503. this.min.x = Math.min(this.min.x, x);
  52504. this.min.y = Math.min(this.min.y, y);
  52505. this.min.z = Math.min(this.min.z, z);
  52506. this.max.x = Math.max(this.max.x, x);
  52507. this.max.y = Math.max(this.max.y, y);
  52508. this.max.z = Math.max(this.max.z, z);
  52509. };
  52510. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  52511. this.min.x = Math.max(this.min.x, x);
  52512. this.min.y = Math.max(this.min.y, y);
  52513. this.min.z = Math.max(this.min.z, z);
  52514. };
  52515. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  52516. this.max.x = Math.min(this.max.x, x);
  52517. this.max.y = Math.min(this.max.y, y);
  52518. this.max.z = Math.min(this.max.z, z);
  52519. };
  52520. CMGBoundinBox.prototype.empty = function () {
  52521. if ((this.min.x > this.max.y) ||
  52522. (this.min.y > this.max.y) ||
  52523. (this.min.z > this.max.y)) {
  52524. return true;
  52525. }
  52526. else {
  52527. return false;
  52528. }
  52529. };
  52530. CMGBoundinBox.MAX = Number.MAX_VALUE;
  52531. CMGBoundinBox.MIN = Number.MIN_VALUE;
  52532. return CMGBoundinBox;
  52533. })();
  52534. /**
  52535. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  52536. * required by the glossinees of a material.
  52537. *
  52538. * This only supports the cosine drop power as well as Warp fixup generation method.
  52539. *
  52540. * This is using the process from CubeMapGen described here:
  52541. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  52542. */
  52543. var PMREMGenerator = (function () {
  52544. /**
  52545. * Constructor of the generator.
  52546. *
  52547. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  52548. * @param inputSize The size of the cubemap faces
  52549. * @param outputSize The size of the output cubemap faces
  52550. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  52551. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  52552. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  52553. * @param specularPower The max specular level of the desired cubemap
  52554. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  52555. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  52556. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  52557. */
  52558. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  52559. this.input = input;
  52560. this.inputSize = inputSize;
  52561. this.outputSize = outputSize;
  52562. this.maxNumMipLevels = maxNumMipLevels;
  52563. this.numChannels = numChannels;
  52564. this.isFloat = isFloat;
  52565. this.specularPower = specularPower;
  52566. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  52567. this.excludeBase = excludeBase;
  52568. this.fixup = fixup;
  52569. this._outputSurface = [];
  52570. this._numMipLevels = 0;
  52571. }
  52572. /**
  52573. * Launches the filter process and return the result.
  52574. *
  52575. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  52576. */
  52577. PMREMGenerator.prototype.filterCubeMap = function () {
  52578. // Init cubemap processor
  52579. this.init();
  52580. // Filters the cubemap
  52581. this.filterCubeMapMipChain();
  52582. // Returns the filtered mips.
  52583. return this._outputSurface;
  52584. };
  52585. PMREMGenerator.prototype.init = function () {
  52586. var i;
  52587. var j;
  52588. var mipLevelSize;
  52589. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  52590. if (this.maxNumMipLevels == 0) {
  52591. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  52592. }
  52593. //first miplevel size
  52594. mipLevelSize = this.outputSize;
  52595. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  52596. for (j = 0; j < this.maxNumMipLevels; j++) {
  52597. this._outputSurface.length++;
  52598. this._outputSurface[j] = [];
  52599. //Iterate over faces for output images
  52600. for (i = 0; i < 6; i++) {
  52601. this._outputSurface[j].length++;
  52602. // Initializes a new array for the output.
  52603. if (this.isFloat) {
  52604. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  52605. }
  52606. else {
  52607. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  52608. }
  52609. }
  52610. //next mip level is half size
  52611. mipLevelSize >>= 1;
  52612. this._numMipLevels++;
  52613. //terminate if mip chain becomes too small
  52614. if (mipLevelSize == 0) {
  52615. this.maxNumMipLevels = j;
  52616. return;
  52617. }
  52618. }
  52619. };
  52620. //--------------------------------------------------------------------------------------
  52621. //Cube map filtering and mip chain generation.
  52622. // the cube map filtereing is specified using a number of parameters:
  52623. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  52624. // indicates the region of the hemisphere to filter over for each tap.
  52625. //
  52626. // Note that the top mip level is also a filtered version of the original input images
  52627. // as well in order to create mip chains for diffuse environment illumination.
  52628. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  52629. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  52630. //
  52631. // Then the mip angle used to genreate the next level of the mip chain from the first level
  52632. // is a_InitialMipAngle
  52633. //
  52634. // The angle for the subsequent levels of the mip chain are specified by their parents
  52635. // filtering angle and a per-level scale and bias
  52636. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  52637. //
  52638. //--------------------------------------------------------------------------------------
  52639. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  52640. // First, take count of the lighting model to modify SpecularPower
  52641. // 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;
  52642. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  52643. //Cone angle start (for generating subsequent mip levels)
  52644. var currentSpecularPower = this.specularPower;
  52645. //Build filter lookup tables based on the source miplevel size
  52646. this.precomputeFilterLookupTables(this.inputSize);
  52647. // Note that we need to filter the first level before generating mipmap
  52648. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  52649. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  52650. // TODO : Write a function to copy and scale the base mipmap in output
  52651. // I am just lazy here and just put a high specular power value, and do some if.
  52652. if (this.excludeBase && (levelIndex == 0)) {
  52653. // 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).
  52654. currentSpecularPower = 100000.0;
  52655. }
  52656. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  52657. var srcCubeImage = this.input;
  52658. var dstCubeImage = this._outputSurface[levelIndex];
  52659. var dstSize = this.outputSize >> levelIndex;
  52660. // Compute required angle.
  52661. var angle = this.getBaseFilterAngle(currentSpecularPower);
  52662. // filter cube surfaces
  52663. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  52664. // fix seams
  52665. if (this.fixup) {
  52666. this.fixupCubeEdges(dstCubeImage, dstSize);
  52667. }
  52668. // Decrease the specular power to generate the mipmap chain
  52669. // TODO : Use another method for Exclude (see first comment at start of the function
  52670. if (this.excludeBase && (levelIndex == 0)) {
  52671. currentSpecularPower = this.specularPower;
  52672. }
  52673. currentSpecularPower *= this.cosinePowerDropPerMip;
  52674. }
  52675. };
  52676. //--------------------------------------------------------------------------------------
  52677. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  52678. // It allow to optimize the texel to access base on the specular power.
  52679. //--------------------------------------------------------------------------------------
  52680. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  52681. // We want to find the alpha such that:
  52682. // cos(alpha)^cosinePower = epsilon
  52683. // That's: acos(epsilon^(1/cosinePower))
  52684. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  52685. var angle = 180.0;
  52686. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  52687. angle *= 180.0 / Math.PI; // Convert to degree
  52688. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  52689. return angle;
  52690. };
  52691. //--------------------------------------------------------------------------------------
  52692. //Builds the following lookup tables prior to filtering:
  52693. // -normalizer cube map
  52694. // -tap weight lookup table
  52695. //
  52696. //--------------------------------------------------------------------------------------
  52697. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  52698. var srcTexelAngle;
  52699. var iCubeFace;
  52700. //clear pre-existing normalizer cube map
  52701. this._normCubeMap = [];
  52702. //Normalized vectors per cubeface and per-texel solid angle
  52703. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  52704. };
  52705. //--------------------------------------------------------------------------------------
  52706. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  52707. //
  52708. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  52709. //
  52710. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  52711. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  52712. // below
  52713. //--------------------------------------------------------------------------------------
  52714. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  52715. var iCubeFace;
  52716. var u;
  52717. var v;
  52718. //iterate over cube faces
  52719. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  52720. //First three channels for norm cube, and last channel for solid angle
  52721. this._normCubeMap.push(new Float32Array(size * size * 4));
  52722. //fast texture walk, build normalizer cube map
  52723. var facesData = this.input[iCubeFace];
  52724. for (v = 0; v < size; v++) {
  52725. for (u = 0; u < size; u++) {
  52726. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  52727. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  52728. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  52729. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  52730. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  52731. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  52732. }
  52733. }
  52734. }
  52735. };
  52736. //--------------------------------------------------------------------------------------
  52737. // Convert cubemap face texel coordinates and face idx to 3D vector
  52738. // note the U and V coords are integer coords and range from 0 to size-1
  52739. // this routine can be used to generate a normalizer cube map
  52740. //--------------------------------------------------------------------------------------
  52741. // SL BEGIN
  52742. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  52743. var nvcU;
  52744. var nvcV;
  52745. var tempVec;
  52746. // Change from original AMD code
  52747. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  52748. // + 0.5f is for texel center addressing
  52749. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  52750. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  52751. // warp fixup
  52752. if (fixup && size > 1) {
  52753. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  52754. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  52755. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  52756. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  52757. }
  52758. // Get current vector
  52759. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  52760. // U contribution
  52761. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  52762. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  52763. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  52764. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  52765. // V contribution and Sum
  52766. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  52767. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  52768. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  52769. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  52770. //add face axis
  52771. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  52772. PMREMGenerator._vectorTemp.x += faceAxis[0];
  52773. PMREMGenerator._vectorTemp.y += faceAxis[1];
  52774. PMREMGenerator._vectorTemp.z += faceAxis[2];
  52775. //normalize vector
  52776. PMREMGenerator._vectorTemp.normalize();
  52777. return PMREMGenerator._vectorTemp;
  52778. };
  52779. //--------------------------------------------------------------------------------------
  52780. // Convert 3D vector to cubemap face texel coordinates and face idx
  52781. // note the U and V coords are integer coords and range from 0 to size-1
  52782. // this routine can be used to generate a normalizer cube map
  52783. //
  52784. // returns face IDX and texel coords
  52785. //--------------------------------------------------------------------------------------
  52786. // SL BEGIN
  52787. /*
  52788. Mapping Texture Coordinates to Cube Map Faces
  52789. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  52790. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  52791. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  52792. map arrangement in Pixar's RenderMan package.
  52793. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  52794. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  52795. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  52796. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  52797. the major axis direction). The target column in the table below explains how the major axis direction
  52798. maps to the 2D image of a particular cube map target.
  52799. major axis
  52800. direction target sc tc ma
  52801. ---------- --------------------------------- --- --- ---
  52802. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  52803. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  52804. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  52805. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  52806. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  52807. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  52808. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  52809. an updated (s,t) is calculated as follows
  52810. s = ( sc/|ma| + 1 ) / 2
  52811. t = ( tc/|ma| + 1 ) / 2
  52812. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  52813. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  52814. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  52815. */
  52816. // Note this method return U and V in range from 0 to size-1
  52817. // SL END
  52818. // Store the information in vector3 for convenience (faceindex, u, v)
  52819. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  52820. var maxCoord;
  52821. var faceIdx;
  52822. //absolute value 3
  52823. var absX = Math.abs(x);
  52824. var absY = Math.abs(y);
  52825. var absZ = Math.abs(z);
  52826. if (absX >= absY && absX >= absZ) {
  52827. maxCoord = absX;
  52828. if (x >= 0) {
  52829. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  52830. }
  52831. else {
  52832. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  52833. }
  52834. }
  52835. else if (absY >= absX && absY >= absZ) {
  52836. maxCoord = absY;
  52837. if (y >= 0) {
  52838. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  52839. }
  52840. else {
  52841. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  52842. }
  52843. }
  52844. else {
  52845. maxCoord = absZ;
  52846. if (z >= 0) {
  52847. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  52848. }
  52849. else {
  52850. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  52851. }
  52852. }
  52853. //divide through by max coord so face vector lies on cube face
  52854. var scale = 1 / maxCoord;
  52855. x *= scale;
  52856. y *= scale;
  52857. z *= scale;
  52858. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  52859. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  52860. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  52861. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  52862. // Modify original AMD code to return value from 0 to Size - 1
  52863. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  52864. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  52865. PMREMGenerator._vectorTemp.x = faceIdx;
  52866. PMREMGenerator._vectorTemp.y = u;
  52867. PMREMGenerator._vectorTemp.z = v;
  52868. return PMREMGenerator._vectorTemp;
  52869. };
  52870. //--------------------------------------------------------------------------------------
  52871. //Original code from Ignacio CastaÒo
  52872. // This formula is from Manne ÷hrstrˆm's thesis.
  52873. // Take two coordiantes in the range [-1, 1] that define a portion of a
  52874. // cube face and return the area of the projection of that portion on the
  52875. // surface of the sphere.
  52876. //--------------------------------------------------------------------------------------
  52877. PMREMGenerator.prototype.areaElement = function (x, y) {
  52878. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  52879. };
  52880. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  52881. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  52882. // (+ 0.5f is for texel center addressing)
  52883. u = (2.0 * (u + 0.5) / size) - 1.0;
  52884. v = (2.0 * (v + 0.5) / size) - 1.0;
  52885. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  52886. var invResolution = 1.0 / size;
  52887. // U and V are the -1..1 texture coordinate on the current face.
  52888. // Get projected area for this texel
  52889. var x0 = u - invResolution;
  52890. var y0 = v - invResolution;
  52891. var x1 = u + invResolution;
  52892. var y1 = v + invResolution;
  52893. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  52894. return solidAngle;
  52895. };
  52896. //--------------------------------------------------------------------------------------
  52897. //The key to the speed of these filtering routines is to quickly define a per-face
  52898. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  52899. // Later these pixels are selectively processed based on their dot products to see if
  52900. // they reside within the filtering cone.
  52901. //
  52902. //This is done by computing the smallest per-texel angle to get a conservative estimate
  52903. // of the number of texels needed to be covered in width and height order to filter the
  52904. // region. the bounding box for the center taps face is defined first, and if the
  52905. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  52906. // defined next
  52907. //--------------------------------------------------------------------------------------
  52908. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  52909. // note that pixels within these regions may be rejected
  52910. // based on the anlge
  52911. var iCubeFace;
  52912. var u;
  52913. var v;
  52914. // bounding box per face to specify region to process
  52915. var filterExtents = [];
  52916. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  52917. filterExtents.push(new CMGBoundinBox());
  52918. }
  52919. // min angle a src texel can cover (in degrees)
  52920. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  52921. // angle about center tap to define filter cone
  52922. // filter angle is 1/2 the cone angle
  52923. var filterAngle = filterConeAngle / 2.0;
  52924. //ensure filter angle is larger than a texel
  52925. if (filterAngle < srcTexelAngle) {
  52926. filterAngle = srcTexelAngle;
  52927. }
  52928. //ensure filter cone is always smaller than the hemisphere
  52929. if (filterAngle > 90.0) {
  52930. filterAngle = 90.0;
  52931. }
  52932. // the maximum number of texels in 1D the filter cone angle will cover
  52933. // used to determine bounding box size for filter extents
  52934. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  52935. // ensure conservative region always covers at least one texel
  52936. if (filterSize < 1) {
  52937. filterSize = 1;
  52938. }
  52939. // dotProdThresh threshold based on cone angle to determine whether or not taps
  52940. // reside within the cone angle
  52941. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  52942. // process required faces
  52943. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  52944. //iterate over dst cube map face texel
  52945. for (v = 0; v < dstSize; v++) {
  52946. for (u = 0; u < dstSize; u++) {
  52947. //get center tap direction
  52948. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  52949. //clear old per-face filter extents
  52950. this.clearFilterExtents(filterExtents);
  52951. //define per-face filter extents
  52952. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  52953. //perform filtering of src faces using filter extents
  52954. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  52955. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  52956. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  52957. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  52958. }
  52959. }
  52960. }
  52961. };
  52962. //--------------------------------------------------------------------------------------
  52963. //Clear filter extents for the 6 cube map faces
  52964. //--------------------------------------------------------------------------------------
  52965. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  52966. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  52967. filterExtents[iCubeFaces].clear();
  52968. }
  52969. };
  52970. //--------------------------------------------------------------------------------------
  52971. //Define per-face bounding box filter extents
  52972. //
  52973. // These define conservative texel regions in each of the faces the filter can possibly
  52974. // process. When the pixels in the regions are actually processed, the dot product
  52975. // between the tap vector and the center tap vector is used to determine the weight of
  52976. // the tap and whether or not the tap is within the cone.
  52977. //
  52978. //--------------------------------------------------------------------------------------
  52979. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  52980. //neighboring face and bleed over amount, and width of BBOX for
  52981. // left, right, top, and bottom edges of this face
  52982. var bleedOverAmount = [0, 0, 0, 0];
  52983. var bleedOverBBoxMin = [0, 0, 0, 0];
  52984. var bleedOverBBoxMax = [0, 0, 0, 0];
  52985. var neighborFace;
  52986. var neighborEdge;
  52987. var oppositeFaceIdx;
  52988. //get face idx, and u, v info from center tap dir
  52989. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  52990. var faceIdx = result.x;
  52991. var u = result.y;
  52992. var v = result.z;
  52993. //define bbox size within face
  52994. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  52995. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  52996. filterExtents[faceIdx].clampMin(0, 0, 0);
  52997. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  52998. //u and v extent in face corresponding to center tap
  52999. var minU = filterExtents[faceIdx].min.x;
  53000. var minV = filterExtents[faceIdx].min.y;
  53001. var maxU = filterExtents[faceIdx].max.x;
  53002. var maxV = filterExtents[faceIdx].max.y;
  53003. //bleed over amounts for face across u=0 edge (left)
  53004. bleedOverAmount[0] = (bboxSize - u);
  53005. bleedOverBBoxMin[0] = minV;
  53006. bleedOverBBoxMax[0] = maxV;
  53007. //bleed over amounts for face across u=1 edge (right)
  53008. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  53009. bleedOverBBoxMin[1] = minV;
  53010. bleedOverBBoxMax[1] = maxV;
  53011. //bleed over to face across v=0 edge (up)
  53012. bleedOverAmount[2] = (bboxSize - v);
  53013. bleedOverBBoxMin[2] = minU;
  53014. bleedOverBBoxMax[2] = maxU;
  53015. //bleed over to face across v=1 edge (down)
  53016. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  53017. bleedOverBBoxMin[3] = minU;
  53018. bleedOverBBoxMax[3] = maxU;
  53019. //compute bleed over regions in neighboring faces
  53020. for (var i = 0; i < 4; i++) {
  53021. if (bleedOverAmount[i] > 0) {
  53022. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  53023. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  53024. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  53025. // be flipped: the cases are
  53026. // if a left edge mates with a left or bottom edge on the neighbor
  53027. // if a top edge mates with a top or right edge on the neighbor
  53028. // if a right edge mates with a right or top edge on the neighbor
  53029. // if a bottom edge mates with a bottom or left edge on the neighbor
  53030. //Seeing as the edges are enumerated as follows
  53031. // left =0
  53032. // right =1
  53033. // top =2
  53034. // bottom =3
  53035. //
  53036. // so if the edge enums are the same, or the sum of the enums == 3,
  53037. // the bbox needs to be flipped
  53038. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  53039. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  53040. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  53041. }
  53042. //The way the bounding box is extended onto the neighboring face
  53043. // depends on which edge of neighboring face abuts with this one
  53044. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  53045. case PMREMGenerator.CP_EDGE_LEFT:
  53046. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  53047. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  53048. break;
  53049. case PMREMGenerator.CP_EDGE_RIGHT:
  53050. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  53051. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  53052. break;
  53053. case PMREMGenerator.CP_EDGE_TOP:
  53054. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  53055. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  53056. break;
  53057. case PMREMGenerator.CP_EDGE_BOTTOM:
  53058. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  53059. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  53060. break;
  53061. }
  53062. //clamp filter extents in non-center tap faces to remain within surface
  53063. filterExtents[neighborFace].clampMin(0, 0, 0);
  53064. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  53065. }
  53066. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  53067. // from the center tap face, then process the opposite face entirely for now.
  53068. //Note that the cases in which this happens, what usually happens is that
  53069. // more than one edge bleeds onto the opposite face, and the bounding box
  53070. // encompasses the entire cube map face.
  53071. if (bleedOverAmount[i] > srcSize) {
  53072. //determine opposite face
  53073. switch (faceIdx) {
  53074. case PMREMGenerator.CP_FACE_X_POS:
  53075. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  53076. break;
  53077. case PMREMGenerator.CP_FACE_X_NEG:
  53078. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  53079. break;
  53080. case PMREMGenerator.CP_FACE_Y_POS:
  53081. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  53082. break;
  53083. case PMREMGenerator.CP_FACE_Y_NEG:
  53084. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  53085. break;
  53086. case PMREMGenerator.CP_FACE_Z_POS:
  53087. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  53088. break;
  53089. case PMREMGenerator.CP_FACE_Z_NEG:
  53090. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  53091. break;
  53092. default:
  53093. break;
  53094. }
  53095. //just encompass entire face for now
  53096. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  53097. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  53098. }
  53099. }
  53100. };
  53101. //--------------------------------------------------------------------------------------
  53102. //ProcessFilterExtents
  53103. // Process bounding box in each cube face
  53104. //
  53105. //--------------------------------------------------------------------------------------
  53106. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  53107. //accumulators are 64-bit floats in order to have the precision needed
  53108. // over a summation of a large number of pixels
  53109. var dstAccum = [0, 0, 0, 0];
  53110. var weightAccum = 0;
  53111. var k = 0;
  53112. var nSrcChannels = this.numChannels;
  53113. // norm cube map and srcCubeMap have same face width
  53114. var faceWidth = srcSize;
  53115. //amount to add to pointer to move to next scanline in images
  53116. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  53117. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  53118. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  53119. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  53120. // iterate over cubefaces
  53121. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  53122. //if bbox is non empty
  53123. if (!filterExtents[iFaceIdx].empty()) {
  53124. var uStart = filterExtents[iFaceIdx].min.x;
  53125. var vStart = filterExtents[iFaceIdx].min.y;
  53126. var uEnd = filterExtents[iFaceIdx].max.x;
  53127. var vEnd = filterExtents[iFaceIdx].max.y;
  53128. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  53129. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  53130. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  53131. for (var v = vStart; v <= vEnd; v++) {
  53132. var normCubeRowWalk = 0;
  53133. var srcCubeRowWalk = 0;
  53134. for (var u = uStart; u <= uEnd; u++) {
  53135. //pointer to direction in cube map associated with texel
  53136. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  53137. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  53138. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  53139. //check dot product to see if texel is within cone
  53140. var tapDotProd = texelVectX * centerTapDir.x +
  53141. texelVectY * centerTapDir.y +
  53142. texelVectZ * centerTapDir.z;
  53143. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  53144. //solid angle stored in 4th channel of normalizer/solid angle cube map
  53145. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  53146. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  53147. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  53148. // so just adding one to specularpower do the trick.
  53149. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  53150. //iterate over channels
  53151. for (k = 0; k < nSrcChannels; k++) {
  53152. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  53153. srcCubeRowWalk++;
  53154. }
  53155. weightAccum += weight; //accumulate weight
  53156. }
  53157. else {
  53158. //step across source pixel
  53159. srcCubeRowWalk += nSrcChannels;
  53160. }
  53161. normCubeRowWalk += 4; // 4 channels per norm cube map.
  53162. }
  53163. startIndexNormCubeMap += normCubePitch;
  53164. startIndexSrcCubeMap += srcCubePitch;
  53165. }
  53166. }
  53167. }
  53168. //divide through by weights if weight is non zero
  53169. if (weightAccum != 0.0) {
  53170. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  53171. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  53172. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  53173. if (this.numChannels > 3) {
  53174. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  53175. }
  53176. }
  53177. else {
  53178. // otherwise sample nearest
  53179. // get face idx and u, v texel coordinate in face
  53180. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  53181. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  53182. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  53183. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  53184. if (this.numChannels > 3) {
  53185. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  53186. }
  53187. }
  53188. return PMREMGenerator._vectorTemp;
  53189. };
  53190. //--------------------------------------------------------------------------------------
  53191. // Fixup cube edges
  53192. //
  53193. // average texels on cube map faces across the edges
  53194. // WARP/BENT Method Only.
  53195. //--------------------------------------------------------------------------------------
  53196. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  53197. var k;
  53198. var j;
  53199. var i;
  53200. var iFace;
  53201. var iCorner = 0;
  53202. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  53203. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  53204. // note that if functionality to filter across the three texels for each corner, then
  53205. //indexed by corner and face idx. the array contains the face the start points belongs to.
  53206. var cornerPtr = [
  53207. [[], [], []],
  53208. [[], [], []],
  53209. [[], [], []],
  53210. [[], [], []],
  53211. [[], [], []],
  53212. [[], [], []],
  53213. [[], [], []],
  53214. [[], [], []]
  53215. ];
  53216. //if there is no fixup, or fixup width = 0, do nothing
  53217. if (cubeMapSize < 1) {
  53218. return;
  53219. }
  53220. //special case 1x1 cubemap, average face colors
  53221. if (cubeMapSize == 1) {
  53222. //iterate over channels
  53223. for (k = 0; k < this.numChannels; k++) {
  53224. var accum = 0.0;
  53225. //iterate over faces to accumulate face colors
  53226. for (iFace = 0; iFace < 6; iFace++) {
  53227. accum += cubeMap[iFace][k];
  53228. }
  53229. //compute average over 6 face colors
  53230. accum /= 6.0;
  53231. //iterate over faces to distribute face colors
  53232. for (iFace = 0; iFace < 6; iFace++) {
  53233. cubeMap[iFace][k] = accum;
  53234. }
  53235. }
  53236. return;
  53237. }
  53238. //iterate over faces to collect list of corner texel pointers
  53239. for (iFace = 0; iFace < 6; iFace++) {
  53240. //the 4 corner pointers for this face
  53241. faceCornerStartIndicies[0] = [iFace, 0];
  53242. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  53243. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  53244. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  53245. //iterate over face corners to collect cube corner pointers
  53246. for (iCorner = 0; iCorner < 4; iCorner++) {
  53247. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  53248. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  53249. cornerNumPtrs[corner]++;
  53250. }
  53251. }
  53252. //iterate over corners to average across corner tap values
  53253. for (iCorner = 0; iCorner < 8; iCorner++) {
  53254. for (k = 0; k < this.numChannels; k++) {
  53255. var cornerTapAccum = 0.0;
  53256. //iterate over corner texels and average results
  53257. for (i = 0; i < 3; i++) {
  53258. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  53259. }
  53260. //divide by 3 to compute average of corner tap values
  53261. cornerTapAccum *= (1.0 / 3.0);
  53262. //iterate over corner texels and average results
  53263. for (i = 0; i < 3; i++) {
  53264. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  53265. }
  53266. }
  53267. }
  53268. //iterate over the twelve edges of the cube to average across edges
  53269. for (i = 0; i < 12; i++) {
  53270. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  53271. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  53272. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  53273. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  53274. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  53275. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  53276. var edgeWalk = 0;
  53277. var neighborEdgeWalk = 0;
  53278. //Determine walking pointers based on edge type
  53279. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  53280. switch (edge) {
  53281. case PMREMGenerator.CP_EDGE_LEFT:
  53282. // no change to faceEdgeStartPtr
  53283. edgeWalk = this.numChannels * cubeMapSize;
  53284. break;
  53285. case PMREMGenerator.CP_EDGE_RIGHT:
  53286. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  53287. edgeWalk = this.numChannels * cubeMapSize;
  53288. break;
  53289. case PMREMGenerator.CP_EDGE_TOP:
  53290. // no change to faceEdgeStartPtr
  53291. edgeWalk = this.numChannels;
  53292. break;
  53293. case PMREMGenerator.CP_EDGE_BOTTOM:
  53294. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  53295. edgeWalk = this.numChannels;
  53296. break;
  53297. }
  53298. //For certain types of edge abutments, the neighbor edge walk needs to
  53299. // be flipped: the cases are
  53300. // if a left edge mates with a left or bottom edge on the neighbor
  53301. // if a top edge mates with a top or right edge on the neighbor
  53302. // if a right edge mates with a right or top edge on the neighbor
  53303. // if a bottom edge mates with a bottom or left edge on the neighbor
  53304. //Seeing as the edges are enumerated as follows
  53305. // left =0
  53306. // right =1
  53307. // top =2
  53308. // bottom =3
  53309. //
  53310. //If the edge enums are the same, or the sum of the enums == 3,
  53311. // the neighbor edge walk needs to be flipped
  53312. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  53313. switch (neighborEdge) {
  53314. case PMREMGenerator.CP_EDGE_LEFT:
  53315. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  53316. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  53317. break;
  53318. case PMREMGenerator.CP_EDGE_RIGHT:
  53319. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  53320. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  53321. break;
  53322. case PMREMGenerator.CP_EDGE_TOP:
  53323. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  53324. neighborEdgeWalk = -this.numChannels;
  53325. break;
  53326. case PMREMGenerator.CP_EDGE_BOTTOM:
  53327. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  53328. neighborEdgeWalk = -this.numChannels;
  53329. break;
  53330. }
  53331. }
  53332. else {
  53333. //swapped direction neighbor edge walk
  53334. switch (neighborEdge) {
  53335. case PMREMGenerator.CP_EDGE_LEFT:
  53336. //no change to neighborEdgeStartPtr for this case since it points
  53337. // to the upper left corner already
  53338. neighborEdgeWalk = this.numChannels * cubeMapSize;
  53339. break;
  53340. case PMREMGenerator.CP_EDGE_RIGHT:
  53341. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  53342. neighborEdgeWalk = this.numChannels * cubeMapSize;
  53343. break;
  53344. case PMREMGenerator.CP_EDGE_TOP:
  53345. //no change to neighborEdgeStartPtr for this case since it points
  53346. // to the upper left corner already
  53347. neighborEdgeWalk = this.numChannels;
  53348. break;
  53349. case PMREMGenerator.CP_EDGE_BOTTOM:
  53350. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  53351. neighborEdgeWalk = this.numChannels;
  53352. break;
  53353. }
  53354. }
  53355. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  53356. //nearby neighborhood
  53357. //step ahead one texel on edge
  53358. edgeStartIndex += edgeWalk;
  53359. neighborEdgeStartIndex += neighborEdgeWalk;
  53360. // note that this loop does not process the corner texels, since they have already been
  53361. // averaged across faces across earlier
  53362. for (j = 1; j < (cubeMapSize - 1); j++) {
  53363. //for each set of taps along edge, average them
  53364. // and rewrite the results into the edges
  53365. for (k = 0; k < this.numChannels; k++) {
  53366. var edgeTap = cubeMap[face][edgeStartIndex + k];
  53367. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  53368. //compute average of tap intensity values
  53369. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  53370. //propagate average of taps to edge taps
  53371. cubeMap[face][edgeStartIndex + k] = avgTap;
  53372. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  53373. }
  53374. edgeStartIndex += edgeWalk;
  53375. neighborEdgeStartIndex += neighborEdgeWalk;
  53376. }
  53377. }
  53378. };
  53379. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  53380. PMREMGenerator.CP_UDIR = 0;
  53381. PMREMGenerator.CP_VDIR = 1;
  53382. PMREMGenerator.CP_FACEAXIS = 2;
  53383. //used to index cube faces
  53384. PMREMGenerator.CP_FACE_X_POS = 0;
  53385. PMREMGenerator.CP_FACE_X_NEG = 1;
  53386. PMREMGenerator.CP_FACE_Y_POS = 2;
  53387. PMREMGenerator.CP_FACE_Y_NEG = 3;
  53388. PMREMGenerator.CP_FACE_Z_POS = 4;
  53389. PMREMGenerator.CP_FACE_Z_NEG = 5;
  53390. //used to index image edges
  53391. // NOTE.. the actual number corresponding to the edge is important
  53392. // do not change these, or the code will break
  53393. //
  53394. // CP_EDGE_LEFT is u = 0
  53395. // CP_EDGE_RIGHT is u = width-1
  53396. // CP_EDGE_TOP is v = 0
  53397. // CP_EDGE_BOTTOM is v = height-1
  53398. PMREMGenerator.CP_EDGE_LEFT = 0;
  53399. PMREMGenerator.CP_EDGE_RIGHT = 1;
  53400. PMREMGenerator.CP_EDGE_TOP = 2;
  53401. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  53402. //corners of CUBE map (P or N specifys if it corresponds to the
  53403. // positive or negative direction each of X, Y, and Z
  53404. PMREMGenerator.CP_CORNER_NNN = 0;
  53405. PMREMGenerator.CP_CORNER_NNP = 1;
  53406. PMREMGenerator.CP_CORNER_NPN = 2;
  53407. PMREMGenerator.CP_CORNER_NPP = 3;
  53408. PMREMGenerator.CP_CORNER_PNN = 4;
  53409. PMREMGenerator.CP_CORNER_PNP = 5;
  53410. PMREMGenerator.CP_CORNER_PPN = 6;
  53411. PMREMGenerator.CP_CORNER_PPP = 7;
  53412. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  53413. //3x2 matrices that map cube map indexing vectors in 3d
  53414. // (after face selection and divide through by the
  53415. // _ABSOLUTE VALUE_ of the max coord)
  53416. // into NVC space
  53417. //Note this currently assumes the D3D cube face ordering and orientation
  53418. PMREMGenerator._sgFace2DMapping = [
  53419. //XPOS face
  53420. [[0, 0, -1],
  53421. [0, -1, 0],
  53422. [1, 0, 0]],
  53423. //XNEG face
  53424. [[0, 0, 1],
  53425. [0, -1, 0],
  53426. [-1, 0, 0]],
  53427. //YPOS face
  53428. [[1, 0, 0],
  53429. [0, 0, 1],
  53430. [0, 1, 0]],
  53431. //YNEG face
  53432. [[1, 0, 0],
  53433. [0, 0, -1],
  53434. [0, -1, 0]],
  53435. //ZPOS face
  53436. [[1, 0, 0],
  53437. [0, -1, 0],
  53438. [0, 0, 1]],
  53439. //ZNEG face
  53440. [[-1, 0, 0],
  53441. [0, -1, 0],
  53442. [0, 0, -1]],
  53443. ];
  53444. //------------------------------------------------------------------------------
  53445. // D3D cube map face specification
  53446. // mapping from 3D x,y,z cube map lookup coordinates
  53447. // to 2D within face u,v coordinates
  53448. //
  53449. // --------------------> U direction
  53450. // | (within-face texture space)
  53451. // | _____
  53452. // | | |
  53453. // | | +Y |
  53454. // | _____|_____|_____ _____
  53455. // | | | | | |
  53456. // | | -X | +Z | +X | -Z |
  53457. // | |_____|_____|_____|_____|
  53458. // | | |
  53459. // | | -Y |
  53460. // | |_____|
  53461. // |
  53462. // v V direction
  53463. // (within-face texture space)
  53464. //------------------------------------------------------------------------------
  53465. //Information about neighbors and how texture coorrdinates change across faces
  53466. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  53467. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  53468. //Note this currently assumes the D3D cube face ordering and orientation
  53469. PMREMGenerator._sgCubeNgh = [
  53470. //XPOS face
  53471. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  53472. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  53473. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  53474. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  53475. //XNEG face
  53476. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  53477. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  53478. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  53479. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  53480. //YPOS face
  53481. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  53482. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  53483. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  53484. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  53485. //YNEG face
  53486. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  53487. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  53488. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  53489. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  53490. //ZPOS face
  53491. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  53492. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  53493. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  53494. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  53495. //ZNEG face
  53496. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  53497. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  53498. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  53499. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  53500. ];
  53501. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  53502. // this table is used to average over the edges.
  53503. PMREMGenerator._sgCubeEdgeList = [
  53504. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  53505. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  53506. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  53507. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  53508. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  53509. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  53510. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  53511. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  53512. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  53513. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  53514. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  53515. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  53516. ];
  53517. //Information about which of the 8 cube corners are correspond to the
  53518. // the 4 corners in each cube face
  53519. // the order is upper left, upper right, lower left, lower right
  53520. PMREMGenerator._sgCubeCornerList = [
  53521. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  53522. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  53523. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  53524. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  53525. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  53526. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  53527. ];
  53528. return PMREMGenerator;
  53529. })();
  53530. Internals.PMREMGenerator = PMREMGenerator;
  53531. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53532. })(BABYLON || (BABYLON = {}));
  53533. var BABYLON;
  53534. (function (BABYLON) {
  53535. /**
  53536. * This represents a texture coming from an HDR input.
  53537. *
  53538. * The only supported format is currently panorama picture stored in RGBE format.
  53539. * Example of such files can be found on HDRLib: http://hdrlib.com/
  53540. */
  53541. var HDRCubeTexture = (function (_super) {
  53542. __extends(HDRCubeTexture, _super);
  53543. /**
  53544. * Instantiates an HDRTexture from the following parameters.
  53545. *
  53546. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  53547. * @param scene The scene the texture will be used in
  53548. * @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.
  53549. * @param noMipmap Forces to not generate the mipmap if true
  53550. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  53551. * @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)
  53552. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  53553. */
  53554. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  53555. if (noMipmap === void 0) { noMipmap = false; }
  53556. if (generateHarmonics === void 0) { generateHarmonics = true; }
  53557. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  53558. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  53559. _super.call(this, scene);
  53560. this._useInGammaSpace = false;
  53561. this._generateHarmonics = true;
  53562. this._isBABYLONPreprocessed = false;
  53563. /**
  53564. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  53565. */
  53566. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53567. /**
  53568. * The spherical polynomial data extracted from the texture.
  53569. */
  53570. this.sphericalPolynomial = null;
  53571. /**
  53572. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  53573. * This is usefull at run time to apply the good shader.
  53574. */
  53575. this.isPMREM = false;
  53576. if (!url) {
  53577. return;
  53578. }
  53579. this.name = url;
  53580. this.url = url;
  53581. this.hasAlpha = false;
  53582. this.isCube = true;
  53583. this._textureMatrix = BABYLON.Matrix.Identity();
  53584. if (size) {
  53585. this._isBABYLONPreprocessed = false;
  53586. this._noMipmap = noMipmap;
  53587. this._size = size;
  53588. this._useInGammaSpace = useInGammaSpace;
  53589. this._usePMREMGenerator = usePMREMGenerator &&
  53590. scene.getEngine().getCaps().textureLOD &&
  53591. this.getScene().getEngine().getCaps().textureFloat &&
  53592. !this._useInGammaSpace;
  53593. }
  53594. else {
  53595. this._isBABYLONPreprocessed = true;
  53596. this._noMipmap = false;
  53597. this._useInGammaSpace = false;
  53598. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  53599. this.getScene().getEngine().getCaps().textureFloat &&
  53600. !this._useInGammaSpace;
  53601. }
  53602. this.isPMREM = this._usePMREMGenerator;
  53603. this._texture = this._getFromCache(url, this._noMipmap);
  53604. if (!this._texture) {
  53605. if (!scene.useDelayedTextureLoading) {
  53606. this.loadTexture();
  53607. }
  53608. else {
  53609. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53610. }
  53611. }
  53612. }
  53613. /**
  53614. * Occurs when the file is a preprocessed .babylon.hdr file.
  53615. */
  53616. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  53617. var _this = this;
  53618. var mipLevels = 0;
  53619. var floatArrayView = null;
  53620. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  53621. var mips = [];
  53622. var startIndex = 30;
  53623. for (var level = 0; level < mipLevels; level++) {
  53624. mips.push([]);
  53625. // Fill each pixel of the mip level.
  53626. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  53627. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53628. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  53629. mips[level].push(faceData);
  53630. startIndex += faceSize;
  53631. }
  53632. }
  53633. return mips;
  53634. } : null;
  53635. var callback = function (buffer) {
  53636. // Create Native Array Views
  53637. var intArrayView = new Int32Array(buffer);
  53638. floatArrayView = new Float32Array(buffer);
  53639. // Fill header.
  53640. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  53641. _this._size = intArrayView[1]; // CubeMap max mip face size.
  53642. // Update Texture Information.
  53643. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  53644. // Fill polynomial information.
  53645. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  53646. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  53647. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  53648. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  53649. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  53650. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  53651. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  53652. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  53653. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  53654. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  53655. // Fill pixel data.
  53656. mipLevels = intArrayView[29]; // Number of mip levels.
  53657. var startIndex = 30;
  53658. var data = [];
  53659. var faceSize = Math.pow(_this._size, 2) * 3;
  53660. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53661. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  53662. startIndex += faceSize;
  53663. }
  53664. var results = [];
  53665. var byteArray = null;
  53666. // Push each faces.
  53667. for (var k = 0; k < 6; k++) {
  53668. var dataFace = null;
  53669. // If special cases.
  53670. if (!mipmapGenerator) {
  53671. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  53672. dataFace = data[j];
  53673. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  53674. // 3 channels of 1 bytes per pixel in bytes.
  53675. var byteBuffer = new ArrayBuffer(faceSize);
  53676. byteArray = new Uint8Array(byteBuffer);
  53677. }
  53678. for (var i = 0; i < _this._size * _this._size; i++) {
  53679. // Put in gamma space if requested.
  53680. if (_this._useInGammaSpace) {
  53681. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  53682. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  53683. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  53684. }
  53685. // Convert to int texture for fallback.
  53686. if (byteArray) {
  53687. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  53688. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  53689. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  53690. // May use luminance instead if the result is not accurate.
  53691. var max = Math.max(Math.max(r, g), b);
  53692. if (max > 255) {
  53693. var scale = 255 / max;
  53694. r *= scale;
  53695. g *= scale;
  53696. b *= scale;
  53697. }
  53698. byteArray[(i * 3) + 0] = r;
  53699. byteArray[(i * 3) + 1] = g;
  53700. byteArray[(i * 3) + 2] = b;
  53701. }
  53702. }
  53703. }
  53704. else {
  53705. dataFace = data[k];
  53706. }
  53707. // Fill the array accordingly.
  53708. if (byteArray) {
  53709. results.push(byteArray);
  53710. }
  53711. else {
  53712. results.push(dataFace);
  53713. }
  53714. }
  53715. return results;
  53716. };
  53717. 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);
  53718. };
  53719. /**
  53720. * Occurs when the file is raw .hdr file.
  53721. */
  53722. HDRCubeTexture.prototype.loadHDRTexture = function () {
  53723. var _this = this;
  53724. var callback = function (buffer) {
  53725. // Extract the raw linear data.
  53726. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  53727. // Generate harmonics if needed.
  53728. if (_this._generateHarmonics) {
  53729. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  53730. }
  53731. var results = [];
  53732. var byteArray = null;
  53733. // Push each faces.
  53734. for (var j = 0; j < 6; j++) {
  53735. // Create uintarray fallback.
  53736. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  53737. // 3 channels of 1 bytes per pixel in bytes.
  53738. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  53739. byteArray = new Uint8Array(byteBuffer);
  53740. }
  53741. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  53742. // If special cases.
  53743. if (_this._useInGammaSpace || byteArray) {
  53744. for (var i = 0; i < _this._size * _this._size; i++) {
  53745. // Put in gamma space if requested.
  53746. if (_this._useInGammaSpace) {
  53747. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  53748. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  53749. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  53750. }
  53751. // Convert to int texture for fallback.
  53752. if (byteArray) {
  53753. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  53754. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  53755. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  53756. // May use luminance instead if the result is not accurate.
  53757. var max = Math.max(Math.max(r, g), b);
  53758. if (max > 255) {
  53759. var scale = 255 / max;
  53760. r *= scale;
  53761. g *= scale;
  53762. b *= scale;
  53763. }
  53764. byteArray[(i * 3) + 0] = r;
  53765. byteArray[(i * 3) + 1] = g;
  53766. byteArray[(i * 3) + 2] = b;
  53767. }
  53768. }
  53769. }
  53770. if (byteArray) {
  53771. results.push(byteArray);
  53772. }
  53773. else {
  53774. results.push(dataFace);
  53775. }
  53776. }
  53777. return results;
  53778. };
  53779. var mipmapGenerator = null;
  53780. if (!this._noMipmap &&
  53781. this._usePMREMGenerator) {
  53782. mipmapGenerator = function (data) {
  53783. // Custom setup of the generator matching with the PBR shader values.
  53784. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  53785. return generator.filterCubeMap();
  53786. };
  53787. }
  53788. 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);
  53789. };
  53790. /**
  53791. * Starts the loading process of the texture.
  53792. */
  53793. HDRCubeTexture.prototype.loadTexture = function () {
  53794. if (this._isBABYLONPreprocessed) {
  53795. this.loadBabylonTexture();
  53796. }
  53797. else {
  53798. this.loadHDRTexture();
  53799. }
  53800. };
  53801. HDRCubeTexture.prototype.clone = function () {
  53802. var size = this._isBABYLONPreprocessed ? null : this._size;
  53803. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  53804. // Base texture
  53805. newTexture.level = this.level;
  53806. newTexture.wrapU = this.wrapU;
  53807. newTexture.wrapV = this.wrapV;
  53808. newTexture.coordinatesIndex = this.coordinatesIndex;
  53809. newTexture.coordinatesMode = this.coordinatesMode;
  53810. return newTexture;
  53811. };
  53812. // Methods
  53813. HDRCubeTexture.prototype.delayLoad = function () {
  53814. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53815. return;
  53816. }
  53817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53818. this._texture = this._getFromCache(this.url, this._noMipmap);
  53819. if (!this._texture) {
  53820. this.loadTexture();
  53821. }
  53822. };
  53823. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  53824. return this._textureMatrix;
  53825. };
  53826. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53827. var texture = null;
  53828. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  53829. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  53830. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  53831. texture.name = parsedTexture.name;
  53832. texture.hasAlpha = parsedTexture.hasAlpha;
  53833. texture.level = parsedTexture.level;
  53834. texture.coordinatesMode = parsedTexture.coordinatesMode;
  53835. }
  53836. return texture;
  53837. };
  53838. HDRCubeTexture.prototype.serialize = function () {
  53839. if (!this.name) {
  53840. return null;
  53841. }
  53842. var serializationObject = {};
  53843. serializationObject.name = this.name;
  53844. serializationObject.hasAlpha = this.hasAlpha;
  53845. serializationObject.isCube = true;
  53846. serializationObject.level = this.level;
  53847. serializationObject.size = this._size;
  53848. serializationObject.coordinatesMode = this.coordinatesMode;
  53849. serializationObject.useInGammaSpace = this._useInGammaSpace;
  53850. serializationObject.generateHarmonics = this._generateHarmonics;
  53851. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  53852. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  53853. return serializationObject;
  53854. };
  53855. /**
  53856. * Saves as a file the data contained in the texture in a binary format.
  53857. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  53858. * as the spherical used in the lighting.
  53859. * @param url The HDR file url.
  53860. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  53861. * @param onError Method called if any error happens during download.
  53862. * @return The packed binary data.
  53863. */
  53864. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  53865. if (onError === void 0) { onError = null; }
  53866. var callback = function (buffer) {
  53867. var data = new Blob([buffer], { type: 'application/octet-stream' });
  53868. // Returns a URL you can use as a href.
  53869. var objUrl = window.URL.createObjectURL(data);
  53870. // Simulates a link to it and click to dowload.
  53871. var a = document.createElement("a");
  53872. document.body.appendChild(a);
  53873. a.style.display = "none";
  53874. a.href = objUrl;
  53875. a.download = "envmap.babylon.hdr";
  53876. a.click();
  53877. };
  53878. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  53879. };
  53880. /**
  53881. * Serializes the data contained in the texture in a binary format.
  53882. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  53883. * as the spherical used in the lighting.
  53884. * @param url The HDR file url.
  53885. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  53886. * @param onError Method called if any error happens during download.
  53887. * @return The packed binary data.
  53888. */
  53889. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  53890. if (onError === void 0) { onError = null; }
  53891. // Needs the url tho create the texture.
  53892. if (!url) {
  53893. return null;
  53894. }
  53895. // Check Power of two size.
  53896. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  53897. return null;
  53898. }
  53899. var getDataCallback = function (dataBuffer) {
  53900. // Extract the raw linear data.
  53901. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  53902. // Generate harmonics if needed.
  53903. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  53904. // Generate seamless faces
  53905. var mipGeneratorArray = [];
  53906. // Data are known to be in +X +Y +Z -X -Y -Z
  53907. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  53908. mipGeneratorArray.push(cubeData.right); // +X
  53909. mipGeneratorArray.push(cubeData.left); // -X
  53910. mipGeneratorArray.push(cubeData.up); // +Y
  53911. mipGeneratorArray.push(cubeData.down); // -Y
  53912. mipGeneratorArray.push(cubeData.front); // +Z
  53913. mipGeneratorArray.push(cubeData.back); // -Z
  53914. // Custom setup of the generator matching with the PBR shader values.
  53915. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  53916. var mippedData = generator.filterCubeMap();
  53917. // Compute required byte length.
  53918. var byteLength = 1 * 4; // Raw Data Version int32.
  53919. byteLength += 4; // CubeMap max mip face size int32.
  53920. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  53921. // Add data size.
  53922. byteLength += 4; // Number of mip levels int32.
  53923. for (var level = 0; level < mippedData.length; level++) {
  53924. var mipSize = size >> level;
  53925. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  53926. }
  53927. // Prepare binary structure.
  53928. var buffer = new ArrayBuffer(byteLength);
  53929. var intArrayView = new Int32Array(buffer);
  53930. var floatArrayView = new Float32Array(buffer);
  53931. // Fill header.
  53932. intArrayView[0] = 1; // Version 1.
  53933. intArrayView[1] = size; // CubeMap max mip face size.
  53934. // Fill polynomial information.
  53935. sphericalPolynomial.x.toArray(floatArrayView, 2);
  53936. sphericalPolynomial.y.toArray(floatArrayView, 5);
  53937. sphericalPolynomial.z.toArray(floatArrayView, 8);
  53938. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  53939. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  53940. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  53941. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  53942. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  53943. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  53944. // Fill pixel data.
  53945. intArrayView[29] = mippedData.length; // Number of mip levels.
  53946. var startIndex = 30;
  53947. for (var level = 0; level < mippedData.length; level++) {
  53948. // Fill each pixel of the mip level.
  53949. var faceSize = Math.pow(size >> level, 2) * 3;
  53950. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53951. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  53952. startIndex += faceSize;
  53953. }
  53954. }
  53955. // Callback.
  53956. callback(buffer);
  53957. };
  53958. // Download and process.
  53959. BABYLON.Tools.LoadFile(url, function (data) {
  53960. getDataCallback(data);
  53961. }, null, null, true, onError);
  53962. };
  53963. HDRCubeTexture._facesMapping = [
  53964. "right",
  53965. "up",
  53966. "front",
  53967. "left",
  53968. "down",
  53969. "back"
  53970. ];
  53971. return HDRCubeTexture;
  53972. })(BABYLON.BaseTexture);
  53973. BABYLON.HDRCubeTexture = HDRCubeTexture;
  53974. })(BABYLON || (BABYLON = {}));
  53975. var BABYLON;
  53976. (function (BABYLON) {
  53977. var Debug;
  53978. (function (Debug) {
  53979. /**
  53980. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  53981. */
  53982. var SkeletonViewer = (function () {
  53983. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  53984. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  53985. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  53986. this.skeleton = skeleton;
  53987. this.mesh = mesh;
  53988. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  53989. this.renderingGroupId = renderingGroupId;
  53990. this.color = BABYLON.Color3.White();
  53991. this._debugLines = [];
  53992. this._isEnabled = false;
  53993. this._scene = scene;
  53994. this.update();
  53995. this._renderFunction = this.update.bind(this);
  53996. }
  53997. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  53998. get: function () {
  53999. return this._isEnabled;
  54000. },
  54001. set: function (value) {
  54002. if (this._isEnabled === value) {
  54003. return;
  54004. }
  54005. this._isEnabled = value;
  54006. if (value) {
  54007. this._scene.registerBeforeRender(this._renderFunction);
  54008. }
  54009. else {
  54010. this._scene.unregisterBeforeRender(this._renderFunction);
  54011. }
  54012. },
  54013. enumerable: true,
  54014. configurable: true
  54015. });
  54016. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  54017. if (x === void 0) { x = 0; }
  54018. if (y === void 0) { y = 0; }
  54019. if (z === void 0) { z = 0; }
  54020. var tmat = BABYLON.Tmp.Matrix[0];
  54021. var parentBone = bone.getParent();
  54022. tmat.copyFrom(bone.getLocalMatrix());
  54023. if (x !== 0 || y !== 0 || z !== 0) {
  54024. var tmat2 = BABYLON.Tmp.Matrix[1];
  54025. BABYLON.Matrix.IdentityToRef(tmat2);
  54026. tmat2.m[12] = x;
  54027. tmat2.m[13] = y;
  54028. tmat2.m[14] = z;
  54029. tmat2.multiplyToRef(tmat, tmat);
  54030. }
  54031. if (parentBone) {
  54032. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  54033. }
  54034. tmat.multiplyToRef(meshMat, tmat);
  54035. position.x = tmat.m[12];
  54036. position.y = tmat.m[13];
  54037. position.z = tmat.m[14];
  54038. };
  54039. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  54040. var len = bones.length;
  54041. for (var i = 0; i < len; i++) {
  54042. var bone = bones[i];
  54043. var points = this._debugLines[i];
  54044. if (!points) {
  54045. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  54046. this._debugLines[i] = points;
  54047. }
  54048. this._getBonePosition(points[0], bone, meshMat);
  54049. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  54050. }
  54051. };
  54052. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  54053. var len = bones.length;
  54054. var boneNum = 0;
  54055. for (var i = len - 1; i >= 0; i--) {
  54056. var childBone = bones[i];
  54057. var parentBone = childBone.getParent();
  54058. if (!parentBone) {
  54059. continue;
  54060. }
  54061. var points = this._debugLines[boneNum];
  54062. if (!points) {
  54063. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  54064. this._debugLines[boneNum] = points;
  54065. }
  54066. this._getBonePosition(points[0], childBone, meshMat);
  54067. this._getBonePosition(points[1], parentBone, meshMat);
  54068. boneNum++;
  54069. }
  54070. };
  54071. SkeletonViewer.prototype.update = function () {
  54072. if (this.autoUpdateBonesMatrices) {
  54073. this._updateBoneMatrix(this.skeleton.bones[0]);
  54074. }
  54075. if (this.skeleton.bones[0].length === undefined) {
  54076. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  54077. }
  54078. else {
  54079. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  54080. }
  54081. if (!this._debugMesh) {
  54082. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  54083. this._debugMesh.renderingGroupId = this.renderingGroupId;
  54084. }
  54085. else {
  54086. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  54087. }
  54088. this._debugMesh.color = this.color;
  54089. };
  54090. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  54091. if (bone.getParent()) {
  54092. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  54093. }
  54094. var children = bone.children;
  54095. var len = children.length;
  54096. for (var i = 0; i < len; i++) {
  54097. this._updateBoneMatrix(children[i]);
  54098. }
  54099. };
  54100. SkeletonViewer.prototype.dispose = function () {
  54101. if (this._debugMesh) {
  54102. this.isEnabled = false;
  54103. this._debugMesh.dispose();
  54104. this._debugMesh = null;
  54105. }
  54106. };
  54107. return SkeletonViewer;
  54108. })();
  54109. Debug.SkeletonViewer = SkeletonViewer;
  54110. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  54111. })(BABYLON || (BABYLON = {}));
  54112. var BABYLON;
  54113. (function (BABYLON) {
  54114. /**
  54115. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  54116. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  54117. * 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;
  54118. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  54119. */
  54120. var ColorCurves = (function () {
  54121. function ColorCurves() {
  54122. this._dirty = true;
  54123. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  54124. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  54125. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  54126. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  54127. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  54128. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  54129. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  54130. this._globalHue = 30;
  54131. this._globalDensity = 0;
  54132. this._globalSaturation = 0;
  54133. this._globalExposure = 0;
  54134. this._highlightsHue = 30;
  54135. this._highlightsDensity = 0;
  54136. this._highlightsSaturation = 0;
  54137. this._highlightsExposure = 0;
  54138. this._midtonesHue = 30;
  54139. this._midtonesDensity = 0;
  54140. this._midtonesSaturation = 0;
  54141. this._midtonesExposure = 0;
  54142. this._shadowsHue = 30;
  54143. this._shadowsDensity = 0;
  54144. this._shadowsSaturation = 0;
  54145. this._shadowsExposure = 0;
  54146. }
  54147. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  54148. /**
  54149. * Gets the global Hue value.
  54150. * 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).
  54151. */
  54152. get: function () {
  54153. return this._globalHue;
  54154. },
  54155. /**
  54156. * Sets the global Hue value.
  54157. * 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).
  54158. */
  54159. set: function (value) {
  54160. this._globalHue = value;
  54161. this._dirty = true;
  54162. },
  54163. enumerable: true,
  54164. configurable: true
  54165. });
  54166. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  54167. /**
  54168. * Gets the global Density value.
  54169. * 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.
  54170. * Values less than zero provide a filter of opposite hue.
  54171. */
  54172. get: function () {
  54173. return this._globalDensity;
  54174. },
  54175. /**
  54176. * Sets the global Density value.
  54177. * 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.
  54178. * Values less than zero provide a filter of opposite hue.
  54179. */
  54180. set: function (value) {
  54181. this._globalDensity = value;
  54182. this._dirty = true;
  54183. },
  54184. enumerable: true,
  54185. configurable: true
  54186. });
  54187. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  54188. /**
  54189. * Gets the global Saturation value.
  54190. * 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.
  54191. */
  54192. get: function () {
  54193. return this._globalSaturation;
  54194. },
  54195. /**
  54196. * Sets the global Saturation value.
  54197. * 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.
  54198. */
  54199. set: function (value) {
  54200. this._globalSaturation = value;
  54201. this._dirty = true;
  54202. },
  54203. enumerable: true,
  54204. configurable: true
  54205. });
  54206. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  54207. /**
  54208. * Gets the highlights Hue value.
  54209. * 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).
  54210. */
  54211. get: function () {
  54212. return this._highlightsHue;
  54213. },
  54214. /**
  54215. * Sets the highlights Hue value.
  54216. * 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).
  54217. */
  54218. set: function (value) {
  54219. this._highlightsHue = value;
  54220. this._dirty = true;
  54221. },
  54222. enumerable: true,
  54223. configurable: true
  54224. });
  54225. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  54226. /**
  54227. * Gets the highlights Density value.
  54228. * 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.
  54229. * Values less than zero provide a filter of opposite hue.
  54230. */
  54231. get: function () {
  54232. return this._highlightsDensity;
  54233. },
  54234. /**
  54235. * Sets the highlights Density value.
  54236. * 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.
  54237. * Values less than zero provide a filter of opposite hue.
  54238. */
  54239. set: function (value) {
  54240. this._highlightsDensity = value;
  54241. this._dirty = true;
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  54247. /**
  54248. * Gets the highlights Saturation value.
  54249. * 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.
  54250. */
  54251. get: function () {
  54252. return this._highlightsSaturation;
  54253. },
  54254. /**
  54255. * Sets the highlights Saturation value.
  54256. * 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.
  54257. */
  54258. set: function (value) {
  54259. this._highlightsSaturation = value;
  54260. this._dirty = true;
  54261. },
  54262. enumerable: true,
  54263. configurable: true
  54264. });
  54265. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  54266. /**
  54267. * Gets the highlights Exposure value.
  54268. * 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.
  54269. */
  54270. get: function () {
  54271. return this._highlightsExposure;
  54272. },
  54273. /**
  54274. * Sets the highlights Exposure value.
  54275. * 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.
  54276. */
  54277. set: function (value) {
  54278. this._highlightsExposure = value;
  54279. this._dirty = true;
  54280. },
  54281. enumerable: true,
  54282. configurable: true
  54283. });
  54284. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  54285. /**
  54286. * Gets the midtones Hue value.
  54287. * 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).
  54288. */
  54289. get: function () {
  54290. return this._midtonesHue;
  54291. },
  54292. /**
  54293. * Sets the midtones Hue value.
  54294. * 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).
  54295. */
  54296. set: function (value) {
  54297. this._midtonesHue = value;
  54298. this._dirty = true;
  54299. },
  54300. enumerable: true,
  54301. configurable: true
  54302. });
  54303. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  54304. /**
  54305. * Gets the midtones Density value.
  54306. * 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.
  54307. * Values less than zero provide a filter of opposite hue.
  54308. */
  54309. get: function () {
  54310. return this._midtonesDensity;
  54311. },
  54312. /**
  54313. * Sets the midtones Density value.
  54314. * 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.
  54315. * Values less than zero provide a filter of opposite hue.
  54316. */
  54317. set: function (value) {
  54318. this._midtonesDensity = value;
  54319. this._dirty = true;
  54320. },
  54321. enumerable: true,
  54322. configurable: true
  54323. });
  54324. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  54325. /**
  54326. * Gets the midtones Saturation value.
  54327. * 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.
  54328. */
  54329. get: function () {
  54330. return this._midtonesSaturation;
  54331. },
  54332. /**
  54333. * Sets the midtones Saturation value.
  54334. * 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.
  54335. */
  54336. set: function (value) {
  54337. this._midtonesSaturation = value;
  54338. this._dirty = true;
  54339. },
  54340. enumerable: true,
  54341. configurable: true
  54342. });
  54343. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  54344. /**
  54345. * Gets the midtones Exposure value.
  54346. * 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.
  54347. */
  54348. get: function () {
  54349. return this._midtonesExposure;
  54350. },
  54351. /**
  54352. * Sets the midtones Exposure value.
  54353. * 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.
  54354. */
  54355. set: function (value) {
  54356. this._midtonesExposure = value;
  54357. this._dirty = true;
  54358. },
  54359. enumerable: true,
  54360. configurable: true
  54361. });
  54362. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  54363. /**
  54364. * Gets the shadows Hue value.
  54365. * 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).
  54366. */
  54367. get: function () {
  54368. return this._shadowsHue;
  54369. },
  54370. /**
  54371. * Sets the shadows Hue value.
  54372. * 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).
  54373. */
  54374. set: function (value) {
  54375. this._shadowsHue = value;
  54376. this._dirty = true;
  54377. },
  54378. enumerable: true,
  54379. configurable: true
  54380. });
  54381. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  54382. /**
  54383. * Gets the shadows Density value.
  54384. * 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.
  54385. * Values less than zero provide a filter of opposite hue.
  54386. */
  54387. get: function () {
  54388. return this._shadowsDensity;
  54389. },
  54390. /**
  54391. * Sets the shadows Density value.
  54392. * 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.
  54393. * Values less than zero provide a filter of opposite hue.
  54394. */
  54395. set: function (value) {
  54396. this._shadowsDensity = value;
  54397. this._dirty = true;
  54398. },
  54399. enumerable: true,
  54400. configurable: true
  54401. });
  54402. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  54403. /**
  54404. * Gets the shadows Saturation value.
  54405. * 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.
  54406. */
  54407. get: function () {
  54408. return this._shadowsSaturation;
  54409. },
  54410. /**
  54411. * Sets the shadows Saturation value.
  54412. * 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.
  54413. */
  54414. set: function (value) {
  54415. this._shadowsSaturation = value;
  54416. this._dirty = true;
  54417. },
  54418. enumerable: true,
  54419. configurable: true
  54420. });
  54421. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  54422. /**
  54423. * Gets the shadows Exposure value.
  54424. * 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.
  54425. */
  54426. get: function () {
  54427. return this._shadowsExposure;
  54428. },
  54429. /**
  54430. * Sets the shadows Exposure value.
  54431. * 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.
  54432. */
  54433. set: function (value) {
  54434. this._shadowsExposure = value;
  54435. this._dirty = true;
  54436. },
  54437. enumerable: true,
  54438. configurable: true
  54439. });
  54440. /**
  54441. * Binds the color curves to the shader.
  54442. * @param colorCurves The color curve to bind
  54443. * @param effect The effect to bind to
  54444. */
  54445. ColorCurves.Bind = function (colorCurves, effect) {
  54446. if (colorCurves._dirty) {
  54447. colorCurves._dirty = false;
  54448. // Fill in global info.
  54449. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  54450. // Compute highlights info.
  54451. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  54452. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  54453. // Compute midtones info.
  54454. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  54455. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  54456. // Compute shadows info.
  54457. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  54458. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  54459. // Compute deltas (neutral is midtones).
  54460. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  54461. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  54462. }
  54463. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  54464. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  54465. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  54466. };
  54467. /**
  54468. * Prepare the list of uniforms associated with the ColorCurves effects.
  54469. * @param uniformsList The list of uniforms used in the effect
  54470. */
  54471. ColorCurves.PrepareUniforms = function (uniformsList) {
  54472. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  54473. };
  54474. /**
  54475. * Returns color grading data based on a hue, density, saturation and exposure value.
  54476. * @param filterHue The hue of the color filter.
  54477. * @param filterDensity The density of the color filter.
  54478. * @param saturation The saturation.
  54479. * @param exposure The exposure.
  54480. * @param result The result data container.
  54481. */
  54482. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  54483. if (hue == null) {
  54484. return;
  54485. }
  54486. hue = ColorCurves.clamp(hue, 0, 360);
  54487. density = ColorCurves.clamp(density, -100, 100);
  54488. saturation = ColorCurves.clamp(saturation, -100, 100);
  54489. exposure = ColorCurves.clamp(exposure, -100, 100);
  54490. // Remap the slider/config filter density with non-linear mapping and also scale by half
  54491. // so that the maximum filter density is only 50% control. This provides fine control
  54492. // for small values and reasonable range.
  54493. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  54494. density *= 0.5;
  54495. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  54496. if (density < 0) {
  54497. density *= -1;
  54498. hue = (hue + 180) % 360;
  54499. }
  54500. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  54501. result.scaleToRef(2, result);
  54502. result.a = 1 + 0.01 * saturation;
  54503. };
  54504. /**
  54505. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  54506. * @param value The input slider value in range [-100,100].
  54507. * @returns Adjusted value.
  54508. */
  54509. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  54510. value /= 100;
  54511. var x = Math.abs(value);
  54512. x = Math.pow(x, 2);
  54513. if (value < 0) {
  54514. x *= -1;
  54515. }
  54516. x *= 100;
  54517. return x;
  54518. };
  54519. /**
  54520. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  54521. * @param hue The hue (H) input.
  54522. * @param saturation The saturation (S) input.
  54523. * @param brightness The brightness (B) input.
  54524. * @result An RGBA color represented as Vector4.
  54525. */
  54526. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  54527. var h = ColorCurves.clamp(hue, 0, 360);
  54528. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  54529. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  54530. if (s === 0) {
  54531. result.r = v;
  54532. result.g = v;
  54533. result.b = v;
  54534. }
  54535. else {
  54536. // sector 0 to 5
  54537. h /= 60;
  54538. var i = Math.floor(h);
  54539. // fractional part of h
  54540. var f = h - i;
  54541. var p = v * (1 - s);
  54542. var q = v * (1 - s * f);
  54543. var t = v * (1 - s * (1 - f));
  54544. switch (i) {
  54545. case 0:
  54546. result.r = v;
  54547. result.g = t;
  54548. result.b = p;
  54549. break;
  54550. case 1:
  54551. result.r = q;
  54552. result.g = v;
  54553. result.b = p;
  54554. break;
  54555. case 2:
  54556. result.r = p;
  54557. result.g = v;
  54558. result.b = t;
  54559. break;
  54560. case 3:
  54561. result.r = p;
  54562. result.g = q;
  54563. result.b = v;
  54564. break;
  54565. case 4:
  54566. result.r = t;
  54567. result.g = p;
  54568. result.b = v;
  54569. break;
  54570. default:
  54571. result.r = v;
  54572. result.g = p;
  54573. result.b = q;
  54574. break;
  54575. }
  54576. }
  54577. result.a = 1;
  54578. };
  54579. /**
  54580. * Returns a value clamped between min and max
  54581. * @param value The value to clamp
  54582. * @param min The minimum of value
  54583. * @param max The maximum of value
  54584. * @returns The clamped value.
  54585. */
  54586. ColorCurves.clamp = function (value, min, max) {
  54587. return Math.min(Math.max(value, min), max);
  54588. };
  54589. /**
  54590. * Clones the current color curve instance.
  54591. * @return The cloned curves
  54592. */
  54593. ColorCurves.prototype.clone = function () {
  54594. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  54595. };
  54596. /**
  54597. * Serializes the current color curve instance to a json representation.
  54598. * @return a JSON representation
  54599. */
  54600. ColorCurves.prototype.serialize = function () {
  54601. return BABYLON.SerializationHelper.Serialize(this);
  54602. };
  54603. /**
  54604. * Parses the color curve from a json representation.
  54605. * @param source the JSON source to parse
  54606. * @return The parsed curves
  54607. */
  54608. ColorCurves.Parse = function (source) {
  54609. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  54610. };
  54611. __decorate([
  54612. BABYLON.serialize()
  54613. ], ColorCurves.prototype, "_globalHue", void 0);
  54614. __decorate([
  54615. BABYLON.serialize()
  54616. ], ColorCurves.prototype, "_globalDensity", void 0);
  54617. __decorate([
  54618. BABYLON.serialize()
  54619. ], ColorCurves.prototype, "_globalSaturation", void 0);
  54620. __decorate([
  54621. BABYLON.serialize()
  54622. ], ColorCurves.prototype, "_globalExposure", void 0);
  54623. __decorate([
  54624. BABYLON.serialize()
  54625. ], ColorCurves.prototype, "_highlightsHue", void 0);
  54626. __decorate([
  54627. BABYLON.serialize()
  54628. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  54629. __decorate([
  54630. BABYLON.serialize()
  54631. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  54632. __decorate([
  54633. BABYLON.serialize()
  54634. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  54635. __decorate([
  54636. BABYLON.serialize()
  54637. ], ColorCurves.prototype, "_midtonesHue", void 0);
  54638. __decorate([
  54639. BABYLON.serialize()
  54640. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  54641. __decorate([
  54642. BABYLON.serialize()
  54643. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  54644. __decorate([
  54645. BABYLON.serialize()
  54646. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  54647. return ColorCurves;
  54648. })();
  54649. BABYLON.ColorCurves = ColorCurves;
  54650. })(BABYLON || (BABYLON = {}));
  54651. var BABYLON;
  54652. (function (BABYLON) {
  54653. /**
  54654. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  54655. * It can help converting any input color in a desired output one. This can then be used to create effects
  54656. * from sepia, black and white to sixties or futuristic rendering...
  54657. *
  54658. * The only supported format is currently 3dl.
  54659. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  54660. */
  54661. var ColorGradingTexture = (function (_super) {
  54662. __extends(ColorGradingTexture, _super);
  54663. /**
  54664. * Instantiates a ColorGradingTexture from the following parameters.
  54665. *
  54666. * @param url The location of the color gradind data (currently only supporting 3dl)
  54667. * @param scene The scene the texture will be used in
  54668. */
  54669. function ColorGradingTexture(url, scene) {
  54670. _super.call(this, scene);
  54671. if (!url) {
  54672. return;
  54673. }
  54674. this._textureMatrix = BABYLON.Matrix.Identity();
  54675. this.name = url;
  54676. this.url = url;
  54677. this.hasAlpha = false;
  54678. this.isCube = false;
  54679. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54680. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54681. this.anisotropicFilteringLevel = 1;
  54682. this._texture = this._getFromCache(url, true);
  54683. if (!this._texture) {
  54684. if (!scene.useDelayedTextureLoading) {
  54685. this.loadTexture();
  54686. }
  54687. else {
  54688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54689. }
  54690. }
  54691. }
  54692. /**
  54693. * Returns the texture matrix used in most of the material.
  54694. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  54695. */
  54696. ColorGradingTexture.prototype.getTextureMatrix = function () {
  54697. return this._textureMatrix;
  54698. };
  54699. /**
  54700. * Occurs when the file being loaded is a .3dl LUT file.
  54701. */
  54702. ColorGradingTexture.prototype.load3dlTexture = function () {
  54703. var _this = this;
  54704. var mipLevels = 0;
  54705. var floatArrayView = null;
  54706. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54707. this._texture = texture;
  54708. var callback = function (text) {
  54709. var data;
  54710. var tempData;
  54711. var line;
  54712. var lines = text.split('\n');
  54713. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  54714. var maxColor = 0;
  54715. for (var i = 0; i < lines.length; i++) {
  54716. line = lines[i];
  54717. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  54718. continue;
  54719. if (line.indexOf('#') === 0)
  54720. continue;
  54721. var words = line.split(" ");
  54722. if (size === 0) {
  54723. // Number of space + one
  54724. size = words.length;
  54725. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  54726. tempData = new Float32Array(size * size * size * 4);
  54727. continue;
  54728. }
  54729. if (size != 0) {
  54730. var r = Math.max(parseInt(words[0]), 0);
  54731. var g = Math.max(parseInt(words[1]), 0);
  54732. var b = Math.max(parseInt(words[2]), 0);
  54733. maxColor = Math.max(r, maxColor);
  54734. maxColor = Math.max(g, maxColor);
  54735. maxColor = Math.max(b, maxColor);
  54736. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  54737. tempData[pixelStorageIndex + 0] = r;
  54738. tempData[pixelStorageIndex + 1] = g;
  54739. tempData[pixelStorageIndex + 2] = b;
  54740. tempData[pixelStorageIndex + 3] = 0;
  54741. pixelIndexSlice++;
  54742. if (pixelIndexSlice % size == 0) {
  54743. pixelIndexH++;
  54744. pixelIndexSlice = 0;
  54745. if (pixelIndexH % size == 0) {
  54746. pixelIndexW++;
  54747. pixelIndexH = 0;
  54748. }
  54749. }
  54750. }
  54751. }
  54752. for (var i = 0; i < tempData.length; i++) {
  54753. var value = tempData[i];
  54754. data[i] = (value / maxColor * 255);
  54755. }
  54756. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  54757. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  54758. };
  54759. BABYLON.Tools.LoadFile(this.url, callback);
  54760. return this._texture;
  54761. };
  54762. /**
  54763. * Starts the loading process of the texture.
  54764. */
  54765. ColorGradingTexture.prototype.loadTexture = function () {
  54766. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  54767. this.load3dlTexture();
  54768. }
  54769. };
  54770. /**
  54771. * Clones the color gradind texture.
  54772. */
  54773. ColorGradingTexture.prototype.clone = function () {
  54774. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  54775. // Base texture
  54776. newTexture.level = this.level;
  54777. return newTexture;
  54778. };
  54779. /**
  54780. * Called during delayed load for textures.
  54781. */
  54782. ColorGradingTexture.prototype.delayLoad = function () {
  54783. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54784. return;
  54785. }
  54786. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54787. this._texture = this._getFromCache(this.url, true);
  54788. if (!this._texture) {
  54789. this.loadTexture();
  54790. }
  54791. };
  54792. /**
  54793. * Parses a color grading texture serialized by Babylon.
  54794. * @param parsedTexture The texture information being parsedTexture
  54795. * @param scene The scene to load the texture in
  54796. * @param rootUrl The root url of the data assets to load
  54797. * @return A color gradind texture
  54798. */
  54799. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54800. var texture = null;
  54801. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  54802. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  54803. texture.name = parsedTexture.name;
  54804. texture.level = parsedTexture.level;
  54805. }
  54806. return texture;
  54807. };
  54808. /**
  54809. * Serializes the LUT texture to json format.
  54810. */
  54811. ColorGradingTexture.prototype.serialize = function () {
  54812. if (!this.name) {
  54813. return null;
  54814. }
  54815. var serializationObject = {};
  54816. serializationObject.name = this.name;
  54817. serializationObject.level = this.level;
  54818. return serializationObject;
  54819. };
  54820. /**
  54821. * Empty line regex stored for GC.
  54822. */
  54823. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  54824. return ColorGradingTexture;
  54825. })(BABYLON.BaseTexture);
  54826. BABYLON.ColorGradingTexture = ColorGradingTexture;
  54827. })(BABYLON || (BABYLON = {}));
  54828. var BABYLON;
  54829. (function (BABYLON) {
  54830. var PBRMaterialDefines = (function (_super) {
  54831. __extends(PBRMaterialDefines, _super);
  54832. function PBRMaterialDefines() {
  54833. _super.call(this);
  54834. this.ALBEDO = false;
  54835. this.AMBIENT = false;
  54836. this.OPACITY = false;
  54837. this.OPACITYRGB = false;
  54838. this.REFLECTION = false;
  54839. this.EMISSIVE = false;
  54840. this.REFLECTIVITY = false;
  54841. this.BUMP = false;
  54842. this.PARALLAX = false;
  54843. this.PARALLAXOCCLUSION = false;
  54844. this.SPECULAROVERALPHA = false;
  54845. this.CLIPPLANE = false;
  54846. this.ALPHATEST = false;
  54847. this.ALPHAFROMALBEDO = false;
  54848. this.POINTSIZE = false;
  54849. this.FOG = false;
  54850. this.SPECULARTERM = false;
  54851. this.OPACITYFRESNEL = false;
  54852. this.EMISSIVEFRESNEL = false;
  54853. this.FRESNEL = false;
  54854. this.NORMAL = false;
  54855. this.UV1 = false;
  54856. this.UV2 = false;
  54857. this.VERTEXCOLOR = false;
  54858. this.VERTEXALPHA = false;
  54859. this.NUM_BONE_INFLUENCERS = 0;
  54860. this.BonesPerMesh = 0;
  54861. this.INSTANCES = false;
  54862. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  54863. this.MICROSURFACEAUTOMATIC = false;
  54864. this.EMISSIVEASILLUMINATION = false;
  54865. this.LINKEMISSIVEWITHALBEDO = false;
  54866. this.LIGHTMAP = false;
  54867. this.USELIGHTMAPASSHADOWMAP = false;
  54868. this.REFLECTIONMAP_3D = false;
  54869. this.REFLECTIONMAP_SPHERICAL = false;
  54870. this.REFLECTIONMAP_PLANAR = false;
  54871. this.REFLECTIONMAP_CUBIC = false;
  54872. this.REFLECTIONMAP_PROJECTION = false;
  54873. this.REFLECTIONMAP_SKYBOX = false;
  54874. this.REFLECTIONMAP_EXPLICIT = false;
  54875. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  54876. this.INVERTCUBICMAP = false;
  54877. this.LOGARITHMICDEPTH = false;
  54878. this.CAMERATONEMAP = false;
  54879. this.CAMERACONTRAST = false;
  54880. this.CAMERACOLORGRADING = false;
  54881. this.CAMERACOLORCURVES = false;
  54882. this.OVERLOADEDVALUES = false;
  54883. this.OVERLOADEDSHADOWVALUES = false;
  54884. this.USESPHERICALFROMREFLECTIONMAP = false;
  54885. this.REFRACTION = false;
  54886. this.REFRACTIONMAP_3D = false;
  54887. this.LINKREFRACTIONTOTRANSPARENCY = false;
  54888. this.REFRACTIONMAPINLINEARSPACE = false;
  54889. this.LODBASEDMICROSFURACE = false;
  54890. this.USEPHYSICALLIGHTFALLOFF = false;
  54891. this.RADIANCEOVERALPHA = false;
  54892. this.USEPMREMREFLECTION = false;
  54893. this.USEPMREMREFRACTION = false;
  54894. this.OPENGLNORMALMAP = false;
  54895. this.INVERTNORMALMAPX = false;
  54896. this.INVERTNORMALMAPY = false;
  54897. this.rebuild();
  54898. }
  54899. return PBRMaterialDefines;
  54900. })(BABYLON.MaterialDefines);
  54901. /**
  54902. * The Physically based material of BJS.
  54903. *
  54904. * This offers the main features of a standard PBR material.
  54905. * For more information, please refer to the documentation :
  54906. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  54907. */
  54908. var PBRMaterial = (function (_super) {
  54909. __extends(PBRMaterial, _super);
  54910. /**
  54911. * Instantiates a new PBRMaterial instance.
  54912. *
  54913. * @param name The material name
  54914. * @param scene The scene the material will be use in.
  54915. */
  54916. function PBRMaterial(name, scene) {
  54917. var _this = this;
  54918. _super.call(this, name, scene);
  54919. /**
  54920. * Intensity of the direct lights e.g. the four lights available in your scene.
  54921. * This impacts both the direct diffuse and specular highlights.
  54922. */
  54923. this.directIntensity = 1.0;
  54924. /**
  54925. * Intensity of the emissive part of the material.
  54926. * This helps controlling the emissive effect without modifying the emissive color.
  54927. */
  54928. this.emissiveIntensity = 1.0;
  54929. /**
  54930. * Intensity of the environment e.g. how much the environment will light the object
  54931. * either through harmonics for rough material or through the refelction for shiny ones.
  54932. */
  54933. this.environmentIntensity = 1.0;
  54934. /**
  54935. * This is a special control allowing the reduction of the specular highlights coming from the
  54936. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  54937. */
  54938. this.specularIntensity = 1.0;
  54939. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  54940. /**
  54941. * Debug Control allowing disabling the bump map on this material.
  54942. */
  54943. this.disableBumpMap = false;
  54944. /**
  54945. * Debug Control helping enforcing or dropping the darkness of shadows.
  54946. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  54947. */
  54948. this.overloadedShadowIntensity = 1.0;
  54949. /**
  54950. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  54951. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  54952. */
  54953. this.overloadedShadeIntensity = 1.0;
  54954. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  54955. /**
  54956. * The camera exposure used on this material.
  54957. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  54958. * This corresponds to a photographic exposure.
  54959. */
  54960. this.cameraExposure = 1.0;
  54961. /**
  54962. * The camera contrast used on this material.
  54963. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  54964. */
  54965. this.cameraContrast = 1.0;
  54966. /**
  54967. * Color Grading 2D Lookup Texture.
  54968. * This allows special effects like sepia, black and white to sixties rendering style.
  54969. */
  54970. this.cameraColorGradingTexture = null;
  54971. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  54972. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  54973. /**
  54974. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  54975. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  54976. * 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;
  54977. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  54978. */
  54979. this.cameraColorCurves = null;
  54980. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  54981. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  54982. /**
  54983. * Debug Control allowing to overload the ambient color.
  54984. * This as to be use with the overloadedAmbientIntensity parameter.
  54985. */
  54986. this.overloadedAmbient = BABYLON.Color3.White();
  54987. /**
  54988. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  54989. */
  54990. this.overloadedAmbientIntensity = 0.0;
  54991. /**
  54992. * Debug Control allowing to overload the albedo color.
  54993. * This as to be use with the overloadedAlbedoIntensity parameter.
  54994. */
  54995. this.overloadedAlbedo = BABYLON.Color3.White();
  54996. /**
  54997. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  54998. */
  54999. this.overloadedAlbedoIntensity = 0.0;
  55000. /**
  55001. * Debug Control allowing to overload the reflectivity color.
  55002. * This as to be use with the overloadedReflectivityIntensity parameter.
  55003. */
  55004. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  55005. /**
  55006. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  55007. */
  55008. this.overloadedReflectivityIntensity = 0.0;
  55009. /**
  55010. * Debug Control allowing to overload the emissive color.
  55011. * This as to be use with the overloadedEmissiveIntensity parameter.
  55012. */
  55013. this.overloadedEmissive = BABYLON.Color3.White();
  55014. /**
  55015. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  55016. */
  55017. this.overloadedEmissiveIntensity = 0.0;
  55018. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  55019. /**
  55020. * Debug Control allowing to overload the reflection color.
  55021. * This as to be use with the overloadedReflectionIntensity parameter.
  55022. */
  55023. this.overloadedReflection = BABYLON.Color3.White();
  55024. /**
  55025. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  55026. */
  55027. this.overloadedReflectionIntensity = 0.0;
  55028. /**
  55029. * Debug Control allowing to overload the microsurface.
  55030. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  55031. */
  55032. this.overloadedMicroSurface = 0.0;
  55033. /**
  55034. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  55035. */
  55036. this.overloadedMicroSurfaceIntensity = 0.0;
  55037. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  55038. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  55039. /**
  55040. * AKA Diffuse Color in other nomenclature.
  55041. */
  55042. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  55043. /**
  55044. * AKA Specular Color in other nomenclature.
  55045. */
  55046. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  55047. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  55048. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  55049. /**
  55050. * AKA Glossiness in other nomenclature.
  55051. */
  55052. this.microSurface = 0.9;
  55053. /**
  55054. * source material index of refraction (IOR)' / 'destination material IOR.
  55055. */
  55056. this.indexOfRefraction = 0.66;
  55057. /**
  55058. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  55059. */
  55060. this.invertRefractionY = false;
  55061. /**
  55062. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  55063. * Materials half opaque for instance using refraction could benefit from this control.
  55064. */
  55065. this.linkRefractionWithTransparency = false;
  55066. /**
  55067. * The emissive and albedo are linked to never be more than one (Energy conservation).
  55068. */
  55069. this.linkEmissiveWithAlbedo = false;
  55070. this.useLightmapAsShadowmap = false;
  55071. /**
  55072. * In this mode, the emissive informtaion will always be added to the lighting once.
  55073. * A light for instance can be thought as emissive.
  55074. */
  55075. this.useEmissiveAsIllumination = false;
  55076. /**
  55077. * Secifies that the alpha is coming form the albedo channel alpha channel.
  55078. */
  55079. this.useAlphaFromAlbedoTexture = false;
  55080. /**
  55081. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  55082. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  55083. */
  55084. this.useSpecularOverAlpha = true;
  55085. /**
  55086. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  55087. */
  55088. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  55089. /**
  55090. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  55091. * The material will try to infer what glossiness each pixel should be.
  55092. */
  55093. this.useAutoMicroSurfaceFromReflectivityMap = false;
  55094. /**
  55095. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  55096. * the creation of the material.
  55097. */
  55098. this.useScalarInLinearSpace = false;
  55099. /**
  55100. * BJS is using an harcoded light falloff based on a manually sets up range.
  55101. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  55102. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  55103. */
  55104. this.usePhysicalLightFalloff = true;
  55105. /**
  55106. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  55107. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  55108. */
  55109. this.useRadianceOverAlpha = true;
  55110. /**
  55111. * Allows using the bump map in parallax mode.
  55112. */
  55113. this.useParallax = false;
  55114. /**
  55115. * Allows using the bump map in parallax occlusion mode.
  55116. */
  55117. this.useParallaxOcclusion = false;
  55118. /**
  55119. * Controls the scale bias of the parallax mode.
  55120. */
  55121. this.parallaxScaleBias = 0.05;
  55122. /**
  55123. * If sets to true, disables all the lights affecting the material.
  55124. */
  55125. this.disableLighting = false;
  55126. /**
  55127. * Number of Simultaneous lights allowed on the material.
  55128. */
  55129. this.maxSimultaneousLights = 4;
  55130. /**
  55131. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  55132. */
  55133. this.invertNormalMapX = false;
  55134. /**
  55135. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  55136. */
  55137. this.invertNormalMapY = false;
  55138. this._renderTargets = new BABYLON.SmartArray(16);
  55139. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  55140. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  55141. this._tempColor = new BABYLON.Color3();
  55142. this._defines = new PBRMaterialDefines();
  55143. this._cachedDefines = new PBRMaterialDefines();
  55144. this._myScene = null;
  55145. this._myShadowGenerator = null;
  55146. this._cachedDefines.BonesPerMesh = -1;
  55147. this.getRenderTargetTextures = function () {
  55148. _this._renderTargets.reset();
  55149. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  55150. _this._renderTargets.push(_this.reflectionTexture);
  55151. }
  55152. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  55153. _this._renderTargets.push(_this.refractionTexture);
  55154. }
  55155. return _this._renderTargets;
  55156. };
  55157. }
  55158. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  55159. get: function () {
  55160. return this._useLogarithmicDepth;
  55161. },
  55162. set: function (value) {
  55163. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  55164. },
  55165. enumerable: true,
  55166. configurable: true
  55167. });
  55168. PBRMaterial.prototype.needAlphaBlending = function () {
  55169. if (this.linkRefractionWithTransparency) {
  55170. return false;
  55171. }
  55172. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  55173. };
  55174. PBRMaterial.prototype.needAlphaTesting = function () {
  55175. if (this.linkRefractionWithTransparency) {
  55176. return false;
  55177. }
  55178. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  55179. };
  55180. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  55181. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  55182. };
  55183. PBRMaterial.prototype.getAlphaTestTexture = function () {
  55184. return this.albedoTexture;
  55185. };
  55186. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55187. if (!mesh) {
  55188. return true;
  55189. }
  55190. if (this._defines.INSTANCES !== useInstances) {
  55191. return false;
  55192. }
  55193. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  55194. return true;
  55195. }
  55196. return false;
  55197. };
  55198. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  55199. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  55200. };
  55201. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  55202. if (!useScalarInLinear) {
  55203. color.toLinearSpaceToRef(ref);
  55204. }
  55205. else {
  55206. ref.r = color.r;
  55207. ref.g = color.g;
  55208. ref.b = color.b;
  55209. }
  55210. };
  55211. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  55212. var lightIndex = 0;
  55213. var depthValuesAlreadySet = false;
  55214. for (var index = 0; index < scene.lights.length; index++) {
  55215. var light = scene.lights[index];
  55216. if (!light.isEnabled()) {
  55217. continue;
  55218. }
  55219. if (!light.canAffectMesh(mesh)) {
  55220. continue;
  55221. }
  55222. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  55223. // GAMMA CORRECTION.
  55224. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  55225. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  55226. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  55227. if (defines["SPECULARTERM"]) {
  55228. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  55229. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  55230. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  55231. }
  55232. // Shadows
  55233. if (scene.shadowsEnabled) {
  55234. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  55235. }
  55236. lightIndex++;
  55237. if (lightIndex === maxSimultaneousLights)
  55238. break;
  55239. }
  55240. };
  55241. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  55242. if (this.checkReadyOnlyOnce) {
  55243. if (this._wasPreviouslyReady) {
  55244. return true;
  55245. }
  55246. }
  55247. var scene = this.getScene();
  55248. if (!this.checkReadyOnEveryCall) {
  55249. if (this._renderId === scene.getRenderId()) {
  55250. if (this._checkCache(scene, mesh, useInstances)) {
  55251. return true;
  55252. }
  55253. }
  55254. }
  55255. var engine = scene.getEngine();
  55256. var needNormals = false;
  55257. var needUVs = false;
  55258. this._defines.reset();
  55259. if (scene.texturesEnabled) {
  55260. // Textures
  55261. if (scene.texturesEnabled) {
  55262. if (scene.getEngine().getCaps().textureLOD) {
  55263. this._defines.LODBASEDMICROSFURACE = true;
  55264. }
  55265. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  55266. if (!this.albedoTexture.isReady()) {
  55267. return false;
  55268. }
  55269. else {
  55270. needUVs = true;
  55271. this._defines.ALBEDO = true;
  55272. }
  55273. }
  55274. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  55275. if (!this.ambientTexture.isReady()) {
  55276. return false;
  55277. }
  55278. else {
  55279. needUVs = true;
  55280. this._defines.AMBIENT = true;
  55281. }
  55282. }
  55283. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  55284. if (!this.opacityTexture.isReady()) {
  55285. return false;
  55286. }
  55287. else {
  55288. needUVs = true;
  55289. this._defines.OPACITY = true;
  55290. if (this.opacityTexture.getAlphaFromRGB) {
  55291. this._defines.OPACITYRGB = true;
  55292. }
  55293. }
  55294. }
  55295. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  55296. if (!this.reflectionTexture.isReady()) {
  55297. return false;
  55298. }
  55299. else {
  55300. needNormals = true;
  55301. this._defines.REFLECTION = true;
  55302. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  55303. this._defines.INVERTCUBICMAP = true;
  55304. }
  55305. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  55306. switch (this.reflectionTexture.coordinatesMode) {
  55307. case BABYLON.Texture.CUBIC_MODE:
  55308. case BABYLON.Texture.INVCUBIC_MODE:
  55309. this._defines.REFLECTIONMAP_CUBIC = true;
  55310. break;
  55311. case BABYLON.Texture.EXPLICIT_MODE:
  55312. this._defines.REFLECTIONMAP_EXPLICIT = true;
  55313. break;
  55314. case BABYLON.Texture.PLANAR_MODE:
  55315. this._defines.REFLECTIONMAP_PLANAR = true;
  55316. break;
  55317. case BABYLON.Texture.PROJECTION_MODE:
  55318. this._defines.REFLECTIONMAP_PROJECTION = true;
  55319. break;
  55320. case BABYLON.Texture.SKYBOX_MODE:
  55321. this._defines.REFLECTIONMAP_SKYBOX = true;
  55322. break;
  55323. case BABYLON.Texture.SPHERICAL_MODE:
  55324. this._defines.REFLECTIONMAP_SPHERICAL = true;
  55325. break;
  55326. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  55327. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  55328. break;
  55329. }
  55330. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  55331. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  55332. needNormals = true;
  55333. if (this.reflectionTexture.isPMREM) {
  55334. this._defines.USEPMREMREFLECTION = true;
  55335. }
  55336. }
  55337. }
  55338. }
  55339. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  55340. if (!this.lightmapTexture.isReady()) {
  55341. return false;
  55342. }
  55343. else {
  55344. needUVs = true;
  55345. this._defines.LIGHTMAP = true;
  55346. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  55347. }
  55348. }
  55349. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  55350. if (!this.emissiveTexture.isReady()) {
  55351. return false;
  55352. }
  55353. else {
  55354. needUVs = true;
  55355. this._defines.EMISSIVE = true;
  55356. }
  55357. }
  55358. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  55359. if (!this.reflectivityTexture.isReady()) {
  55360. return false;
  55361. }
  55362. else {
  55363. needUVs = true;
  55364. this._defines.REFLECTIVITY = true;
  55365. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  55366. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  55367. }
  55368. }
  55369. }
  55370. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  55371. if (!this.bumpTexture.isReady()) {
  55372. return false;
  55373. }
  55374. else {
  55375. needUVs = true;
  55376. this._defines.BUMP = true;
  55377. if (this.useParallax) {
  55378. this._defines.PARALLAX = true;
  55379. if (this.useParallaxOcclusion) {
  55380. this._defines.PARALLAXOCCLUSION = true;
  55381. }
  55382. }
  55383. if (this.invertNormalMapX) {
  55384. this._defines.INVERTNORMALMAPX = true;
  55385. }
  55386. if (this.invertNormalMapY) {
  55387. this._defines.INVERTNORMALMAPY = true;
  55388. }
  55389. }
  55390. }
  55391. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  55392. if (!this.refractionTexture.isReady()) {
  55393. return false;
  55394. }
  55395. else {
  55396. needUVs = true;
  55397. this._defines.REFRACTION = true;
  55398. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  55399. if (this.linkRefractionWithTransparency) {
  55400. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  55401. }
  55402. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  55403. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  55404. if (this.refractionTexture.isPMREM) {
  55405. this._defines.USEPMREMREFRACTION = true;
  55406. }
  55407. }
  55408. }
  55409. }
  55410. if (this.cameraColorGradingTexture) {
  55411. if (!this.cameraColorGradingTexture.isReady()) {
  55412. return false;
  55413. }
  55414. else {
  55415. this._defines.CAMERACOLORGRADING = true;
  55416. }
  55417. }
  55418. }
  55419. // Effect
  55420. if (scene.clipPlane) {
  55421. this._defines.CLIPPLANE = true;
  55422. }
  55423. if (engine.getAlphaTesting()) {
  55424. this._defines.ALPHATEST = true;
  55425. }
  55426. if (this._shouldUseAlphaFromAlbedoTexture()) {
  55427. this._defines.ALPHAFROMALBEDO = true;
  55428. }
  55429. if (this.useEmissiveAsIllumination) {
  55430. this._defines.EMISSIVEASILLUMINATION = true;
  55431. }
  55432. if (this.linkEmissiveWithAlbedo) {
  55433. this._defines.LINKEMISSIVEWITHALBEDO = true;
  55434. }
  55435. if (this.useLogarithmicDepth) {
  55436. this._defines.LOGARITHMICDEPTH = true;
  55437. }
  55438. if (this.cameraContrast != 1) {
  55439. this._defines.CAMERACONTRAST = true;
  55440. }
  55441. if (this.cameraExposure != 1) {
  55442. this._defines.CAMERATONEMAP = true;
  55443. }
  55444. if (this.cameraColorCurves) {
  55445. this._defines.CAMERACOLORCURVES = true;
  55446. }
  55447. if (this.overloadedShadeIntensity != 1 ||
  55448. this.overloadedShadowIntensity != 1) {
  55449. this._defines.OVERLOADEDSHADOWVALUES = true;
  55450. }
  55451. if (this.overloadedMicroSurfaceIntensity > 0 ||
  55452. this.overloadedEmissiveIntensity > 0 ||
  55453. this.overloadedReflectivityIntensity > 0 ||
  55454. this.overloadedAlbedoIntensity > 0 ||
  55455. this.overloadedAmbientIntensity > 0 ||
  55456. this.overloadedReflectionIntensity > 0) {
  55457. this._defines.OVERLOADEDVALUES = true;
  55458. }
  55459. // Point size
  55460. if (this.pointsCloud || scene.forcePointsCloud) {
  55461. this._defines.POINTSIZE = true;
  55462. }
  55463. // Fog
  55464. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55465. this._defines.FOG = true;
  55466. }
  55467. if (scene.lightsEnabled && !this.disableLighting) {
  55468. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  55469. }
  55470. if (BABYLON.StandardMaterial.FresnelEnabled) {
  55471. // Fresnel
  55472. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  55473. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  55474. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  55475. this._defines.OPACITYFRESNEL = true;
  55476. }
  55477. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  55478. this._defines.EMISSIVEFRESNEL = true;
  55479. }
  55480. needNormals = true;
  55481. this._defines.FRESNEL = true;
  55482. }
  55483. }
  55484. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  55485. this._defines.SPECULAROVERALPHA = true;
  55486. }
  55487. if (this.usePhysicalLightFalloff) {
  55488. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  55489. }
  55490. if (this.useRadianceOverAlpha) {
  55491. this._defines.RADIANCEOVERALPHA = true;
  55492. }
  55493. // Attribs
  55494. if (mesh) {
  55495. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55496. this._defines.NORMAL = true;
  55497. }
  55498. if (needUVs) {
  55499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55500. this._defines.UV1 = true;
  55501. }
  55502. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55503. this._defines.UV2 = true;
  55504. }
  55505. }
  55506. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55507. this._defines.VERTEXCOLOR = true;
  55508. if (mesh.hasVertexAlpha) {
  55509. this._defines.VERTEXALPHA = true;
  55510. }
  55511. }
  55512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55513. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  55514. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  55515. }
  55516. // Instances
  55517. if (useInstances) {
  55518. this._defines.INSTANCES = true;
  55519. }
  55520. }
  55521. // Get correct effect
  55522. if (!this._defines.isEqual(this._cachedDefines)) {
  55523. this._defines.cloneTo(this._cachedDefines);
  55524. scene.resetCachedMaterial();
  55525. // Fallbacks
  55526. var fallbacks = new BABYLON.EffectFallbacks();
  55527. if (this._defines.REFLECTION) {
  55528. fallbacks.addFallback(0, "REFLECTION");
  55529. }
  55530. if (this._defines.REFRACTION) {
  55531. fallbacks.addFallback(0, "REFRACTION");
  55532. }
  55533. if (this._defines.REFLECTIVITY) {
  55534. fallbacks.addFallback(0, "REFLECTIVITY");
  55535. }
  55536. if (this._defines.BUMP) {
  55537. fallbacks.addFallback(0, "BUMP");
  55538. }
  55539. if (this._defines.PARALLAX) {
  55540. fallbacks.addFallback(1, "PARALLAX");
  55541. }
  55542. if (this._defines.PARALLAXOCCLUSION) {
  55543. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  55544. }
  55545. if (this._defines.SPECULAROVERALPHA) {
  55546. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  55547. }
  55548. if (this._defines.FOG) {
  55549. fallbacks.addFallback(1, "FOG");
  55550. }
  55551. if (this._defines.POINTSIZE) {
  55552. fallbacks.addFallback(0, "POINTSIZE");
  55553. }
  55554. if (this._defines.LOGARITHMICDEPTH) {
  55555. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  55556. }
  55557. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  55558. if (this._defines.SPECULARTERM) {
  55559. fallbacks.addFallback(0, "SPECULARTERM");
  55560. }
  55561. if (this._defines.OPACITYFRESNEL) {
  55562. fallbacks.addFallback(1, "OPACITYFRESNEL");
  55563. }
  55564. if (this._defines.EMISSIVEFRESNEL) {
  55565. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  55566. }
  55567. if (this._defines.FRESNEL) {
  55568. fallbacks.addFallback(3, "FRESNEL");
  55569. }
  55570. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  55571. fallbacks.addCPUSkinningFallback(0, mesh);
  55572. }
  55573. //Attributes
  55574. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55575. if (this._defines.NORMAL) {
  55576. attribs.push(BABYLON.VertexBuffer.NormalKind);
  55577. }
  55578. if (this._defines.UV1) {
  55579. attribs.push(BABYLON.VertexBuffer.UVKind);
  55580. }
  55581. if (this._defines.UV2) {
  55582. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55583. }
  55584. if (this._defines.VERTEXCOLOR) {
  55585. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55586. }
  55587. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  55588. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  55589. // Legacy browser patch
  55590. var shaderName = "pbr";
  55591. if (!scene.getEngine().getCaps().standardDerivatives) {
  55592. shaderName = "legacypbr";
  55593. }
  55594. var join = this._defines.toString();
  55595. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  55596. "vFogInfos", "vFogColor", "pointSize",
  55597. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  55598. "mBones",
  55599. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  55600. "depthValues",
  55601. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  55602. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  55603. "logarithmicDepthConstant",
  55604. "vSphericalX", "vSphericalY", "vSphericalZ",
  55605. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  55606. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  55607. "vMicrosurfaceTextureLods",
  55608. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  55609. ];
  55610. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  55611. "cameraColorGrading2DSampler"];
  55612. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  55613. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  55614. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  55615. }
  55616. if (!this._effect.isReady()) {
  55617. return false;
  55618. }
  55619. this._renderId = scene.getRenderId();
  55620. this._wasPreviouslyReady = true;
  55621. if (mesh) {
  55622. if (!mesh._materialDefines) {
  55623. mesh._materialDefines = new PBRMaterialDefines();
  55624. }
  55625. this._defines.cloneTo(mesh._materialDefines);
  55626. }
  55627. return true;
  55628. };
  55629. PBRMaterial.prototype.unbind = function () {
  55630. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  55631. this._effect.setTexture("reflection2DSampler", null);
  55632. }
  55633. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  55634. this._effect.setTexture("refraction2DSampler", null);
  55635. }
  55636. _super.prototype.unbind.call(this);
  55637. };
  55638. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55639. this._effect.setMatrix("world", world);
  55640. };
  55641. PBRMaterial.prototype.bind = function (world, mesh) {
  55642. this._myScene = this.getScene();
  55643. // Matrices
  55644. this.bindOnlyWorldMatrix(world);
  55645. // Bones
  55646. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55647. if (this._myScene.getCachedMaterial() !== this) {
  55648. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  55649. if (BABYLON.StandardMaterial.FresnelEnabled) {
  55650. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  55651. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  55652. }
  55653. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  55654. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  55655. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  55656. }
  55657. }
  55658. // Textures
  55659. if (this._myScene.texturesEnabled) {
  55660. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  55661. this._effect.setTexture("albedoSampler", this.albedoTexture);
  55662. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  55663. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  55664. }
  55665. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  55666. this._effect.setTexture("ambientSampler", this.ambientTexture);
  55667. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  55668. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  55669. }
  55670. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  55671. this._effect.setTexture("opacitySampler", this.opacityTexture);
  55672. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  55673. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  55674. }
  55675. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  55676. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  55677. if (this.reflectionTexture.isCube) {
  55678. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  55679. }
  55680. else {
  55681. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  55682. }
  55683. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  55684. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  55685. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  55686. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  55687. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  55688. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  55689. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  55690. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  55691. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  55692. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  55693. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  55694. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  55695. }
  55696. }
  55697. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  55698. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  55699. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  55700. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  55701. }
  55702. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  55703. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  55704. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  55705. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  55706. }
  55707. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  55708. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  55709. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  55710. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  55711. }
  55712. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  55713. this._effect.setTexture("bumpSampler", this.bumpTexture);
  55714. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  55715. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  55716. }
  55717. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  55718. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  55719. var depth = 1.0;
  55720. if (this.refractionTexture.isCube) {
  55721. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  55722. }
  55723. else {
  55724. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  55725. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  55726. if (this.refractionTexture.depth) {
  55727. depth = this.refractionTexture.depth;
  55728. }
  55729. }
  55730. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  55731. }
  55732. if ((this.reflectionTexture || this.refractionTexture)) {
  55733. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  55734. }
  55735. if (this.cameraColorGradingTexture) {
  55736. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  55737. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  55738. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  55739. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  55740. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  55741. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  55742. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  55743. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  55744. 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
  55745. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  55746. 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
  55747. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  55748. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  55749. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  55750. }
  55751. }
  55752. // Clip plane
  55753. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  55754. // Point size
  55755. if (this.pointsCloud) {
  55756. this._effect.setFloat("pointSize", this.pointSize);
  55757. }
  55758. // Colors
  55759. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  55760. // GAMMA CORRECTION.
  55761. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  55762. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  55763. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  55764. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  55765. // GAMMA CORRECTION.
  55766. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  55767. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  55768. // GAMMA CORRECTION.
  55769. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  55770. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  55771. }
  55772. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  55773. // GAMMA CORRECTION.
  55774. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  55775. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  55776. // Lights
  55777. if (this._myScene.lightsEnabled && !this.disableLighting) {
  55778. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  55779. }
  55780. // View
  55781. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  55782. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  55783. }
  55784. // Fog
  55785. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  55786. this._lightingInfos.x = this.directIntensity;
  55787. this._lightingInfos.y = this.emissiveIntensity;
  55788. this._lightingInfos.z = this.environmentIntensity;
  55789. this._lightingInfos.w = this.specularIntensity;
  55790. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  55791. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  55792. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  55793. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  55794. this._cameraInfos.x = this.cameraExposure;
  55795. this._cameraInfos.y = this.cameraContrast;
  55796. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  55797. if (this.cameraColorCurves) {
  55798. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  55799. }
  55800. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  55801. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  55802. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  55803. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  55804. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  55805. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  55806. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  55807. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  55808. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  55809. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  55810. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  55811. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  55812. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  55813. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  55814. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  55815. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  55816. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  55817. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  55818. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  55819. // Log. depth
  55820. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  55821. }
  55822. _super.prototype.bind.call(this, world, mesh);
  55823. this._myScene = null;
  55824. };
  55825. PBRMaterial.prototype.getAnimatables = function () {
  55826. var results = [];
  55827. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  55828. results.push(this.albedoTexture);
  55829. }
  55830. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  55831. results.push(this.ambientTexture);
  55832. }
  55833. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  55834. results.push(this.opacityTexture);
  55835. }
  55836. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  55837. results.push(this.reflectionTexture);
  55838. }
  55839. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  55840. results.push(this.emissiveTexture);
  55841. }
  55842. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  55843. results.push(this.reflectivityTexture);
  55844. }
  55845. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  55846. results.push(this.bumpTexture);
  55847. }
  55848. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  55849. results.push(this.lightmapTexture);
  55850. }
  55851. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  55852. results.push(this.refractionTexture);
  55853. }
  55854. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  55855. results.push(this.cameraColorGradingTexture);
  55856. }
  55857. return results;
  55858. };
  55859. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55860. if (forceDisposeTextures) {
  55861. if (this.albedoTexture) {
  55862. this.albedoTexture.dispose();
  55863. }
  55864. if (this.ambientTexture) {
  55865. this.ambientTexture.dispose();
  55866. }
  55867. if (this.opacityTexture) {
  55868. this.opacityTexture.dispose();
  55869. }
  55870. if (this.reflectionTexture) {
  55871. this.reflectionTexture.dispose();
  55872. }
  55873. if (this.emissiveTexture) {
  55874. this.emissiveTexture.dispose();
  55875. }
  55876. if (this.reflectivityTexture) {
  55877. this.reflectivityTexture.dispose();
  55878. }
  55879. if (this.bumpTexture) {
  55880. this.bumpTexture.dispose();
  55881. }
  55882. if (this.lightmapTexture) {
  55883. this.lightmapTexture.dispose();
  55884. }
  55885. if (this.refractionTexture) {
  55886. this.refractionTexture.dispose();
  55887. }
  55888. if (this.cameraColorGradingTexture) {
  55889. this.cameraColorGradingTexture.dispose();
  55890. }
  55891. }
  55892. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55893. };
  55894. PBRMaterial.prototype.clone = function (name) {
  55895. var _this = this;
  55896. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  55897. };
  55898. PBRMaterial.prototype.serialize = function () {
  55899. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55900. serializationObject.customType = "BABYLON.PBRMaterial";
  55901. return serializationObject;
  55902. };
  55903. // Statics
  55904. PBRMaterial.Parse = function (source, scene, rootUrl) {
  55905. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  55906. };
  55907. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  55908. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  55909. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  55910. PBRMaterial._scaledReflection = new BABYLON.Color3();
  55911. __decorate([
  55912. BABYLON.serialize()
  55913. ], PBRMaterial.prototype, "directIntensity", void 0);
  55914. __decorate([
  55915. BABYLON.serialize()
  55916. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  55917. __decorate([
  55918. BABYLON.serialize()
  55919. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  55920. __decorate([
  55921. BABYLON.serialize()
  55922. ], PBRMaterial.prototype, "specularIntensity", void 0);
  55923. __decorate([
  55924. BABYLON.serialize()
  55925. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  55926. __decorate([
  55927. BABYLON.serialize()
  55928. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  55929. __decorate([
  55930. BABYLON.serialize()
  55931. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  55932. __decorate([
  55933. BABYLON.serialize()
  55934. ], PBRMaterial.prototype, "cameraExposure", void 0);
  55935. __decorate([
  55936. BABYLON.serialize()
  55937. ], PBRMaterial.prototype, "cameraContrast", void 0);
  55938. __decorate([
  55939. BABYLON.serializeAsTexture()
  55940. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  55941. __decorate([
  55942. BABYLON.serializeAsColorCurves()
  55943. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  55944. __decorate([
  55945. BABYLON.serializeAsColor3()
  55946. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  55947. __decorate([
  55948. BABYLON.serialize()
  55949. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  55950. __decorate([
  55951. BABYLON.serializeAsColor3()
  55952. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  55953. __decorate([
  55954. BABYLON.serialize()
  55955. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  55956. __decorate([
  55957. BABYLON.serializeAsColor3()
  55958. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  55959. __decorate([
  55960. BABYLON.serialize()
  55961. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  55962. __decorate([
  55963. BABYLON.serializeAsColor3()
  55964. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  55965. __decorate([
  55966. BABYLON.serialize()
  55967. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  55968. __decorate([
  55969. BABYLON.serializeAsColor3()
  55970. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  55971. __decorate([
  55972. BABYLON.serialize()
  55973. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  55974. __decorate([
  55975. BABYLON.serialize()
  55976. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  55977. __decorate([
  55978. BABYLON.serialize()
  55979. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  55980. __decorate([
  55981. BABYLON.serializeAsTexture()
  55982. ], PBRMaterial.prototype, "albedoTexture", void 0);
  55983. __decorate([
  55984. BABYLON.serializeAsTexture()
  55985. ], PBRMaterial.prototype, "ambientTexture", void 0);
  55986. __decorate([
  55987. BABYLON.serializeAsTexture()
  55988. ], PBRMaterial.prototype, "opacityTexture", void 0);
  55989. __decorate([
  55990. BABYLON.serializeAsTexture()
  55991. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  55992. __decorate([
  55993. BABYLON.serializeAsTexture()
  55994. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  55995. __decorate([
  55996. BABYLON.serializeAsTexture()
  55997. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  55998. __decorate([
  55999. BABYLON.serializeAsTexture()
  56000. ], PBRMaterial.prototype, "bumpTexture", void 0);
  56001. __decorate([
  56002. BABYLON.serializeAsTexture()
  56003. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  56004. __decorate([
  56005. BABYLON.serializeAsTexture()
  56006. ], PBRMaterial.prototype, "refractionTexture", void 0);
  56007. __decorate([
  56008. BABYLON.serializeAsColor3("ambient")
  56009. ], PBRMaterial.prototype, "ambientColor", void 0);
  56010. __decorate([
  56011. BABYLON.serializeAsColor3("albedo")
  56012. ], PBRMaterial.prototype, "albedoColor", void 0);
  56013. __decorate([
  56014. BABYLON.serializeAsColor3("reflectivity")
  56015. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  56016. __decorate([
  56017. BABYLON.serializeAsColor3("reflection")
  56018. ], PBRMaterial.prototype, "reflectionColor", void 0);
  56019. __decorate([
  56020. BABYLON.serializeAsColor3("emissive")
  56021. ], PBRMaterial.prototype, "emissiveColor", void 0);
  56022. __decorate([
  56023. BABYLON.serialize()
  56024. ], PBRMaterial.prototype, "microSurface", void 0);
  56025. __decorate([
  56026. BABYLON.serialize()
  56027. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  56028. __decorate([
  56029. BABYLON.serialize()
  56030. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  56031. __decorate([
  56032. BABYLON.serializeAsFresnelParameters()
  56033. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  56034. __decorate([
  56035. BABYLON.serializeAsFresnelParameters()
  56036. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  56037. __decorate([
  56038. BABYLON.serialize()
  56039. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  56040. __decorate([
  56041. BABYLON.serialize()
  56042. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  56043. __decorate([
  56044. BABYLON.serialize()
  56045. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  56046. __decorate([
  56047. BABYLON.serialize()
  56048. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  56049. __decorate([
  56050. BABYLON.serialize()
  56051. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  56052. __decorate([
  56053. BABYLON.serialize()
  56054. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  56055. __decorate([
  56056. BABYLON.serialize()
  56057. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  56058. __decorate([
  56059. BABYLON.serialize()
  56060. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  56061. __decorate([
  56062. BABYLON.serialize()
  56063. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  56064. __decorate([
  56065. BABYLON.serialize()
  56066. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  56067. __decorate([
  56068. BABYLON.serialize()
  56069. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  56070. __decorate([
  56071. BABYLON.serialize()
  56072. ], PBRMaterial.prototype, "useParallax", void 0);
  56073. __decorate([
  56074. BABYLON.serialize()
  56075. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  56076. __decorate([
  56077. BABYLON.serialize()
  56078. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  56079. __decorate([
  56080. BABYLON.serialize()
  56081. ], PBRMaterial.prototype, "disableLighting", void 0);
  56082. __decorate([
  56083. BABYLON.serialize()
  56084. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  56085. __decorate([
  56086. BABYLON.serialize()
  56087. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  56088. __decorate([
  56089. BABYLON.serialize()
  56090. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  56091. __decorate([
  56092. BABYLON.serialize()
  56093. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  56094. return PBRMaterial;
  56095. })(BABYLON.Material);
  56096. BABYLON.PBRMaterial = PBRMaterial;
  56097. })(BABYLON || (BABYLON = {}));
  56098. var BABYLON;
  56099. (function (BABYLON) {
  56100. var DebugLayer = (function () {
  56101. function DebugLayer(scene) {
  56102. var _this = this;
  56103. this._transformationMatrix = BABYLON.Matrix.Identity();
  56104. this._enabled = false;
  56105. this._labelsEnabled = false;
  56106. this._displayStatistics = true;
  56107. this._displayTree = false;
  56108. this._displayLogs = false;
  56109. this._skeletonViewers = new Array();
  56110. this._identityMatrix = BABYLON.Matrix.Identity();
  56111. this.axisRatio = 0.02;
  56112. this.accentColor = "orange";
  56113. this._scene = scene;
  56114. this._syncPositions = function () {
  56115. var engine = _this._scene.getEngine();
  56116. var canvasRect = engine.getRenderingCanvasClientRect();
  56117. if (_this._showUI) {
  56118. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  56119. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  56120. _this._statsDiv.style.width = "400px";
  56121. _this._statsDiv.style.height = "auto";
  56122. _this._statsSubsetDiv.style.maxHeight = "240px";
  56123. _this._optionsDiv.style.left = "0px";
  56124. _this._optionsDiv.style.top = "10px";
  56125. _this._optionsDiv.style.width = "200px";
  56126. _this._optionsDiv.style.height = "auto";
  56127. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  56128. _this._logDiv.style.left = "0px";
  56129. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  56130. _this._logDiv.style.width = "600px";
  56131. _this._logDiv.style.height = "160px";
  56132. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  56133. _this._treeDiv.style.top = "10px";
  56134. _this._treeDiv.style.width = "300px";
  56135. _this._treeDiv.style.height = "auto";
  56136. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  56137. }
  56138. _this._globalDiv.style.left = canvasRect.left + "px";
  56139. _this._globalDiv.style.top = canvasRect.top + "px";
  56140. _this._drawingCanvas.style.left = "0px";
  56141. _this._drawingCanvas.style.top = "0px";
  56142. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  56143. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  56144. var devicePixelRatio = window.devicePixelRatio || 1;
  56145. var context = _this._drawingContext;
  56146. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  56147. context.mozBackingStorePixelRatio ||
  56148. context.msBackingStorePixelRatio ||
  56149. context.oBackingStorePixelRatio ||
  56150. context.backingStorePixelRatio || 1;
  56151. _this._ratio = devicePixelRatio / backingStoreRatio;
  56152. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  56153. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  56154. };
  56155. this._onCanvasClick = function (evt) {
  56156. _this._clickPosition = {
  56157. x: evt.clientX * _this._ratio,
  56158. y: evt.clientY * _this._ratio
  56159. };
  56160. };
  56161. this._syncUI = function () {
  56162. if (_this._showUI) {
  56163. if (_this._displayStatistics) {
  56164. _this._displayStats();
  56165. _this._statsDiv.style.display = "";
  56166. }
  56167. else {
  56168. _this._statsDiv.style.display = "none";
  56169. }
  56170. if (_this._displayLogs) {
  56171. _this._logDiv.style.display = "";
  56172. }
  56173. else {
  56174. _this._logDiv.style.display = "none";
  56175. }
  56176. if (_this._displayTree) {
  56177. _this._treeDiv.style.display = "";
  56178. if (_this._needToRefreshMeshesTree) {
  56179. _this._needToRefreshMeshesTree = false;
  56180. _this._refreshMeshesTreeContent();
  56181. }
  56182. }
  56183. else {
  56184. _this._treeDiv.style.display = "none";
  56185. }
  56186. }
  56187. };
  56188. this._syncData = function () {
  56189. if (_this._labelsEnabled || !_this._showUI) {
  56190. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  56191. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  56192. var engine = _this._scene.getEngine();
  56193. var viewport = _this._camera.viewport;
  56194. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  56195. // Meshes
  56196. var meshes = _this._camera.getActiveMeshes();
  56197. var index;
  56198. var projectedPosition;
  56199. for (index = 0; index < meshes.length; index++) {
  56200. var mesh = meshes.data[index];
  56201. var position = mesh.getBoundingInfo().boundingSphere.center;
  56202. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  56203. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  56204. _this._renderAxis(projectedPosition, mesh, globalViewport);
  56205. }
  56206. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  56207. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  56208. }
  56209. }
  56210. // Cameras
  56211. var cameras = _this._scene.cameras;
  56212. for (index = 0; index < cameras.length; index++) {
  56213. var camera = cameras[index];
  56214. if (camera === _this._camera) {
  56215. continue;
  56216. }
  56217. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  56218. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  56219. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  56220. _this._camera.detachControl(engine.getRenderingCanvas());
  56221. _this._camera = camera;
  56222. _this._camera.attachControl(engine.getRenderingCanvas());
  56223. }, function () { return "purple"; });
  56224. }
  56225. }
  56226. // Lights
  56227. var lights = _this._scene.lights;
  56228. for (index = 0; index < lights.length; index++) {
  56229. var light = lights[index];
  56230. if (light.position) {
  56231. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  56232. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  56233. _this._renderLabel(light.name, projectedPosition, -20, function () {
  56234. light.setEnabled(!light.isEnabled());
  56235. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  56236. }
  56237. }
  56238. }
  56239. }
  56240. _this._clickPosition = undefined;
  56241. };
  56242. }
  56243. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  56244. while (this._treeSubsetDiv.hasChildNodes()) {
  56245. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  56246. }
  56247. // Add meshes
  56248. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  56249. sortedArray.sort(function (a, b) {
  56250. if (a.name === b.name) {
  56251. return 0;
  56252. }
  56253. return (a.name > b.name) ? 1 : -1;
  56254. });
  56255. for (var index = 0; index < sortedArray.length; index++) {
  56256. var mesh = sortedArray[index];
  56257. if (!mesh.isEnabled()) {
  56258. continue;
  56259. }
  56260. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  56261. m.isVisible = element.checked;
  56262. }, mesh);
  56263. }
  56264. };
  56265. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  56266. this._drawingContext.beginPath();
  56267. this._drawingContext.moveTo(zero.x, zero.y);
  56268. this._drawingContext.lineTo(unit.x, unit.y);
  56269. this._drawingContext.strokeStyle = color;
  56270. this._drawingContext.lineWidth = 4;
  56271. this._drawingContext.stroke();
  56272. this._drawingContext.font = "normal 14px Segoe UI";
  56273. this._drawingContext.fillStyle = color;
  56274. this._drawingContext.fillText(label, unitText.x, unitText.y);
  56275. };
  56276. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  56277. var position = mesh.getBoundingInfo().boundingSphere.center;
  56278. var worldMatrix = mesh.getWorldMatrix();
  56279. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  56280. var unit = (unprojectedVector.subtract(position)).length();
  56281. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  56282. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  56283. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  56284. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  56285. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  56286. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  56287. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  56288. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  56289. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  56290. };
  56291. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  56292. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  56293. this._drawingContext.font = "normal 12px Segoe UI";
  56294. var textMetrics = this._drawingContext.measureText(text);
  56295. var centerX = projectedPosition.x - textMetrics.width / 2;
  56296. var centerY = projectedPosition.y;
  56297. var clientRect = this._drawingCanvas.getBoundingClientRect();
  56298. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  56299. onClick();
  56300. }
  56301. this._drawingContext.beginPath();
  56302. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  56303. this._drawingContext.fillStyle = getFillStyle();
  56304. this._drawingContext.globalAlpha = 0.5;
  56305. this._drawingContext.fill();
  56306. this._drawingContext.globalAlpha = 1.0;
  56307. this._drawingContext.strokeStyle = '#FFFFFF';
  56308. this._drawingContext.lineWidth = 1;
  56309. this._drawingContext.stroke();
  56310. this._drawingContext.fillStyle = "#FFFFFF";
  56311. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  56312. this._drawingContext.beginPath();
  56313. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  56314. this._drawingContext.fill();
  56315. }
  56316. };
  56317. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  56318. if (!this._clickPosition) {
  56319. return false;
  56320. }
  56321. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  56322. return false;
  56323. }
  56324. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  56325. return false;
  56326. }
  56327. return true;
  56328. };
  56329. DebugLayer.prototype.isVisible = function () {
  56330. return this._enabled;
  56331. };
  56332. DebugLayer.prototype.hide = function () {
  56333. if (!this._enabled) {
  56334. return;
  56335. }
  56336. this._enabled = false;
  56337. var engine = this._scene.getEngine();
  56338. this._scene.unregisterBeforeRender(this._syncData);
  56339. this._scene.unregisterAfterRender(this._syncUI);
  56340. this._rootElement.removeChild(this._globalDiv);
  56341. this._scene.forceShowBoundingBoxes = false;
  56342. this._scene.forceWireframe = false;
  56343. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  56344. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  56345. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  56346. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  56347. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  56348. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  56349. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  56350. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  56351. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  56352. this._scene.shadowsEnabled = true;
  56353. this._scene.particlesEnabled = true;
  56354. this._scene.postProcessesEnabled = true;
  56355. this._scene.collisionsEnabled = true;
  56356. this._scene.lightsEnabled = true;
  56357. this._scene.texturesEnabled = true;
  56358. this._scene.lensFlaresEnabled = true;
  56359. this._scene.proceduralTexturesEnabled = true;
  56360. this._scene.renderTargetsEnabled = true;
  56361. this._scene.probesEnabled = true;
  56362. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  56363. this._clearSkeletonViewers();
  56364. };
  56365. DebugLayer.prototype._clearSkeletonViewers = function () {
  56366. for (var index = 0; index < this._skeletonViewers.length; index++) {
  56367. this._skeletonViewers[index].dispose();
  56368. }
  56369. this._skeletonViewers = [];
  56370. };
  56371. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  56372. if (showUI === void 0) { showUI = true; }
  56373. if (camera === void 0) { camera = null; }
  56374. if (rootElement === void 0) { rootElement = null; }
  56375. if (this._enabled) {
  56376. return;
  56377. }
  56378. this._enabled = true;
  56379. if (camera) {
  56380. this._camera = camera;
  56381. }
  56382. else {
  56383. this._camera = this._scene.activeCamera;
  56384. }
  56385. this._showUI = showUI;
  56386. var engine = this._scene.getEngine();
  56387. this._globalDiv = document.createElement("div");
  56388. this._rootElement = rootElement || document.body;
  56389. this._rootElement.appendChild(this._globalDiv);
  56390. this._generateDOMelements();
  56391. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  56392. this._syncPositions();
  56393. this._scene.registerBeforeRender(this._syncData);
  56394. this._scene.registerAfterRender(this._syncUI);
  56395. };
  56396. DebugLayer.prototype._clearLabels = function () {
  56397. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  56398. for (var index = 0; index < this._scene.meshes.length; index++) {
  56399. var mesh = this._scene.meshes[index];
  56400. mesh.renderOverlay = false;
  56401. }
  56402. };
  56403. DebugLayer.prototype._generateheader = function (root, text) {
  56404. var header = document.createElement("div");
  56405. header.innerHTML = text + "&nbsp;";
  56406. header.style.textAlign = "right";
  56407. header.style.width = "100%";
  56408. header.style.color = "white";
  56409. header.style.backgroundColor = "Black";
  56410. header.style.padding = "5px 5px 4px 0px";
  56411. header.style.marginLeft = "-5px";
  56412. header.style.fontWeight = "bold";
  56413. root.appendChild(header);
  56414. };
  56415. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  56416. var label = document.createElement("label");
  56417. label.style.display = "inline";
  56418. label.innerHTML = title;
  56419. label.style.color = color;
  56420. root.appendChild(label);
  56421. root.appendChild(document.createElement("br"));
  56422. };
  56423. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  56424. if (tag === void 0) { tag = null; }
  56425. var label = document.createElement("label");
  56426. label.style.display = "inline";
  56427. var boundingBoxesCheckbox = document.createElement("input");
  56428. boundingBoxesCheckbox.type = "checkbox";
  56429. boundingBoxesCheckbox.checked = initialState;
  56430. boundingBoxesCheckbox.style.display = "inline";
  56431. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  56432. boundingBoxesCheckbox.style.verticalAlign = "sub";
  56433. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  56434. task(evt.target, tag);
  56435. });
  56436. label.appendChild(boundingBoxesCheckbox);
  56437. var container = document.createElement("span");
  56438. var leftPart = document.createElement("span");
  56439. var rightPart = document.createElement("span");
  56440. rightPart.style.cssFloat = "right";
  56441. leftPart.innerHTML = leftTitle;
  56442. rightPart.innerHTML = rightTitle;
  56443. rightPart.style.fontSize = "12px";
  56444. rightPart.style.maxWidth = "200px";
  56445. container.appendChild(leftPart);
  56446. container.appendChild(rightPart);
  56447. label.appendChild(container);
  56448. root.appendChild(label);
  56449. root.appendChild(document.createElement("br"));
  56450. };
  56451. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  56452. if (tag === void 0) { tag = null; }
  56453. var label = document.createElement("label");
  56454. label.style.display = "inline";
  56455. var checkBox = document.createElement("input");
  56456. checkBox.type = "checkbox";
  56457. checkBox.checked = initialState;
  56458. checkBox.style.display = "inline";
  56459. checkBox.style.margin = "0px 5px 0px 0px";
  56460. checkBox.style.verticalAlign = "sub";
  56461. checkBox.addEventListener("change", function (evt) {
  56462. task(evt.target, tag);
  56463. });
  56464. label.appendChild(checkBox);
  56465. label.appendChild(document.createTextNode(title));
  56466. root.appendChild(label);
  56467. root.appendChild(document.createElement("br"));
  56468. };
  56469. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  56470. if (tag === void 0) { tag = null; }
  56471. var button = document.createElement("button");
  56472. button.innerHTML = title;
  56473. button.style.height = "24px";
  56474. button.style.width = "150px";
  56475. button.style.marginBottom = "5px";
  56476. button.style.color = "#444444";
  56477. button.style.border = "1px solid white";
  56478. button.className = "debugLayerButton";
  56479. button.addEventListener("click", function (evt) {
  56480. task(evt.target, tag);
  56481. });
  56482. root.appendChild(button);
  56483. root.appendChild(document.createElement("br"));
  56484. };
  56485. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  56486. if (tag === void 0) { tag = null; }
  56487. var label = document.createElement("label");
  56488. label.style.display = "inline";
  56489. var boundingBoxesRadio = document.createElement("input");
  56490. boundingBoxesRadio.type = "radio";
  56491. boundingBoxesRadio.name = name;
  56492. boundingBoxesRadio.checked = initialState;
  56493. boundingBoxesRadio.style.display = "inline";
  56494. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  56495. boundingBoxesRadio.style.verticalAlign = "sub";
  56496. boundingBoxesRadio.addEventListener("change", function (evt) {
  56497. task(evt.target, tag);
  56498. });
  56499. label.appendChild(boundingBoxesRadio);
  56500. label.appendChild(document.createTextNode(title));
  56501. root.appendChild(label);
  56502. root.appendChild(document.createElement("br"));
  56503. };
  56504. DebugLayer.prototype._generateDOMelements = function () {
  56505. var _this = this;
  56506. this._globalDiv.id = "DebugLayer";
  56507. this._globalDiv.style.position = "absolute";
  56508. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  56509. this._globalDiv.style.fontSize = "14px";
  56510. this._globalDiv.style.color = "white";
  56511. // Drawing canvas
  56512. this._drawingCanvas = document.createElement("canvas");
  56513. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  56514. this._drawingCanvas.style.position = "absolute";
  56515. this._drawingCanvas.style.pointerEvents = "none";
  56516. this._drawingCanvas.style.backgroundColor = "transparent";
  56517. this._drawingContext = this._drawingCanvas.getContext("2d");
  56518. this._globalDiv.appendChild(this._drawingCanvas);
  56519. if (this._showUI) {
  56520. var background = "rgba(128, 128, 128, 0.4)";
  56521. var border = "rgb(180, 180, 180) solid 1px";
  56522. // Stats
  56523. this._statsDiv = document.createElement("div");
  56524. this._statsDiv.id = "DebugLayerStats";
  56525. this._statsDiv.style.border = border;
  56526. this._statsDiv.style.position = "absolute";
  56527. this._statsDiv.style.background = background;
  56528. this._statsDiv.style.padding = "0px 0px 0px 5px";
  56529. this._generateheader(this._statsDiv, "STATISTICS");
  56530. this._statsSubsetDiv = document.createElement("div");
  56531. this._statsSubsetDiv.style.paddingTop = "5px";
  56532. this._statsSubsetDiv.style.paddingBottom = "5px";
  56533. this._statsSubsetDiv.style.overflowY = "auto";
  56534. this._statsDiv.appendChild(this._statsSubsetDiv);
  56535. // Tree
  56536. this._treeDiv = document.createElement("div");
  56537. this._treeDiv.id = "DebugLayerTree";
  56538. this._treeDiv.style.border = border;
  56539. this._treeDiv.style.position = "absolute";
  56540. this._treeDiv.style.background = background;
  56541. this._treeDiv.style.padding = "0px 0px 0px 5px";
  56542. this._treeDiv.style.display = "none";
  56543. this._generateheader(this._treeDiv, "MESHES TREE");
  56544. this._treeSubsetDiv = document.createElement("div");
  56545. this._treeSubsetDiv.style.paddingTop = "5px";
  56546. this._treeSubsetDiv.style.paddingRight = "5px";
  56547. this._treeSubsetDiv.style.overflowY = "auto";
  56548. this._treeSubsetDiv.style.maxHeight = "300px";
  56549. this._treeDiv.appendChild(this._treeSubsetDiv);
  56550. this._needToRefreshMeshesTree = true;
  56551. // Logs
  56552. this._logDiv = document.createElement("div");
  56553. this._logDiv.style.border = border;
  56554. this._logDiv.id = "DebugLayerLogs";
  56555. this._logDiv.style.position = "absolute";
  56556. this._logDiv.style.background = background;
  56557. this._logDiv.style.padding = "0px 0px 0px 5px";
  56558. this._logDiv.style.display = "none";
  56559. this._generateheader(this._logDiv, "LOGS");
  56560. this._logSubsetDiv = document.createElement("div");
  56561. this._logSubsetDiv.style.height = "127px";
  56562. this._logSubsetDiv.style.paddingTop = "5px";
  56563. this._logSubsetDiv.style.overflowY = "auto";
  56564. this._logSubsetDiv.style.fontSize = "12px";
  56565. this._logSubsetDiv.style.fontFamily = "consolas";
  56566. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  56567. this._logDiv.appendChild(this._logSubsetDiv);
  56568. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  56569. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  56570. };
  56571. // Options
  56572. this._optionsDiv = document.createElement("div");
  56573. this._optionsDiv.id = "DebugLayerOptions";
  56574. this._optionsDiv.style.border = border;
  56575. this._optionsDiv.style.position = "absolute";
  56576. this._optionsDiv.style.background = background;
  56577. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  56578. this._optionsDiv.style.overflowY = "auto";
  56579. this._generateheader(this._optionsDiv, "OPTIONS");
  56580. this._optionsSubsetDiv = document.createElement("div");
  56581. this._optionsSubsetDiv.style.paddingTop = "5px";
  56582. this._optionsSubsetDiv.style.paddingBottom = "5px";
  56583. this._optionsSubsetDiv.style.overflowY = "auto";
  56584. this._optionsSubsetDiv.style.maxHeight = "200px";
  56585. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  56586. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  56587. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  56588. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  56589. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  56590. _this._displayTree = element.checked;
  56591. _this._needToRefreshMeshesTree = true;
  56592. });
  56593. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56594. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  56595. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  56596. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  56597. _this._labelsEnabled = element.checked;
  56598. if (!_this._labelsEnabled) {
  56599. _this._clearLabels();
  56600. }
  56601. });
  56602. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  56603. if (element.checked) {
  56604. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  56605. }
  56606. else {
  56607. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  56608. }
  56609. });
  56610. ;
  56611. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56612. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  56613. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  56614. if (element.checked) {
  56615. _this._scene.forceWireframe = false;
  56616. _this._scene.forcePointsCloud = false;
  56617. }
  56618. });
  56619. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  56620. if (element.checked) {
  56621. _this._scene.forceWireframe = true;
  56622. _this._scene.forcePointsCloud = false;
  56623. }
  56624. });
  56625. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  56626. if (element.checked) {
  56627. _this._scene.forceWireframe = false;
  56628. _this._scene.forcePointsCloud = true;
  56629. }
  56630. });
  56631. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56632. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  56633. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  56634. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  56635. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  56636. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  56637. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  56638. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  56639. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  56640. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  56641. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  56642. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  56643. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56644. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  56645. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  56646. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  56647. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  56648. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  56649. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  56650. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  56651. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  56652. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  56653. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  56654. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  56655. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  56656. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  56657. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  56658. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  56659. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56660. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56661. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  56662. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  56663. if (element.checked) {
  56664. _this._scene.headphone = true;
  56665. }
  56666. });
  56667. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  56668. if (element.checked) {
  56669. _this._scene.headphone = false;
  56670. }
  56671. });
  56672. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  56673. _this._scene.audioEnabled = !element.checked;
  56674. });
  56675. }
  56676. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56677. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  56678. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  56679. if (!element.checked) {
  56680. _this._clearSkeletonViewers();
  56681. return;
  56682. }
  56683. for (var index = 0; index < _this._scene.meshes.length; index++) {
  56684. var mesh = _this._scene.meshes[index];
  56685. if (mesh.skeleton) {
  56686. var found = false;
  56687. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  56688. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  56689. found = true;
  56690. break;
  56691. }
  56692. }
  56693. if (found) {
  56694. continue;
  56695. }
  56696. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  56697. viewer.isEnabled = true;
  56698. _this._skeletonViewers.push(viewer);
  56699. }
  56700. }
  56701. });
  56702. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56703. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  56704. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  56705. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  56706. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  56707. if (_this._camera) {
  56708. console.log(_this._camera);
  56709. }
  56710. else {
  56711. console.warn("No camera defined, or debug layer created before camera creation!");
  56712. }
  56713. });
  56714. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  56715. this._globalDiv.appendChild(this._statsDiv);
  56716. this._globalDiv.appendChild(this._logDiv);
  56717. this._globalDiv.appendChild(this._optionsDiv);
  56718. this._globalDiv.appendChild(this._treeDiv);
  56719. }
  56720. };
  56721. DebugLayer.prototype._displayStats = function () {
  56722. var scene = this._scene;
  56723. var engine = scene.getEngine();
  56724. var glInfo = engine.getGlInfo();
  56725. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  56726. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  56727. + "<b>Count</b><br>"
  56728. + "Total meshes: " + scene.meshes.length + "<br>"
  56729. + "Total lights: " + scene.lights.length + "<br>"
  56730. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  56731. + "Total materials: " + scene.materials.length + "<br>"
  56732. + "Total textures: " + scene.textures.length + "<br>"
  56733. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  56734. + "Active indices: " + scene.getActiveIndices() + "<br>"
  56735. + "Active bones: " + scene.getActiveBones() + "<br>"
  56736. + "Active particles: " + scene.getActiveParticles() + "<br>"
  56737. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  56738. + "<b>Duration</b><br>"
  56739. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  56740. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  56741. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  56742. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  56743. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  56744. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  56745. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  56746. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  56747. + "</div>"
  56748. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  56749. + "<b>Extensions</b><br>"
  56750. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  56751. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  56752. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  56753. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  56754. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  56755. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  56756. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  56757. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  56758. + "</div><br>"
  56759. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  56760. + "<b>Caps.</b><br>"
  56761. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  56762. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  56763. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  56764. + "<b>Info</b><br>"
  56765. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  56766. + glInfo.version + "<br>"
  56767. + "</div><br>"
  56768. + glInfo.renderer + "<br>";
  56769. if (this.customStatsFunction) {
  56770. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  56771. }
  56772. };
  56773. return DebugLayer;
  56774. })();
  56775. BABYLON.DebugLayer = DebugLayer;
  56776. })(BABYLON || (BABYLON = {}));
  56777. 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,1);\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*(boundingMax-boundingMin));\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\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,1);\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.a == 0.05) {\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;\n\natt vec3 properties;\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);\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\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;\nif (alignToPixel == 1.0)\n{\npos.xy=floor((pos2.xy*sizeUV*textureSize)-origin);\n} else {\npos.xy=(pos2.xy*sizeUV*textureSize)-origin;\n}\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\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":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\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;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\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#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\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);\nif (color.a<0.05)\ndiscard;\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,1);\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}"};
  56778. 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"};
  56779. 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={}));";
  56780. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  56781. module.exports = BABYLON;
  56782. };