babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265
  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. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  915. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  916. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  917. result.copyFrom(Tmp.Vector3[0]);
  918. };
  919. Vector3.Normalize = function (vector) {
  920. var result = Vector3.Zero();
  921. Vector3.NormalizeToRef(vector, result);
  922. return result;
  923. };
  924. Vector3.NormalizeToRef = function (vector, result) {
  925. result.copyFrom(vector);
  926. result.normalize();
  927. };
  928. Vector3.Project = function (vector, world, transform, viewport) {
  929. var cw = viewport.width;
  930. var ch = viewport.height;
  931. var cx = viewport.x;
  932. var cy = viewport.y;
  933. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  934. Matrix.FromValuesToRef(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, viewportMatrix);
  935. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  936. world.multiplyToRef(transform, matrix);
  937. matrix.multiplyToRef(viewportMatrix, matrix);
  938. return Vector3.TransformCoordinates(vector, matrix);
  939. };
  940. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  941. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  942. world.multiplyToRef(transform, matrix);
  943. matrix.invert();
  944. source.x = source.x / viewportWidth * 2 - 1;
  945. source.y = -(source.y / viewportHeight * 2 - 1);
  946. var vector = Vector3.TransformCoordinates(source, matrix);
  947. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  948. if (MathTools.WithinEpsilon(num, 1.0)) {
  949. vector = vector.scale(1.0 / num);
  950. }
  951. return vector;
  952. };
  953. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  954. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  955. world.multiplyToRef(view, matrix);
  956. matrix.multiplyToRef(projection, matrix);
  957. matrix.invert();
  958. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  959. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  960. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  961. if (MathTools.WithinEpsilon(num, 1.0)) {
  962. vector = vector.scale(1.0 / num);
  963. }
  964. return vector;
  965. };
  966. Vector3.Minimize = function (left, right) {
  967. var min = left.clone();
  968. min.MinimizeInPlace(right);
  969. return min;
  970. };
  971. Vector3.Maximize = function (left, right) {
  972. var max = left.clone();
  973. max.MaximizeInPlace(right);
  974. return max;
  975. };
  976. Vector3.Distance = function (value1, value2) {
  977. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  978. };
  979. Vector3.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. var z = value1.z - value2.z;
  983. return (x * x) + (y * y) + (z * z);
  984. };
  985. Vector3.Center = function (value1, value2) {
  986. var center = value1.add(value2);
  987. center.scaleInPlace(0.5);
  988. return center;
  989. };
  990. /**
  991. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  992. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  993. * to something in order to rotate it from its local system to the given target system.
  994. */
  995. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  996. var rotation = Vector3.Zero();
  997. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  998. return rotation;
  999. };
  1000. /**
  1001. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1002. */
  1003. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1004. var u = axis1.normalize();
  1005. var w = axis3.normalize();
  1006. // world axis
  1007. var X = Axis.X;
  1008. var Y = Axis.Y;
  1009. // equation unknowns and vars
  1010. var yaw = 0.0;
  1011. var pitch = 0.0;
  1012. var roll = 0.0;
  1013. var x = 0.0;
  1014. var y = 0.0;
  1015. var z = 0.0;
  1016. var t = 0.0;
  1017. var sign = -1.0;
  1018. var nbRevert = 0;
  1019. var cross = Tmp.Vector3[0];
  1020. var dot = 0.0;
  1021. // step 1 : rotation around w
  1022. // Rv3(u) = u1, and u1 belongs to plane xOz
  1023. // Rv3(w) = w1 = w invariant
  1024. var u1 = Tmp.Vector3[1];
  1025. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1026. z = 1.0;
  1027. }
  1028. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1029. x = 1.0;
  1030. }
  1031. else {
  1032. t = w.z / w.x;
  1033. x = -t * Math.sqrt(1 / (1 + t * t));
  1034. z = Math.sqrt(1 / (1 + t * t));
  1035. }
  1036. u1.x = x;
  1037. u1.y = y;
  1038. u1.z = z;
  1039. u1.normalize();
  1040. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1041. cross.normalize();
  1042. if (Vector3.Dot(w, cross) < 0) {
  1043. sign = 1.0;
  1044. }
  1045. dot = Vector3.Dot(u, u1);
  1046. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1047. roll = Math.acos(dot) * sign;
  1048. if (Vector3.Dot(u1, X) < 0) {
  1049. roll = Math.PI + roll;
  1050. u1 = u1.scaleInPlace(-1);
  1051. nbRevert++;
  1052. }
  1053. // step 2 : rotate around u1
  1054. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1055. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1056. var w2 = Tmp.Vector3[2];
  1057. var v2 = Tmp.Vector3[3];
  1058. x = 0.0;
  1059. y = 0.0;
  1060. z = 0.0;
  1061. sign = -1.0;
  1062. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1063. x = 1.0;
  1064. }
  1065. else {
  1066. t = u1.z / u1.x;
  1067. x = -t * Math.sqrt(1 / (1 + t * t));
  1068. z = Math.sqrt(1 / (1 + t * t));
  1069. }
  1070. w2.x = x;
  1071. w2.y = y;
  1072. w2.z = z;
  1073. w2.normalize();
  1074. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1075. v2.normalize();
  1076. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1077. cross.normalize();
  1078. if (Vector3.Dot(u1, cross) < 0) {
  1079. sign = 1.0;
  1080. }
  1081. dot = Vector3.Dot(w, w2);
  1082. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1083. pitch = Math.acos(dot) * sign;
  1084. if (Vector3.Dot(v2, Y) < 0) {
  1085. pitch = Math.PI + pitch;
  1086. nbRevert++;
  1087. }
  1088. // step 3 : rotate around v2
  1089. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1090. sign = -1.0;
  1091. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1092. cross.normalize();
  1093. if (Vector3.Dot(cross, Y) < 0) {
  1094. sign = 1.0;
  1095. }
  1096. dot = Vector3.Dot(u1, X);
  1097. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1098. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1099. if (dot < 0 && nbRevert < 2) {
  1100. yaw = Math.PI + yaw;
  1101. }
  1102. ref.x = pitch;
  1103. ref.y = yaw;
  1104. ref.z = roll;
  1105. };
  1106. return Vector3;
  1107. })();
  1108. BABYLON.Vector3 = Vector3;
  1109. //Vector4 class created for EulerAngle class conversion to Quaternion
  1110. var Vector4 = (function () {
  1111. function Vector4(x, y, z, w) {
  1112. this.x = x;
  1113. this.y = y;
  1114. this.z = z;
  1115. this.w = w;
  1116. }
  1117. Vector4.prototype.toString = function () {
  1118. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1119. };
  1120. Vector4.prototype.getClassName = function () {
  1121. return "Vector4";
  1122. };
  1123. Vector4.prototype.getHashCode = function () {
  1124. var hash = this.x || 0;
  1125. hash = (hash * 397) ^ (this.y || 0);
  1126. hash = (hash * 397) ^ (this.z || 0);
  1127. hash = (hash * 397) ^ (this.w || 0);
  1128. return hash;
  1129. };
  1130. // Operators
  1131. Vector4.prototype.asArray = function () {
  1132. var result = [];
  1133. this.toArray(result, 0);
  1134. return result;
  1135. };
  1136. Vector4.prototype.toArray = function (array, index) {
  1137. if (index === undefined) {
  1138. index = 0;
  1139. }
  1140. array[index] = this.x;
  1141. array[index + 1] = this.y;
  1142. array[index + 2] = this.z;
  1143. array[index + 3] = this.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.addInPlace = function (otherVector) {
  1147. this.x += otherVector.x;
  1148. this.y += otherVector.y;
  1149. this.z += otherVector.z;
  1150. this.w += otherVector.w;
  1151. return this;
  1152. };
  1153. Vector4.prototype.add = function (otherVector) {
  1154. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1155. };
  1156. Vector4.prototype.addToRef = function (otherVector, result) {
  1157. result.x = this.x + otherVector.x;
  1158. result.y = this.y + otherVector.y;
  1159. result.z = this.z + otherVector.z;
  1160. result.w = this.w + otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.subtractInPlace = function (otherVector) {
  1164. this.x -= otherVector.x;
  1165. this.y -= otherVector.y;
  1166. this.z -= otherVector.z;
  1167. this.w -= otherVector.w;
  1168. return this;
  1169. };
  1170. Vector4.prototype.subtract = function (otherVector) {
  1171. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1172. };
  1173. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1174. result.x = this.x - otherVector.x;
  1175. result.y = this.y - otherVector.y;
  1176. result.z = this.z - otherVector.z;
  1177. result.w = this.w - otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1181. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1182. };
  1183. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1184. result.x = this.x - x;
  1185. result.y = this.y - y;
  1186. result.z = this.z - z;
  1187. result.w = this.w - w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.negate = function () {
  1191. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1192. };
  1193. Vector4.prototype.scaleInPlace = function (scale) {
  1194. this.x *= scale;
  1195. this.y *= scale;
  1196. this.z *= scale;
  1197. this.w *= scale;
  1198. return this;
  1199. };
  1200. Vector4.prototype.scale = function (scale) {
  1201. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1202. };
  1203. Vector4.prototype.scaleToRef = function (scale, result) {
  1204. result.x = this.x * scale;
  1205. result.y = this.y * scale;
  1206. result.z = this.z * scale;
  1207. result.w = this.w * scale;
  1208. };
  1209. Vector4.prototype.equals = function (otherVector) {
  1210. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1211. };
  1212. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1213. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1214. return otherVector
  1215. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1216. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1217. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1218. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1219. };
  1220. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1221. return this.x === x && this.y === y && this.z === z && this.w === w;
  1222. };
  1223. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1224. this.x *= otherVector.x;
  1225. this.y *= otherVector.y;
  1226. this.z *= otherVector.z;
  1227. this.w *= otherVector.w;
  1228. return this;
  1229. };
  1230. Vector4.prototype.multiply = function (otherVector) {
  1231. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1232. };
  1233. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1234. result.x = this.x * otherVector.x;
  1235. result.y = this.y * otherVector.y;
  1236. result.z = this.z * otherVector.z;
  1237. result.w = this.w * otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1241. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1242. };
  1243. Vector4.prototype.divide = function (otherVector) {
  1244. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1245. };
  1246. Vector4.prototype.divideToRef = function (otherVector, result) {
  1247. result.x = this.x / otherVector.x;
  1248. result.y = this.y / otherVector.y;
  1249. result.z = this.z / otherVector.z;
  1250. result.w = this.w / otherVector.w;
  1251. return this;
  1252. };
  1253. Vector4.prototype.MinimizeInPlace = function (other) {
  1254. if (other.x < this.x)
  1255. this.x = other.x;
  1256. if (other.y < this.y)
  1257. this.y = other.y;
  1258. if (other.z < this.z)
  1259. this.z = other.z;
  1260. if (other.w < this.w)
  1261. this.w = other.w;
  1262. return this;
  1263. };
  1264. Vector4.prototype.MaximizeInPlace = function (other) {
  1265. if (other.x > this.x)
  1266. this.x = other.x;
  1267. if (other.y > this.y)
  1268. this.y = other.y;
  1269. if (other.z > this.z)
  1270. this.z = other.z;
  1271. if (other.w > this.w)
  1272. this.w = other.w;
  1273. return this;
  1274. };
  1275. // Properties
  1276. Vector4.prototype.length = function () {
  1277. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1278. };
  1279. Vector4.prototype.lengthSquared = function () {
  1280. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1281. };
  1282. // Methods
  1283. Vector4.prototype.normalize = function () {
  1284. var len = this.length();
  1285. if (len === 0)
  1286. return this;
  1287. var num = 1.0 / len;
  1288. this.x *= num;
  1289. this.y *= num;
  1290. this.z *= num;
  1291. this.w *= num;
  1292. return this;
  1293. };
  1294. Vector4.prototype.toVector3 = function () {
  1295. return new Vector3(this.x, this.y, this.z);
  1296. };
  1297. Vector4.prototype.clone = function () {
  1298. return new Vector4(this.x, this.y, this.z, this.w);
  1299. };
  1300. Vector4.prototype.copyFrom = function (source) {
  1301. this.x = source.x;
  1302. this.y = source.y;
  1303. this.z = source.z;
  1304. this.w = source.w;
  1305. return this;
  1306. };
  1307. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1308. this.x = x;
  1309. this.y = y;
  1310. this.z = z;
  1311. this.w = w;
  1312. return this;
  1313. };
  1314. // Statics
  1315. Vector4.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1320. };
  1321. Vector4.FromArrayToRef = function (array, offset, result) {
  1322. result.x = array[offset];
  1323. result.y = array[offset + 1];
  1324. result.z = array[offset + 2];
  1325. result.w = array[offset + 3];
  1326. };
  1327. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1328. result.x = array[offset];
  1329. result.y = array[offset + 1];
  1330. result.z = array[offset + 2];
  1331. result.w = array[offset + 3];
  1332. };
  1333. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1334. result.x = x;
  1335. result.y = y;
  1336. result.z = z;
  1337. result.w = w;
  1338. };
  1339. Vector4.Zero = function () {
  1340. return new Vector4(0, 0, 0, 0);
  1341. };
  1342. Vector4.Normalize = function (vector) {
  1343. var result = Vector4.Zero();
  1344. Vector4.NormalizeToRef(vector, result);
  1345. return result;
  1346. };
  1347. Vector4.NormalizeToRef = function (vector, result) {
  1348. result.copyFrom(vector);
  1349. result.normalize();
  1350. };
  1351. Vector4.Minimize = function (left, right) {
  1352. var min = left.clone();
  1353. min.MinimizeInPlace(right);
  1354. return min;
  1355. };
  1356. Vector4.Maximize = function (left, right) {
  1357. var max = left.clone();
  1358. max.MaximizeInPlace(right);
  1359. return max;
  1360. };
  1361. Vector4.Distance = function (value1, value2) {
  1362. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1363. };
  1364. Vector4.DistanceSquared = function (value1, value2) {
  1365. var x = value1.x - value2.x;
  1366. var y = value1.y - value2.y;
  1367. var z = value1.z - value2.z;
  1368. var w = value1.w - value2.w;
  1369. return (x * x) + (y * y) + (z * z) + (w * w);
  1370. };
  1371. Vector4.Center = function (value1, value2) {
  1372. var center = value1.add(value2);
  1373. center.scaleInPlace(0.5);
  1374. return center;
  1375. };
  1376. return Vector4;
  1377. })();
  1378. BABYLON.Vector4 = Vector4;
  1379. var Size = (function () {
  1380. function Size(width, height) {
  1381. this.width = width;
  1382. this.height = height;
  1383. }
  1384. Size.prototype.toString = function () {
  1385. return "{W: " + this.width + ", H: " + this.height + "}";
  1386. };
  1387. Size.prototype.getClassName = function () {
  1388. return "Size";
  1389. };
  1390. Size.prototype.getHashCode = function () {
  1391. var hash = this.width || 0;
  1392. hash = (hash * 397) ^ (this.height || 0);
  1393. return hash;
  1394. };
  1395. Size.prototype.copyFrom = function (src) {
  1396. this.width = src.width;
  1397. this.height = src.height;
  1398. };
  1399. Size.prototype.copyFromFloats = function (width, height) {
  1400. this.width = width;
  1401. this.height = height;
  1402. };
  1403. Size.prototype.multiplyByFloats = function (w, h) {
  1404. return new Size(this.width * w, this.height * h);
  1405. };
  1406. Size.prototype.clone = function () {
  1407. return new Size(this.width, this.height);
  1408. };
  1409. Size.prototype.equals = function (other) {
  1410. if (!other) {
  1411. return false;
  1412. }
  1413. return (this.width === other.width) && (this.height === other.height);
  1414. };
  1415. Object.defineProperty(Size.prototype, "surface", {
  1416. get: function () {
  1417. return this.width * this.height;
  1418. },
  1419. enumerable: true,
  1420. configurable: true
  1421. });
  1422. Size.Zero = function () {
  1423. return new Size(0, 0);
  1424. };
  1425. Size.prototype.add = function (otherSize) {
  1426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1427. return r;
  1428. };
  1429. Size.prototype.substract = function (otherSize) {
  1430. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1431. return r;
  1432. };
  1433. Size.Lerp = function (start, end, amount) {
  1434. var w = start.width + ((end.width - start.width) * amount);
  1435. var h = start.height + ((end.height - start.height) * amount);
  1436. return new Size(w, h);
  1437. };
  1438. return Size;
  1439. })();
  1440. BABYLON.Size = Size;
  1441. var Quaternion = (function () {
  1442. function Quaternion(x, y, z, w) {
  1443. if (x === void 0) { x = 0; }
  1444. if (y === void 0) { y = 0; }
  1445. if (z === void 0) { z = 0; }
  1446. if (w === void 0) { w = 1; }
  1447. this.x = x;
  1448. this.y = y;
  1449. this.z = z;
  1450. this.w = w;
  1451. }
  1452. Quaternion.prototype.toString = function () {
  1453. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1454. };
  1455. Quaternion.prototype.getClassName = function () {
  1456. return "Quaternion";
  1457. };
  1458. Quaternion.prototype.getHashCode = function () {
  1459. var hash = this.x || 0;
  1460. hash = (hash * 397) ^ (this.y || 0);
  1461. hash = (hash * 397) ^ (this.z || 0);
  1462. hash = (hash * 397) ^ (this.w || 0);
  1463. return hash;
  1464. };
  1465. Quaternion.prototype.asArray = function () {
  1466. return [this.x, this.y, this.z, this.w];
  1467. };
  1468. Quaternion.prototype.equals = function (otherQuaternion) {
  1469. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1470. };
  1471. Quaternion.prototype.clone = function () {
  1472. return new Quaternion(this.x, this.y, this.z, this.w);
  1473. };
  1474. Quaternion.prototype.copyFrom = function (other) {
  1475. this.x = other.x;
  1476. this.y = other.y;
  1477. this.z = other.z;
  1478. this.w = other.w;
  1479. return this;
  1480. };
  1481. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1482. this.x = x;
  1483. this.y = y;
  1484. this.z = z;
  1485. this.w = w;
  1486. return this;
  1487. };
  1488. Quaternion.prototype.add = function (other) {
  1489. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1490. };
  1491. Quaternion.prototype.subtract = function (other) {
  1492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1493. };
  1494. Quaternion.prototype.scale = function (value) {
  1495. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1496. };
  1497. Quaternion.prototype.multiply = function (q1) {
  1498. var result = new Quaternion(0, 0, 0, 1.0);
  1499. this.multiplyToRef(q1, result);
  1500. return result;
  1501. };
  1502. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1503. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1504. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1505. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1506. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1507. result.copyFromFloats(x, y, z, w);
  1508. return this;
  1509. };
  1510. Quaternion.prototype.multiplyInPlace = function (q1) {
  1511. this.multiplyToRef(q1, this);
  1512. return this;
  1513. };
  1514. Quaternion.prototype.conjugateToRef = function (ref) {
  1515. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1516. return this;
  1517. };
  1518. Quaternion.prototype.conjugateInPlace = function () {
  1519. this.x *= -1;
  1520. this.y *= -1;
  1521. this.z *= -1;
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugate = function () {
  1525. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1526. return result;
  1527. };
  1528. Quaternion.prototype.length = function () {
  1529. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1530. };
  1531. Quaternion.prototype.normalize = function () {
  1532. var length = 1.0 / this.length();
  1533. this.x *= length;
  1534. this.y *= length;
  1535. this.z *= length;
  1536. this.w *= length;
  1537. return this;
  1538. };
  1539. Quaternion.prototype.toEulerAngles = function (order) {
  1540. if (order === void 0) { order = "YZX"; }
  1541. var result = Vector3.Zero();
  1542. this.toEulerAnglesToRef(result, order);
  1543. return result;
  1544. };
  1545. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1546. if (order === void 0) { order = "YZX"; }
  1547. var heading, attitude, bank;
  1548. var x = this.x, y = this.y, z = this.z, w = this.w;
  1549. switch (order) {
  1550. case "YZX":
  1551. var test = x * y + z * w;
  1552. if (test > 0.499) {
  1553. heading = 2 * Math.atan2(x, w);
  1554. attitude = Math.PI / 2;
  1555. bank = 0;
  1556. }
  1557. if (test < -0.499) {
  1558. heading = -2 * Math.atan2(x, w);
  1559. attitude = -Math.PI / 2;
  1560. bank = 0;
  1561. }
  1562. if (isNaN(heading)) {
  1563. var sqx = x * x;
  1564. var sqy = y * y;
  1565. var sqz = z * z;
  1566. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1567. attitude = Math.asin(2 * test); // attitude
  1568. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1569. }
  1570. break;
  1571. default:
  1572. throw new Error("Euler order " + order + " not supported yet.");
  1573. }
  1574. result.y = heading;
  1575. result.z = attitude;
  1576. result.x = bank;
  1577. return this;
  1578. };
  1579. ;
  1580. Quaternion.prototype.toRotationMatrix = function (result) {
  1581. var xx = this.x * this.x;
  1582. var yy = this.y * this.y;
  1583. var zz = this.z * this.z;
  1584. var xy = this.x * this.y;
  1585. var zw = this.z * this.w;
  1586. var zx = this.z * this.x;
  1587. var yw = this.y * this.w;
  1588. var yz = this.y * this.z;
  1589. var xw = this.x * this.w;
  1590. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1591. result.m[1] = 2.0 * (xy + zw);
  1592. result.m[2] = 2.0 * (zx - yw);
  1593. result.m[3] = 0;
  1594. result.m[4] = 2.0 * (xy - zw);
  1595. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1596. result.m[6] = 2.0 * (yz + xw);
  1597. result.m[7] = 0;
  1598. result.m[8] = 2.0 * (zx + yw);
  1599. result.m[9] = 2.0 * (yz - xw);
  1600. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1601. result.m[11] = 0;
  1602. result.m[12] = 0;
  1603. result.m[13] = 0;
  1604. result.m[14] = 0;
  1605. result.m[15] = 1.0;
  1606. return this;
  1607. };
  1608. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1609. Quaternion.FromRotationMatrixToRef(matrix, this);
  1610. return this;
  1611. };
  1612. // Statics
  1613. Quaternion.FromRotationMatrix = function (matrix) {
  1614. var result = new Quaternion();
  1615. Quaternion.FromRotationMatrixToRef(matrix, result);
  1616. return result;
  1617. };
  1618. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1619. var data = matrix.m;
  1620. var m11 = data[0], m12 = data[4], m13 = data[8];
  1621. var m21 = data[1], m22 = data[5], m23 = data[9];
  1622. var m31 = data[2], m32 = data[6], m33 = data[10];
  1623. var trace = m11 + m22 + m33;
  1624. var s;
  1625. if (trace > 0) {
  1626. s = 0.5 / Math.sqrt(trace + 1.0);
  1627. result.w = 0.25 / s;
  1628. result.x = (m32 - m23) * s;
  1629. result.y = (m13 - m31) * s;
  1630. result.z = (m21 - m12) * s;
  1631. }
  1632. else if (m11 > m22 && m11 > m33) {
  1633. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1634. result.w = (m32 - m23) / s;
  1635. result.x = 0.25 * s;
  1636. result.y = (m12 + m21) / s;
  1637. result.z = (m13 + m31) / s;
  1638. }
  1639. else if (m22 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1641. result.w = (m13 - m31) / s;
  1642. result.x = (m12 + m21) / s;
  1643. result.y = 0.25 * s;
  1644. result.z = (m23 + m32) / s;
  1645. }
  1646. else {
  1647. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1648. result.w = (m21 - m12) / s;
  1649. result.x = (m13 + m31) / s;
  1650. result.y = (m23 + m32) / s;
  1651. result.z = 0.25 * s;
  1652. }
  1653. };
  1654. Quaternion.Inverse = function (q) {
  1655. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1656. };
  1657. Quaternion.Identity = function () {
  1658. return new Quaternion(0, 0, 0, 1);
  1659. };
  1660. Quaternion.RotationAxis = function (axis, angle) {
  1661. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1662. };
  1663. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1664. var sin = Math.sin(angle / 2);
  1665. axis.normalize();
  1666. result.w = Math.cos(angle / 2);
  1667. result.x = axis.x * sin;
  1668. result.y = axis.y * sin;
  1669. result.z = axis.z * sin;
  1670. return result;
  1671. };
  1672. Quaternion.FromArray = function (array, offset) {
  1673. if (!offset) {
  1674. offset = 0;
  1675. }
  1676. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1677. };
  1678. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1679. var q = new Quaternion();
  1680. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1681. return q;
  1682. };
  1683. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1684. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1685. var halfRoll = roll * 0.5;
  1686. var halfPitch = pitch * 0.5;
  1687. var halfYaw = yaw * 0.5;
  1688. var sinRoll = Math.sin(halfRoll);
  1689. var cosRoll = Math.cos(halfRoll);
  1690. var sinPitch = Math.sin(halfPitch);
  1691. var cosPitch = Math.cos(halfPitch);
  1692. var sinYaw = Math.sin(halfYaw);
  1693. var cosYaw = Math.cos(halfYaw);
  1694. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1695. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1696. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1697. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1698. };
  1699. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1700. var result = new Quaternion();
  1701. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1702. return result;
  1703. };
  1704. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1705. // Produces a quaternion from Euler angles in the z-x-z orientation
  1706. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1707. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1708. var halfBeta = beta * 0.5;
  1709. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1710. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1711. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1712. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1713. };
  1714. Quaternion.Slerp = function (left, right, amount) {
  1715. var num2;
  1716. var num3;
  1717. var num = amount;
  1718. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1719. var flag = false;
  1720. if (num4 < 0) {
  1721. flag = true;
  1722. num4 = -num4;
  1723. }
  1724. if (num4 > 0.999999) {
  1725. num3 = 1 - num;
  1726. num2 = flag ? -num : num;
  1727. }
  1728. else {
  1729. var num5 = Math.acos(num4);
  1730. var num6 = (1.0 / Math.sin(num5));
  1731. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1732. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1733. }
  1734. 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));
  1735. };
  1736. return Quaternion;
  1737. })();
  1738. BABYLON.Quaternion = Quaternion;
  1739. var Matrix = (function () {
  1740. function Matrix() {
  1741. this.m = new Float32Array(16);
  1742. }
  1743. // Properties
  1744. Matrix.prototype.isIdentity = function () {
  1745. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1746. return false;
  1747. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1751. return false;
  1752. return true;
  1753. };
  1754. Matrix.prototype.determinant = function () {
  1755. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1756. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1757. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1758. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1759. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1760. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1761. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1762. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1763. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1764. };
  1765. // Methods
  1766. Matrix.prototype.toArray = function () {
  1767. return this.m;
  1768. };
  1769. Matrix.prototype.asArray = function () {
  1770. return this.toArray();
  1771. };
  1772. Matrix.prototype.invert = function () {
  1773. this.invertToRef(this);
  1774. return this;
  1775. };
  1776. Matrix.prototype.reset = function () {
  1777. for (var index = 0; index < 16; index++) {
  1778. this.m[index] = 0;
  1779. }
  1780. return this;
  1781. };
  1782. Matrix.prototype.add = function (other) {
  1783. var result = new Matrix();
  1784. this.addToRef(other, result);
  1785. return result;
  1786. };
  1787. Matrix.prototype.addToRef = function (other, result) {
  1788. for (var index = 0; index < 16; index++) {
  1789. result.m[index] = this.m[index] + other.m[index];
  1790. }
  1791. return this;
  1792. };
  1793. Matrix.prototype.addToSelf = function (other) {
  1794. for (var index = 0; index < 16; index++) {
  1795. this.m[index] += other.m[index];
  1796. }
  1797. return this;
  1798. };
  1799. Matrix.prototype.invertToRef = function (other) {
  1800. var l1 = this.m[0];
  1801. var l2 = this.m[1];
  1802. var l3 = this.m[2];
  1803. var l4 = this.m[3];
  1804. var l5 = this.m[4];
  1805. var l6 = this.m[5];
  1806. var l7 = this.m[6];
  1807. var l8 = this.m[7];
  1808. var l9 = this.m[8];
  1809. var l10 = this.m[9];
  1810. var l11 = this.m[10];
  1811. var l12 = this.m[11];
  1812. var l13 = this.m[12];
  1813. var l14 = this.m[13];
  1814. var l15 = this.m[14];
  1815. var l16 = this.m[15];
  1816. var l17 = (l11 * l16) - (l12 * l15);
  1817. var l18 = (l10 * l16) - (l12 * l14);
  1818. var l19 = (l10 * l15) - (l11 * l14);
  1819. var l20 = (l9 * l16) - (l12 * l13);
  1820. var l21 = (l9 * l15) - (l11 * l13);
  1821. var l22 = (l9 * l14) - (l10 * l13);
  1822. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1823. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1824. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1825. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1826. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1827. var l28 = (l7 * l16) - (l8 * l15);
  1828. var l29 = (l6 * l16) - (l8 * l14);
  1829. var l30 = (l6 * l15) - (l7 * l14);
  1830. var l31 = (l5 * l16) - (l8 * l13);
  1831. var l32 = (l5 * l15) - (l7 * l13);
  1832. var l33 = (l5 * l14) - (l6 * l13);
  1833. var l34 = (l7 * l12) - (l8 * l11);
  1834. var l35 = (l6 * l12) - (l8 * l10);
  1835. var l36 = (l6 * l11) - (l7 * l10);
  1836. var l37 = (l5 * l12) - (l8 * l9);
  1837. var l38 = (l5 * l11) - (l7 * l9);
  1838. var l39 = (l5 * l10) - (l6 * l9);
  1839. other.m[0] = l23 * l27;
  1840. other.m[4] = l24 * l27;
  1841. other.m[8] = l25 * l27;
  1842. other.m[12] = l26 * l27;
  1843. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1844. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1845. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1846. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1847. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1848. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1849. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1850. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1851. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1852. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1853. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1854. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1855. return this;
  1856. };
  1857. Matrix.prototype.setTranslation = function (vector3) {
  1858. this.m[12] = vector3.x;
  1859. this.m[13] = vector3.y;
  1860. this.m[14] = vector3.z;
  1861. return this;
  1862. };
  1863. Matrix.prototype.getTranslation = function () {
  1864. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1865. };
  1866. Matrix.prototype.multiply = function (other) {
  1867. var result = new Matrix();
  1868. this.multiplyToRef(other, result);
  1869. return result;
  1870. };
  1871. Matrix.prototype.copyFrom = function (other) {
  1872. for (var index = 0; index < 16; index++) {
  1873. this.m[index] = other.m[index];
  1874. }
  1875. return this;
  1876. };
  1877. Matrix.prototype.copyToArray = function (array, offset) {
  1878. if (offset === void 0) { offset = 0; }
  1879. for (var index = 0; index < 16; index++) {
  1880. array[offset + index] = this.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.multiplyToRef = function (other, result) {
  1885. this.multiplyToArray(other, result.m, 0);
  1886. return this;
  1887. };
  1888. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1889. var tm0 = this.m[0];
  1890. var tm1 = this.m[1];
  1891. var tm2 = this.m[2];
  1892. var tm3 = this.m[3];
  1893. var tm4 = this.m[4];
  1894. var tm5 = this.m[5];
  1895. var tm6 = this.m[6];
  1896. var tm7 = this.m[7];
  1897. var tm8 = this.m[8];
  1898. var tm9 = this.m[9];
  1899. var tm10 = this.m[10];
  1900. var tm11 = this.m[11];
  1901. var tm12 = this.m[12];
  1902. var tm13 = this.m[13];
  1903. var tm14 = this.m[14];
  1904. var tm15 = this.m[15];
  1905. var om0 = other.m[0];
  1906. var om1 = other.m[1];
  1907. var om2 = other.m[2];
  1908. var om3 = other.m[3];
  1909. var om4 = other.m[4];
  1910. var om5 = other.m[5];
  1911. var om6 = other.m[6];
  1912. var om7 = other.m[7];
  1913. var om8 = other.m[8];
  1914. var om9 = other.m[9];
  1915. var om10 = other.m[10];
  1916. var om11 = other.m[11];
  1917. var om12 = other.m[12];
  1918. var om13 = other.m[13];
  1919. var om14 = other.m[14];
  1920. var om15 = other.m[15];
  1921. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1922. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1923. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1924. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1925. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1926. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1927. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1928. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1929. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1930. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1931. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1932. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1933. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1934. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1935. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1936. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1937. return this;
  1938. };
  1939. Matrix.prototype.equals = function (value) {
  1940. return value &&
  1941. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1942. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1943. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1944. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1945. };
  1946. Matrix.prototype.clone = function () {
  1947. 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]);
  1948. };
  1949. Matrix.prototype.getClassName = function () {
  1950. return "Matrix";
  1951. };
  1952. Matrix.prototype.getHashCode = function () {
  1953. var hash = this.m[0] || 0;
  1954. for (var i = 1; i < 16; i++) {
  1955. hash = (hash * 397) ^ (this.m[i] || 0);
  1956. }
  1957. return hash;
  1958. };
  1959. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1960. translation.x = this.m[12];
  1961. translation.y = this.m[13];
  1962. translation.z = this.m[14];
  1963. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1964. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1965. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1966. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1967. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1968. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1969. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1970. rotation.x = 0;
  1971. rotation.y = 0;
  1972. rotation.z = 0;
  1973. rotation.w = 1;
  1974. return false;
  1975. }
  1976. 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);
  1977. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1978. return true;
  1979. };
  1980. // Statics
  1981. Matrix.FromArray = function (array, offset) {
  1982. var result = new Matrix();
  1983. if (!offset) {
  1984. offset = 0;
  1985. }
  1986. Matrix.FromArrayToRef(array, offset, result);
  1987. return result;
  1988. };
  1989. Matrix.FromArrayToRef = function (array, offset, result) {
  1990. for (var index = 0; index < 16; index++) {
  1991. result.m[index] = array[index + offset];
  1992. }
  1993. };
  1994. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1995. for (var index = 0; index < 16; index++) {
  1996. result.m[index] = array[index + offset] * scale;
  1997. }
  1998. };
  1999. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2000. result.m[0] = initialM11;
  2001. result.m[1] = initialM12;
  2002. result.m[2] = initialM13;
  2003. result.m[3] = initialM14;
  2004. result.m[4] = initialM21;
  2005. result.m[5] = initialM22;
  2006. result.m[6] = initialM23;
  2007. result.m[7] = initialM24;
  2008. result.m[8] = initialM31;
  2009. result.m[9] = initialM32;
  2010. result.m[10] = initialM33;
  2011. result.m[11] = initialM34;
  2012. result.m[12] = initialM41;
  2013. result.m[13] = initialM42;
  2014. result.m[14] = initialM43;
  2015. result.m[15] = initialM44;
  2016. };
  2017. Matrix.prototype.getRow = function (index) {
  2018. if (index < 0 || index > 3) {
  2019. return null;
  2020. }
  2021. var i = index * 4;
  2022. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2023. };
  2024. Matrix.prototype.setRow = function (index, row) {
  2025. if (index < 0 || index > 3) {
  2026. return this;
  2027. }
  2028. var i = index * 4;
  2029. this.m[i + 0] = row.x;
  2030. this.m[i + 1] = row.y;
  2031. this.m[i + 2] = row.z;
  2032. this.m[i + 3] = row.w;
  2033. return this;
  2034. };
  2035. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2036. var result = new Matrix();
  2037. result.m[0] = initialM11;
  2038. result.m[1] = initialM12;
  2039. result.m[2] = initialM13;
  2040. result.m[3] = initialM14;
  2041. result.m[4] = initialM21;
  2042. result.m[5] = initialM22;
  2043. result.m[6] = initialM23;
  2044. result.m[7] = initialM24;
  2045. result.m[8] = initialM31;
  2046. result.m[9] = initialM32;
  2047. result.m[10] = initialM33;
  2048. result.m[11] = initialM34;
  2049. result.m[12] = initialM41;
  2050. result.m[13] = initialM42;
  2051. result.m[14] = initialM43;
  2052. result.m[15] = initialM44;
  2053. return result;
  2054. };
  2055. Matrix.Compose = function (scale, rotation, translation) {
  2056. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2057. var rotationMatrix = Matrix.Identity();
  2058. rotation.toRotationMatrix(rotationMatrix);
  2059. result = result.multiply(rotationMatrix);
  2060. result.setTranslation(translation);
  2061. return result;
  2062. };
  2063. Matrix.Identity = function () {
  2064. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2065. };
  2066. Matrix.IdentityToRef = function (result) {
  2067. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2068. };
  2069. Matrix.Zero = function () {
  2070. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2071. };
  2072. Matrix.RotationX = function (angle) {
  2073. var result = new Matrix();
  2074. Matrix.RotationXToRef(angle, result);
  2075. return result;
  2076. };
  2077. Matrix.Invert = function (source) {
  2078. var result = new Matrix();
  2079. source.invertToRef(result);
  2080. return result;
  2081. };
  2082. Matrix.RotationXToRef = function (angle, result) {
  2083. var s = Math.sin(angle);
  2084. var c = Math.cos(angle);
  2085. result.m[0] = 1.0;
  2086. result.m[15] = 1.0;
  2087. result.m[5] = c;
  2088. result.m[10] = c;
  2089. result.m[9] = -s;
  2090. result.m[6] = s;
  2091. result.m[1] = 0;
  2092. result.m[2] = 0;
  2093. result.m[3] = 0;
  2094. result.m[4] = 0;
  2095. result.m[7] = 0;
  2096. result.m[8] = 0;
  2097. result.m[11] = 0;
  2098. result.m[12] = 0;
  2099. result.m[13] = 0;
  2100. result.m[14] = 0;
  2101. };
  2102. Matrix.RotationY = function (angle) {
  2103. var result = new Matrix();
  2104. Matrix.RotationYToRef(angle, result);
  2105. return result;
  2106. };
  2107. Matrix.RotationYToRef = function (angle, result) {
  2108. var s = Math.sin(angle);
  2109. var c = Math.cos(angle);
  2110. result.m[5] = 1.0;
  2111. result.m[15] = 1.0;
  2112. result.m[0] = c;
  2113. result.m[2] = -s;
  2114. result.m[8] = s;
  2115. result.m[10] = c;
  2116. result.m[1] = 0;
  2117. result.m[3] = 0;
  2118. result.m[4] = 0;
  2119. result.m[6] = 0;
  2120. result.m[7] = 0;
  2121. result.m[9] = 0;
  2122. result.m[11] = 0;
  2123. result.m[12] = 0;
  2124. result.m[13] = 0;
  2125. result.m[14] = 0;
  2126. };
  2127. Matrix.RotationZ = function (angle) {
  2128. var result = new Matrix();
  2129. Matrix.RotationZToRef(angle, result);
  2130. return result;
  2131. };
  2132. Matrix.RotationZToRef = function (angle, result) {
  2133. var s = Math.sin(angle);
  2134. var c = Math.cos(angle);
  2135. result.m[10] = 1.0;
  2136. result.m[15] = 1.0;
  2137. result.m[0] = c;
  2138. result.m[1] = s;
  2139. result.m[4] = -s;
  2140. result.m[5] = c;
  2141. result.m[2] = 0;
  2142. result.m[3] = 0;
  2143. result.m[6] = 0;
  2144. result.m[7] = 0;
  2145. result.m[8] = 0;
  2146. result.m[9] = 0;
  2147. result.m[11] = 0;
  2148. result.m[12] = 0;
  2149. result.m[13] = 0;
  2150. result.m[14] = 0;
  2151. };
  2152. Matrix.RotationAxis = function (axis, angle) {
  2153. var result = Matrix.Zero();
  2154. Matrix.RotationAxisToRef(axis, angle, result);
  2155. return result;
  2156. };
  2157. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2158. var s = Math.sin(-angle);
  2159. var c = Math.cos(-angle);
  2160. var c1 = 1 - c;
  2161. axis.normalize();
  2162. result.m[0] = (axis.x * axis.x) * c1 + c;
  2163. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2164. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2165. result.m[3] = 0.0;
  2166. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2167. result.m[5] = (axis.y * axis.y) * c1 + c;
  2168. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2169. result.m[7] = 0.0;
  2170. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2171. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2172. result.m[10] = (axis.z * axis.z) * c1 + c;
  2173. result.m[11] = 0.0;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2177. var result = new Matrix();
  2178. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2179. return result;
  2180. };
  2181. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2183. this._tempQuaternion.toRotationMatrix(result);
  2184. };
  2185. Matrix.Scaling = function (x, y, z) {
  2186. var result = Matrix.Zero();
  2187. Matrix.ScalingToRef(x, y, z, result);
  2188. return result;
  2189. };
  2190. Matrix.ScalingToRef = function (x, y, z, result) {
  2191. result.m[0] = x;
  2192. result.m[1] = 0;
  2193. result.m[2] = 0;
  2194. result.m[3] = 0;
  2195. result.m[4] = 0;
  2196. result.m[5] = y;
  2197. result.m[6] = 0;
  2198. result.m[7] = 0;
  2199. result.m[8] = 0;
  2200. result.m[9] = 0;
  2201. result.m[10] = z;
  2202. result.m[11] = 0;
  2203. result.m[12] = 0;
  2204. result.m[13] = 0;
  2205. result.m[14] = 0;
  2206. result.m[15] = 1.0;
  2207. };
  2208. Matrix.Translation = function (x, y, z) {
  2209. var result = Matrix.Identity();
  2210. Matrix.TranslationToRef(x, y, z, result);
  2211. return result;
  2212. };
  2213. Matrix.TranslationToRef = function (x, y, z, result) {
  2214. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2215. };
  2216. Matrix.Lerp = function (startValue, endValue, gradient) {
  2217. var result = Matrix.Zero();
  2218. for (var index = 0; index < 16; index++) {
  2219. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2220. }
  2221. return result;
  2222. };
  2223. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2224. var startScale = new Vector3(0, 0, 0);
  2225. var startRotation = new Quaternion();
  2226. var startTranslation = new Vector3(0, 0, 0);
  2227. startValue.decompose(startScale, startRotation, startTranslation);
  2228. var endScale = new Vector3(0, 0, 0);
  2229. var endRotation = new Quaternion();
  2230. var endTranslation = new Vector3(0, 0, 0);
  2231. endValue.decompose(endScale, endRotation, endTranslation);
  2232. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2233. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2234. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2235. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2236. };
  2237. Matrix.LookAtLH = function (eye, target, up) {
  2238. var result = Matrix.Zero();
  2239. Matrix.LookAtLHToRef(eye, target, up, result);
  2240. return result;
  2241. };
  2242. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2243. // Z axis
  2244. target.subtractToRef(eye, this._zAxis);
  2245. this._zAxis.normalize();
  2246. // X axis
  2247. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2248. if (this._xAxis.lengthSquared() === 0) {
  2249. this._xAxis.x = 1.0;
  2250. }
  2251. else {
  2252. this._xAxis.normalize();
  2253. }
  2254. // Y axis
  2255. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2256. this._yAxis.normalize();
  2257. // Eye angles
  2258. var ex = -Vector3.Dot(this._xAxis, eye);
  2259. var ey = -Vector3.Dot(this._yAxis, eye);
  2260. var ez = -Vector3.Dot(this._zAxis, eye);
  2261. 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);
  2262. };
  2263. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2264. var matrix = Matrix.Zero();
  2265. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2266. return matrix;
  2267. };
  2268. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2269. var hw = 2.0 / width;
  2270. var hh = 2.0 / height;
  2271. var id = 1.0 / (zfar - znear);
  2272. var nid = znear / (znear - zfar);
  2273. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2274. };
  2275. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2276. var matrix = Matrix.Zero();
  2277. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2278. return matrix;
  2279. };
  2280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2281. result.m[0] = 2.0 / (right - left);
  2282. result.m[1] = result.m[2] = result.m[3] = 0;
  2283. result.m[5] = 2.0 / (top - bottom);
  2284. result.m[4] = result.m[6] = result.m[7] = 0;
  2285. result.m[10] = -1.0 / (znear - zfar);
  2286. result.m[8] = result.m[9] = result.m[11] = 0;
  2287. result.m[12] = (left + right) / (left - right);
  2288. result.m[13] = (top + bottom) / (bottom - top);
  2289. result.m[14] = znear / (znear - zfar);
  2290. result.m[15] = 1.0;
  2291. };
  2292. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2293. var matrix = Matrix.Zero();
  2294. matrix.m[0] = (2.0 * znear) / width;
  2295. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2296. matrix.m[5] = (2.0 * znear) / height;
  2297. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2298. matrix.m[10] = -zfar / (znear - zfar);
  2299. matrix.m[8] = matrix.m[9] = 0.0;
  2300. matrix.m[11] = 1.0;
  2301. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2302. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2303. return matrix;
  2304. };
  2305. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2306. var matrix = Matrix.Zero();
  2307. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2308. return matrix;
  2309. };
  2310. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2311. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2312. var tan = 1.0 / (Math.tan(fov * 0.5));
  2313. if (isVerticalFovFixed) {
  2314. result.m[0] = tan / aspect;
  2315. }
  2316. else {
  2317. result.m[0] = tan;
  2318. }
  2319. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2320. if (isVerticalFovFixed) {
  2321. result.m[5] = tan;
  2322. }
  2323. else {
  2324. result.m[5] = tan * aspect;
  2325. }
  2326. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2327. result.m[8] = result.m[9] = 0.0;
  2328. result.m[10] = -zfar / (znear - zfar);
  2329. result.m[11] = 1.0;
  2330. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2331. result.m[14] = (znear * zfar) / (znear - zfar);
  2332. };
  2333. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2334. var cw = viewport.width;
  2335. var ch = viewport.height;
  2336. var cx = viewport.x;
  2337. var cy = viewport.y;
  2338. 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);
  2339. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2340. };
  2341. Matrix.GetAsMatrix2x2 = function (matrix) {
  2342. return new Float32Array([
  2343. matrix.m[0], matrix.m[1],
  2344. matrix.m[4], matrix.m[5]
  2345. ]);
  2346. };
  2347. Matrix.GetAsMatrix3x3 = function (matrix) {
  2348. return new Float32Array([
  2349. matrix.m[0], matrix.m[1], matrix.m[2],
  2350. matrix.m[4], matrix.m[5], matrix.m[6],
  2351. matrix.m[8], matrix.m[9], matrix.m[10]
  2352. ]);
  2353. };
  2354. Matrix.Transpose = function (matrix) {
  2355. var result = new Matrix();
  2356. result.m[0] = matrix.m[0];
  2357. result.m[1] = matrix.m[4];
  2358. result.m[2] = matrix.m[8];
  2359. result.m[3] = matrix.m[12];
  2360. result.m[4] = matrix.m[1];
  2361. result.m[5] = matrix.m[5];
  2362. result.m[6] = matrix.m[9];
  2363. result.m[7] = matrix.m[13];
  2364. result.m[8] = matrix.m[2];
  2365. result.m[9] = matrix.m[6];
  2366. result.m[10] = matrix.m[10];
  2367. result.m[11] = matrix.m[14];
  2368. result.m[12] = matrix.m[3];
  2369. result.m[13] = matrix.m[7];
  2370. result.m[14] = matrix.m[11];
  2371. result.m[15] = matrix.m[15];
  2372. return result;
  2373. };
  2374. Matrix.Reflection = function (plane) {
  2375. var matrix = new Matrix();
  2376. Matrix.ReflectionToRef(plane, matrix);
  2377. return matrix;
  2378. };
  2379. Matrix.ReflectionToRef = function (plane, result) {
  2380. plane.normalize();
  2381. var x = plane.normal.x;
  2382. var y = plane.normal.y;
  2383. var z = plane.normal.z;
  2384. var temp = -2 * x;
  2385. var temp2 = -2 * y;
  2386. var temp3 = -2 * z;
  2387. result.m[0] = (temp * x) + 1;
  2388. result.m[1] = temp2 * x;
  2389. result.m[2] = temp3 * x;
  2390. result.m[3] = 0.0;
  2391. result.m[4] = temp * y;
  2392. result.m[5] = (temp2 * y) + 1;
  2393. result.m[6] = temp3 * y;
  2394. result.m[7] = 0.0;
  2395. result.m[8] = temp * z;
  2396. result.m[9] = temp2 * z;
  2397. result.m[10] = (temp3 * z) + 1;
  2398. result.m[11] = 0.0;
  2399. result.m[12] = temp * plane.d;
  2400. result.m[13] = temp2 * plane.d;
  2401. result.m[14] = temp3 * plane.d;
  2402. result.m[15] = 1.0;
  2403. };
  2404. Matrix._tempQuaternion = new Quaternion();
  2405. Matrix._xAxis = Vector3.Zero();
  2406. Matrix._yAxis = Vector3.Zero();
  2407. Matrix._zAxis = Vector3.Zero();
  2408. return Matrix;
  2409. })();
  2410. BABYLON.Matrix = Matrix;
  2411. var Plane = (function () {
  2412. function Plane(a, b, c, d) {
  2413. this.normal = new Vector3(a, b, c);
  2414. this.d = d;
  2415. }
  2416. Plane.prototype.asArray = function () {
  2417. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2418. };
  2419. // Methods
  2420. Plane.prototype.clone = function () {
  2421. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2422. };
  2423. Plane.prototype.getClassName = function () {
  2424. return "Plane";
  2425. };
  2426. Plane.prototype.getHashCode = function () {
  2427. var hash = this.normal.getHashCode();
  2428. hash = (hash * 397) ^ (this.d || 0);
  2429. return hash;
  2430. };
  2431. Plane.prototype.normalize = function () {
  2432. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2433. var magnitude = 0;
  2434. if (norm !== 0) {
  2435. magnitude = 1.0 / norm;
  2436. }
  2437. this.normal.x *= magnitude;
  2438. this.normal.y *= magnitude;
  2439. this.normal.z *= magnitude;
  2440. this.d *= magnitude;
  2441. return this;
  2442. };
  2443. Plane.prototype.transform = function (transformation) {
  2444. var transposedMatrix = Matrix.Transpose(transformation);
  2445. var x = this.normal.x;
  2446. var y = this.normal.y;
  2447. var z = this.normal.z;
  2448. var d = this.d;
  2449. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2450. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2451. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2452. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2453. return new Plane(normalX, normalY, normalZ, finalD);
  2454. };
  2455. Plane.prototype.dotCoordinate = function (point) {
  2456. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2457. };
  2458. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2459. var x1 = point2.x - point1.x;
  2460. var y1 = point2.y - point1.y;
  2461. var z1 = point2.z - point1.z;
  2462. var x2 = point3.x - point1.x;
  2463. var y2 = point3.y - point1.y;
  2464. var z2 = point3.z - point1.z;
  2465. var yz = (y1 * z2) - (z1 * y2);
  2466. var xz = (z1 * x2) - (x1 * z2);
  2467. var xy = (x1 * y2) - (y1 * x2);
  2468. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2469. var invPyth;
  2470. if (pyth !== 0) {
  2471. invPyth = 1.0 / pyth;
  2472. }
  2473. else {
  2474. invPyth = 0;
  2475. }
  2476. this.normal.x = yz * invPyth;
  2477. this.normal.y = xz * invPyth;
  2478. this.normal.z = xy * invPyth;
  2479. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2480. return this;
  2481. };
  2482. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2483. var dot = Vector3.Dot(this.normal, direction);
  2484. return (dot <= epsilon);
  2485. };
  2486. Plane.prototype.signedDistanceTo = function (point) {
  2487. return Vector3.Dot(point, this.normal) + this.d;
  2488. };
  2489. // Statics
  2490. Plane.FromArray = function (array) {
  2491. return new Plane(array[0], array[1], array[2], array[3]);
  2492. };
  2493. Plane.FromPoints = function (point1, point2, point3) {
  2494. var result = new Plane(0, 0, 0, 0);
  2495. result.copyFromPoints(point1, point2, point3);
  2496. return result;
  2497. };
  2498. Plane.FromPositionAndNormal = function (origin, normal) {
  2499. var result = new Plane(0, 0, 0, 0);
  2500. normal.normalize();
  2501. result.normal = normal;
  2502. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2503. return result;
  2504. };
  2505. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2506. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2507. return Vector3.Dot(point, normal) + d;
  2508. };
  2509. return Plane;
  2510. })();
  2511. BABYLON.Plane = Plane;
  2512. var Viewport = (function () {
  2513. function Viewport(x, y, width, height) {
  2514. this.x = x;
  2515. this.y = y;
  2516. this.width = width;
  2517. this.height = height;
  2518. }
  2519. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2520. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2521. };
  2522. return Viewport;
  2523. })();
  2524. BABYLON.Viewport = Viewport;
  2525. var Frustum = (function () {
  2526. function Frustum() {
  2527. }
  2528. Frustum.GetPlanes = function (transform) {
  2529. var frustumPlanes = [];
  2530. for (var index = 0; index < 6; index++) {
  2531. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2532. }
  2533. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2534. return frustumPlanes;
  2535. };
  2536. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2537. // Near
  2538. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2539. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2540. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2541. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2542. frustumPlanes[0].normalize();
  2543. // Far
  2544. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2545. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2546. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2547. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2548. frustumPlanes[1].normalize();
  2549. // Left
  2550. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2551. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2552. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2553. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2554. frustumPlanes[2].normalize();
  2555. // Right
  2556. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2557. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2558. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2559. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2560. frustumPlanes[3].normalize();
  2561. // Top
  2562. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2563. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2564. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2565. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2566. frustumPlanes[4].normalize();
  2567. // Bottom
  2568. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2569. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2570. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2571. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2572. frustumPlanes[5].normalize();
  2573. };
  2574. return Frustum;
  2575. })();
  2576. BABYLON.Frustum = Frustum;
  2577. (function (Space) {
  2578. Space[Space["LOCAL"] = 0] = "LOCAL";
  2579. Space[Space["WORLD"] = 1] = "WORLD";
  2580. })(BABYLON.Space || (BABYLON.Space = {}));
  2581. var Space = BABYLON.Space;
  2582. var Axis = (function () {
  2583. function Axis() {
  2584. }
  2585. Axis.X = new Vector3(1, 0, 0);
  2586. Axis.Y = new Vector3(0, 1, 0);
  2587. Axis.Z = new Vector3(0, 0, 1);
  2588. return Axis;
  2589. })();
  2590. BABYLON.Axis = Axis;
  2591. ;
  2592. var BezierCurve = (function () {
  2593. function BezierCurve() {
  2594. }
  2595. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2596. // Extract X (which is equal to time here)
  2597. var f0 = 1 - 3 * x2 + 3 * x1;
  2598. var f1 = 3 * x2 - 6 * x1;
  2599. var f2 = 3 * x1;
  2600. var refinedT = t;
  2601. for (var i = 0; i < 5; i++) {
  2602. var refinedT2 = refinedT * refinedT;
  2603. var refinedT3 = refinedT2 * refinedT;
  2604. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2605. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2606. refinedT -= (x - t) * slope;
  2607. refinedT = Math.min(1, Math.max(0, refinedT));
  2608. }
  2609. // Resolve cubic bezier for the given x
  2610. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2611. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2612. Math.pow(refinedT, 3);
  2613. };
  2614. return BezierCurve;
  2615. })();
  2616. BABYLON.BezierCurve = BezierCurve;
  2617. (function (Orientation) {
  2618. Orientation[Orientation["CW"] = 0] = "CW";
  2619. Orientation[Orientation["CCW"] = 1] = "CCW";
  2620. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2621. var Orientation = BABYLON.Orientation;
  2622. var Angle = (function () {
  2623. function Angle(radians) {
  2624. var _this = this;
  2625. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2626. this.radians = function () { return _this._radians; };
  2627. this._radians = radians;
  2628. if (this._radians < 0)
  2629. this._radians += (2 * Math.PI);
  2630. }
  2631. Angle.BetweenTwoPoints = function (a, b) {
  2632. var delta = b.subtract(a);
  2633. var theta = Math.atan2(delta.y, delta.x);
  2634. return new Angle(theta);
  2635. };
  2636. Angle.FromRadians = function (radians) {
  2637. return new Angle(radians);
  2638. };
  2639. Angle.FromDegrees = function (degrees) {
  2640. return new Angle(degrees * Math.PI / 180);
  2641. };
  2642. return Angle;
  2643. })();
  2644. BABYLON.Angle = Angle;
  2645. var Arc2 = (function () {
  2646. function Arc2(startPoint, midPoint, endPoint) {
  2647. this.startPoint = startPoint;
  2648. this.midPoint = midPoint;
  2649. this.endPoint = endPoint;
  2650. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2651. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2652. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2653. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2654. 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);
  2655. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2656. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2657. var a1 = this.startAngle.degrees();
  2658. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2659. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2660. // angles correction
  2661. if (a2 - a1 > +180.0)
  2662. a2 -= 360.0;
  2663. if (a2 - a1 < -180.0)
  2664. a2 += 360.0;
  2665. if (a3 - a2 > +180.0)
  2666. a3 -= 360.0;
  2667. if (a3 - a2 < -180.0)
  2668. a3 += 360.0;
  2669. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2670. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2671. }
  2672. return Arc2;
  2673. })();
  2674. BABYLON.Arc2 = Arc2;
  2675. var Path2 = (function () {
  2676. function Path2(x, y) {
  2677. this._points = new Array();
  2678. this._length = 0;
  2679. this.closed = false;
  2680. this._points.push(new Vector2(x, y));
  2681. }
  2682. Path2.prototype.addLineTo = function (x, y) {
  2683. if (closed) {
  2684. //Tools.Error("cannot add lines to closed paths");
  2685. return this;
  2686. }
  2687. var newPoint = new Vector2(x, y);
  2688. var previousPoint = this._points[this._points.length - 1];
  2689. this._points.push(newPoint);
  2690. this._length += newPoint.subtract(previousPoint).length();
  2691. return this;
  2692. };
  2693. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2694. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2695. if (closed) {
  2696. //Tools.Error("cannot add arcs to closed paths");
  2697. return this;
  2698. }
  2699. var startPoint = this._points[this._points.length - 1];
  2700. var midPoint = new Vector2(midX, midY);
  2701. var endPoint = new Vector2(endX, endY);
  2702. var arc = new Arc2(startPoint, midPoint, endPoint);
  2703. var increment = arc.angle.radians() / numberOfSegments;
  2704. if (arc.orientation === Orientation.CW)
  2705. increment *= -1;
  2706. var currentAngle = arc.startAngle.radians() + increment;
  2707. for (var i = 0; i < numberOfSegments; i++) {
  2708. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2709. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2710. this.addLineTo(x, y);
  2711. currentAngle += increment;
  2712. }
  2713. return this;
  2714. };
  2715. Path2.prototype.close = function () {
  2716. this.closed = true;
  2717. return this;
  2718. };
  2719. Path2.prototype.length = function () {
  2720. var result = this._length;
  2721. if (!this.closed) {
  2722. var lastPoint = this._points[this._points.length - 1];
  2723. var firstPoint = this._points[0];
  2724. result += (firstPoint.subtract(lastPoint).length());
  2725. }
  2726. return result;
  2727. };
  2728. Path2.prototype.getPoints = function () {
  2729. return this._points;
  2730. };
  2731. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2732. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2733. //Tools.Error("normalized length position should be between 0 and 1.");
  2734. return Vector2.Zero();
  2735. }
  2736. var lengthPosition = normalizedLengthPosition * this.length();
  2737. var previousOffset = 0;
  2738. for (var i = 0; i < this._points.length; i++) {
  2739. var j = (i + 1) % this._points.length;
  2740. var a = this._points[i];
  2741. var b = this._points[j];
  2742. var bToA = b.subtract(a);
  2743. var nextOffset = (bToA.length() + previousOffset);
  2744. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2745. var dir = bToA.normalize();
  2746. var localOffset = lengthPosition - previousOffset;
  2747. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2748. }
  2749. previousOffset = nextOffset;
  2750. }
  2751. //Tools.Error("internal error");
  2752. return Vector2.Zero();
  2753. };
  2754. Path2.StartingAt = function (x, y) {
  2755. return new Path2(x, y);
  2756. };
  2757. return Path2;
  2758. })();
  2759. BABYLON.Path2 = Path2;
  2760. var Path3D = (function () {
  2761. /**
  2762. * new Path3D(path, normal, raw)
  2763. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2764. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2765. * path : an array of Vector3, the curve axis of the Path3D
  2766. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2767. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2768. */
  2769. function Path3D(path, firstNormal, raw) {
  2770. this.path = path;
  2771. this._curve = new Array();
  2772. this._distances = new Array();
  2773. this._tangents = new Array();
  2774. this._normals = new Array();
  2775. this._binormals = new Array();
  2776. for (var p = 0; p < path.length; p++) {
  2777. this._curve[p] = path[p].clone(); // hard copy
  2778. }
  2779. this._raw = raw || false;
  2780. this._compute(firstNormal);
  2781. }
  2782. /**
  2783. * Returns the Path3D array of successive Vector3 designing its curve.
  2784. */
  2785. Path3D.prototype.getCurve = function () {
  2786. return this._curve;
  2787. };
  2788. /**
  2789. * Returns an array populated with tangent vectors on each Path3D curve point.
  2790. */
  2791. Path3D.prototype.getTangents = function () {
  2792. return this._tangents;
  2793. };
  2794. /**
  2795. * Returns an array populated with normal vectors on each Path3D curve point.
  2796. */
  2797. Path3D.prototype.getNormals = function () {
  2798. return this._normals;
  2799. };
  2800. /**
  2801. * Returns an array populated with binormal vectors on each Path3D curve point.
  2802. */
  2803. Path3D.prototype.getBinormals = function () {
  2804. return this._binormals;
  2805. };
  2806. /**
  2807. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2808. */
  2809. Path3D.prototype.getDistances = function () {
  2810. return this._distances;
  2811. };
  2812. /**
  2813. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2814. * Returns the same object updated.
  2815. */
  2816. Path3D.prototype.update = function (path, firstNormal) {
  2817. for (var p = 0; p < path.length; p++) {
  2818. this._curve[p].x = path[p].x;
  2819. this._curve[p].y = path[p].y;
  2820. this._curve[p].z = path[p].z;
  2821. }
  2822. this._compute(firstNormal);
  2823. return this;
  2824. };
  2825. // private function compute() : computes tangents, normals and binormals
  2826. Path3D.prototype._compute = function (firstNormal) {
  2827. var l = this._curve.length;
  2828. // first and last tangents
  2829. this._tangents[0] = this._getFirstNonNullVector(0);
  2830. if (!this._raw) {
  2831. this._tangents[0].normalize();
  2832. }
  2833. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2834. if (!this._raw) {
  2835. this._tangents[l - 1].normalize();
  2836. }
  2837. // normals and binormals at first point : arbitrary vector with _normalVector()
  2838. var tg0 = this._tangents[0];
  2839. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2840. this._normals[0] = pp0;
  2841. if (!this._raw) {
  2842. this._normals[0].normalize();
  2843. }
  2844. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2845. if (!this._raw) {
  2846. this._binormals[0].normalize();
  2847. }
  2848. this._distances[0] = 0;
  2849. // normals and binormals : next points
  2850. var prev; // previous vector (segment)
  2851. var cur; // current vector (segment)
  2852. var curTang; // current tangent
  2853. // previous normal
  2854. var prevBinor; // previous binormal
  2855. for (var i = 1; i < l; i++) {
  2856. // tangents
  2857. prev = this._getLastNonNullVector(i);
  2858. if (i < l - 1) {
  2859. cur = this._getFirstNonNullVector(i);
  2860. this._tangents[i] = prev.add(cur);
  2861. this._tangents[i].normalize();
  2862. }
  2863. this._distances[i] = this._distances[i - 1] + prev.length();
  2864. // normals and binormals
  2865. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2866. curTang = this._tangents[i];
  2867. prevBinor = this._binormals[i - 1];
  2868. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2869. if (!this._raw) {
  2870. this._normals[i].normalize();
  2871. }
  2872. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2873. if (!this._raw) {
  2874. this._binormals[i].normalize();
  2875. }
  2876. }
  2877. };
  2878. // private function getFirstNonNullVector(index)
  2879. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2880. Path3D.prototype._getFirstNonNullVector = function (index) {
  2881. var i = 1;
  2882. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2883. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2884. i++;
  2885. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2886. }
  2887. return nNVector;
  2888. };
  2889. // private function getLastNonNullVector(index)
  2890. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2891. Path3D.prototype._getLastNonNullVector = function (index) {
  2892. var i = 1;
  2893. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2894. while (nLVector.length() === 0 && index > i + 1) {
  2895. i++;
  2896. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2897. }
  2898. return nLVector;
  2899. };
  2900. // private function normalVector(v0, vt, va) :
  2901. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2902. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2903. Path3D.prototype._normalVector = function (v0, vt, va) {
  2904. var normal0;
  2905. if (va === undefined || va === null) {
  2906. var point;
  2907. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2908. point = new Vector3(0, -1, 0);
  2909. }
  2910. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2911. point = new Vector3(1, 0, 0);
  2912. }
  2913. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2914. point = new Vector3(0, 0, 1);
  2915. }
  2916. normal0 = Vector3.Cross(vt, point);
  2917. }
  2918. else {
  2919. normal0 = Vector3.Cross(vt, va);
  2920. Vector3.CrossToRef(normal0, vt, normal0);
  2921. }
  2922. normal0.normalize();
  2923. return normal0;
  2924. };
  2925. return Path3D;
  2926. })();
  2927. BABYLON.Path3D = Path3D;
  2928. var Curve3 = (function () {
  2929. /**
  2930. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2931. * A Curve3 is designed from a series of successive Vector3.
  2932. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2933. */
  2934. function Curve3(points) {
  2935. this._length = 0;
  2936. this._points = points;
  2937. this._length = this._computeLength(points);
  2938. }
  2939. /**
  2940. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2941. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2942. * @param v1 (Vector3) the control point
  2943. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2944. * @param nbPoints (integer) the wanted number of points in the curve
  2945. */
  2946. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2947. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2948. var bez = new Array();
  2949. var equation = function (t, val0, val1, val2) {
  2950. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  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), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2955. }
  2956. return new Curve3(bez);
  2957. };
  2958. /**
  2959. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2960. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2961. * @param v1 (Vector3) the first control point
  2962. * @param v2 (Vector3) the second control point
  2963. * @param v3 (Vector3) the end point of the Cubic Bezier
  2964. * @param nbPoints (integer) the wanted number of points in the curve
  2965. */
  2966. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2967. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2968. var bez = new Array();
  2969. var equation = function (t, val0, val1, val2, val3) {
  2970. 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;
  2971. return res;
  2972. };
  2973. for (var i = 0; i <= nbPoints; i++) {
  2974. 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)));
  2975. }
  2976. return new Curve3(bez);
  2977. };
  2978. /**
  2979. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2980. * @param p1 (Vector3) the origin point of the Hermite Spline
  2981. * @param t1 (Vector3) the tangent vector at the origin point
  2982. * @param p2 (Vector3) the end point of the Hermite Spline
  2983. * @param t2 (Vector3) the tangent vector at the end point
  2984. * @param nbPoints (integer) the wanted number of points in the curve
  2985. */
  2986. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2987. var hermite = new Array();
  2988. var step = 1 / nbPoints;
  2989. for (var i = 0; i <= nbPoints; i++) {
  2990. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2991. }
  2992. return new Curve3(hermite);
  2993. };
  2994. /**
  2995. * Returns the Curve3 stored array of successive Vector3
  2996. */
  2997. Curve3.prototype.getPoints = function () {
  2998. return this._points;
  2999. };
  3000. /**
  3001. * Returns the computed length (float) of the curve.
  3002. */
  3003. Curve3.prototype.length = function () {
  3004. return this._length;
  3005. };
  3006. /**
  3007. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3008. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3009. * curveA and curveB keep unchanged.
  3010. */
  3011. Curve3.prototype.continue = function (curve) {
  3012. var lastPoint = this._points[this._points.length - 1];
  3013. var continuedPoints = this._points.slice();
  3014. var curvePoints = curve.getPoints();
  3015. for (var i = 1; i < curvePoints.length; i++) {
  3016. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3017. }
  3018. var continuedCurve = new Curve3(continuedPoints);
  3019. return continuedCurve;
  3020. };
  3021. Curve3.prototype._computeLength = function (path) {
  3022. var l = 0;
  3023. for (var i = 1; i < path.length; i++) {
  3024. l += (path[i].subtract(path[i - 1])).length();
  3025. }
  3026. return l;
  3027. };
  3028. return Curve3;
  3029. })();
  3030. BABYLON.Curve3 = Curve3;
  3031. // SphericalHarmonics
  3032. var SphericalHarmonics = (function () {
  3033. function SphericalHarmonics() {
  3034. this.L00 = Vector3.Zero();
  3035. this.L1_1 = Vector3.Zero();
  3036. this.L10 = Vector3.Zero();
  3037. this.L11 = Vector3.Zero();
  3038. this.L2_2 = Vector3.Zero();
  3039. this.L2_1 = Vector3.Zero();
  3040. this.L20 = Vector3.Zero();
  3041. this.L21 = Vector3.Zero();
  3042. this.L22 = Vector3.Zero();
  3043. }
  3044. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3045. var colorVector = new Vector3(color.r, color.g, color.b);
  3046. var c = colorVector.scale(deltaSolidAngle);
  3047. this.L00 = this.L00.add(c.scale(0.282095));
  3048. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3049. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3050. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3051. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3052. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3053. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3054. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3055. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3056. };
  3057. SphericalHarmonics.prototype.scale = function (scale) {
  3058. this.L00 = this.L00.scale(scale);
  3059. this.L1_1 = this.L1_1.scale(scale);
  3060. this.L10 = this.L10.scale(scale);
  3061. this.L11 = this.L11.scale(scale);
  3062. this.L2_2 = this.L2_2.scale(scale);
  3063. this.L2_1 = this.L2_1.scale(scale);
  3064. this.L20 = this.L20.scale(scale);
  3065. this.L21 = this.L21.scale(scale);
  3066. this.L22 = this.L22.scale(scale);
  3067. };
  3068. return SphericalHarmonics;
  3069. })();
  3070. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3071. // SphericalPolynomial
  3072. var SphericalPolynomial = (function () {
  3073. function SphericalPolynomial() {
  3074. this.x = Vector3.Zero();
  3075. this.y = Vector3.Zero();
  3076. this.z = Vector3.Zero();
  3077. this.xx = Vector3.Zero();
  3078. this.yy = Vector3.Zero();
  3079. this.zz = Vector3.Zero();
  3080. this.xy = Vector3.Zero();
  3081. this.yz = Vector3.Zero();
  3082. this.zx = Vector3.Zero();
  3083. }
  3084. SphericalPolynomial.prototype.addAmbient = function (color) {
  3085. var colorVector = new Vector3(color.r, color.g, color.b);
  3086. this.xx = this.xx.add(colorVector);
  3087. this.yy = this.yy.add(colorVector);
  3088. this.zz = this.zz.add(colorVector);
  3089. };
  3090. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3091. var result = new SphericalPolynomial();
  3092. result.x = harmonics.L11.scale(1.02333);
  3093. result.y = harmonics.L1_1.scale(1.02333);
  3094. result.z = harmonics.L10.scale(1.02333);
  3095. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3096. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3097. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3098. result.yz = harmonics.L2_1.scale(0.858086);
  3099. result.zx = harmonics.L21.scale(0.858086);
  3100. result.xy = harmonics.L2_2.scale(0.858086);
  3101. return result;
  3102. };
  3103. return SphericalPolynomial;
  3104. })();
  3105. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3106. // Vertex formats
  3107. var PositionNormalVertex = (function () {
  3108. function PositionNormalVertex(position, normal) {
  3109. if (position === void 0) { position = Vector3.Zero(); }
  3110. if (normal === void 0) { normal = Vector3.Up(); }
  3111. this.position = position;
  3112. this.normal = normal;
  3113. }
  3114. PositionNormalVertex.prototype.clone = function () {
  3115. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3116. };
  3117. return PositionNormalVertex;
  3118. })();
  3119. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3120. var PositionNormalTextureVertex = (function () {
  3121. function PositionNormalTextureVertex(position, normal, uv) {
  3122. if (position === void 0) { position = Vector3.Zero(); }
  3123. if (normal === void 0) { normal = Vector3.Up(); }
  3124. if (uv === void 0) { uv = Vector2.Zero(); }
  3125. this.position = position;
  3126. this.normal = normal;
  3127. this.uv = uv;
  3128. }
  3129. PositionNormalTextureVertex.prototype.clone = function () {
  3130. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3131. };
  3132. return PositionNormalTextureVertex;
  3133. })();
  3134. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3135. // Temporary pre-allocated objects for engine internal use
  3136. // usage in any internal function :
  3137. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3138. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3139. var Tmp = (function () {
  3140. function Tmp() {
  3141. }
  3142. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3143. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3144. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3145. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3146. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3147. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3148. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3149. Matrix.Zero(), Matrix.Zero(),
  3150. Matrix.Zero(), Matrix.Zero(),
  3151. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3152. return Tmp;
  3153. })();
  3154. BABYLON.Tmp = Tmp;
  3155. })(BABYLON || (BABYLON = {}));
  3156. var BABYLON;
  3157. (function (BABYLON) {
  3158. function generateSerializableMember(type, sourceName) {
  3159. return function (target, propertyKey) {
  3160. if (!target.__serializableMembers) {
  3161. target.__serializableMembers = {};
  3162. }
  3163. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3164. };
  3165. }
  3166. function serialize(sourceName) {
  3167. return generateSerializableMember(0, sourceName); // value member
  3168. }
  3169. BABYLON.serialize = serialize;
  3170. function serializeAsTexture(sourceName) {
  3171. return generateSerializableMember(1, sourceName); // texture member
  3172. }
  3173. BABYLON.serializeAsTexture = serializeAsTexture;
  3174. function serializeAsColor3(sourceName) {
  3175. return generateSerializableMember(2, sourceName); // color3 member
  3176. }
  3177. BABYLON.serializeAsColor3 = serializeAsColor3;
  3178. function serializeAsFresnelParameters(sourceName) {
  3179. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3180. }
  3181. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3182. function serializeAsVector2(sourceName) {
  3183. return generateSerializableMember(4, sourceName); // vector2 member
  3184. }
  3185. BABYLON.serializeAsVector2 = serializeAsVector2;
  3186. function serializeAsVector3(sourceName) {
  3187. return generateSerializableMember(5, sourceName); // vector3 member
  3188. }
  3189. BABYLON.serializeAsVector3 = serializeAsVector3;
  3190. function serializeAsMeshReference(sourceName) {
  3191. return generateSerializableMember(6, sourceName); // mesh reference member
  3192. }
  3193. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3194. function serializeAsColorCurves(sourceName) {
  3195. return generateSerializableMember(7, sourceName); // color curves
  3196. }
  3197. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3198. var SerializationHelper = (function () {
  3199. function SerializationHelper() {
  3200. }
  3201. SerializationHelper.Serialize = function (entity, serializationObject) {
  3202. if (!serializationObject) {
  3203. serializationObject = {};
  3204. }
  3205. // Tags
  3206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3207. // Properties
  3208. for (var property in entity.__serializableMembers) {
  3209. var propertyDescriptor = entity.__serializableMembers[property];
  3210. var targetPropertyName = propertyDescriptor.sourceName || property;
  3211. var propertyType = propertyDescriptor.type;
  3212. var sourceProperty = entity[property];
  3213. if (sourceProperty !== undefined && sourceProperty !== null) {
  3214. switch (propertyType) {
  3215. case 0:
  3216. serializationObject[targetPropertyName] = sourceProperty;
  3217. break;
  3218. case 1:
  3219. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3220. break;
  3221. case 2:
  3222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3223. break;
  3224. case 3:
  3225. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3226. break;
  3227. case 4:
  3228. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3229. break;
  3230. case 5:
  3231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3232. break;
  3233. case 6:
  3234. serializationObject[targetPropertyName] = sourceProperty.id;
  3235. break;
  3236. case 7:
  3237. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3238. break;
  3239. }
  3240. }
  3241. }
  3242. return serializationObject;
  3243. };
  3244. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3245. var destination = creationFunction();
  3246. // Tags
  3247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3248. // Properties
  3249. for (var property in destination.__serializableMembers) {
  3250. var propertyDescriptor = destination.__serializableMembers[property];
  3251. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3252. var propertyType = propertyDescriptor.type;
  3253. if (sourceProperty !== undefined && sourceProperty !== null) {
  3254. switch (propertyType) {
  3255. case 0:
  3256. destination[property] = sourceProperty;
  3257. break;
  3258. case 1:
  3259. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3260. break;
  3261. case 2:
  3262. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3263. break;
  3264. case 3:
  3265. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3266. break;
  3267. case 4:
  3268. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3269. break;
  3270. case 5:
  3271. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3272. break;
  3273. case 6:
  3274. destination[property] = scene.getLastMeshByID(sourceProperty);
  3275. break;
  3276. case 7:
  3277. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3278. break;
  3279. }
  3280. }
  3281. }
  3282. return destination;
  3283. };
  3284. SerializationHelper.Clone = function (creationFunction, source) {
  3285. var destination = creationFunction();
  3286. // Tags
  3287. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3288. // Properties
  3289. for (var property in destination.__serializableMembers) {
  3290. var propertyDescriptor = destination.__serializableMembers[property];
  3291. var sourceProperty = source[property];
  3292. var propertyType = propertyDescriptor.type;
  3293. if (sourceProperty !== undefined && sourceProperty !== null) {
  3294. switch (propertyType) {
  3295. case 0: // Value
  3296. case 6:
  3297. destination[property] = sourceProperty;
  3298. break;
  3299. case 1: // Texture
  3300. case 2: // Color3
  3301. case 3: // FresnelParameters
  3302. case 4: // Vector2
  3303. case 5: // Vector3
  3304. case 7:
  3305. destination[property] = sourceProperty.clone();
  3306. break;
  3307. }
  3308. }
  3309. }
  3310. return destination;
  3311. };
  3312. return SerializationHelper;
  3313. })();
  3314. BABYLON.SerializationHelper = SerializationHelper;
  3315. })(BABYLON || (BABYLON = {}));
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. /**
  3319. * A class serves as a medium between the observable and its observers
  3320. */
  3321. var EventState = (function () {
  3322. /**
  3323. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3324. */
  3325. function EventState(mask, skipNextObservers) {
  3326. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3327. this.initalize(mask, skipNextObservers);
  3328. }
  3329. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3330. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3331. this.mask = mask;
  3332. this.skipNextObservers = skipNextObservers;
  3333. return this;
  3334. };
  3335. return EventState;
  3336. })();
  3337. BABYLON.EventState = EventState;
  3338. /**
  3339. * Represent an Observer registered to a given Observable object.
  3340. */
  3341. var Observer = (function () {
  3342. function Observer(callback, mask) {
  3343. this.callback = callback;
  3344. this.mask = mask;
  3345. }
  3346. return Observer;
  3347. })();
  3348. BABYLON.Observer = Observer;
  3349. /**
  3350. * The Observable class is a simple implementation of the Observable pattern.
  3351. * 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.
  3352. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3353. * 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).
  3354. * 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.
  3355. */
  3356. var Observable = (function () {
  3357. function Observable() {
  3358. this._observers = new Array();
  3359. }
  3360. /**
  3361. * Create a new Observer with the specified callback
  3362. * @param callback the callback that will be executed for that Observer
  3363. * @param mask the mask used to filter observers
  3364. * @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.
  3365. */
  3366. Observable.prototype.add = function (callback, mask, insertFirst) {
  3367. if (mask === void 0) { mask = -1; }
  3368. if (insertFirst === void 0) { insertFirst = false; }
  3369. if (!callback) {
  3370. return null;
  3371. }
  3372. var observer = new Observer(callback, mask);
  3373. if (insertFirst) {
  3374. this._observers.unshift(observer);
  3375. }
  3376. else {
  3377. this._observers.push(observer);
  3378. }
  3379. return observer;
  3380. };
  3381. /**
  3382. * Remove an Observer from the Observable object
  3383. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3384. */
  3385. Observable.prototype.remove = function (observer) {
  3386. var index = this._observers.indexOf(observer);
  3387. if (index !== -1) {
  3388. this._observers.splice(index, 1);
  3389. return true;
  3390. }
  3391. return false;
  3392. };
  3393. /**
  3394. * Remove a callback from the Observable object
  3395. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3396. */
  3397. Observable.prototype.removeCallback = function (callback) {
  3398. for (var index = 0; index < this._observers.length; index++) {
  3399. if (this._observers[index].callback === callback) {
  3400. this._observers.splice(index, 1);
  3401. return true;
  3402. }
  3403. }
  3404. return false;
  3405. };
  3406. /**
  3407. * Notify all Observers by calling their respective callback with the given data
  3408. * @param eventData
  3409. * @param mask
  3410. */
  3411. Observable.prototype.notifyObservers = function (eventData, mask) {
  3412. if (mask === void 0) { mask = -1; }
  3413. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3414. Observable._pooledEventState = null;
  3415. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3416. var obs = _a[_i];
  3417. if (obs.mask & mask) {
  3418. obs.callback(eventData, state);
  3419. }
  3420. if (state.skipNextObservers) {
  3421. break;
  3422. }
  3423. }
  3424. Observable._pooledEventState = state;
  3425. };
  3426. /**
  3427. * return true is the Observable has at least one Observer registered
  3428. */
  3429. Observable.prototype.hasObservers = function () {
  3430. return this._observers.length > 0;
  3431. };
  3432. /**
  3433. * Clear the list of observers
  3434. */
  3435. Observable.prototype.clear = function () {
  3436. this._observers = new Array();
  3437. };
  3438. /**
  3439. * Clone the current observable
  3440. */
  3441. Observable.prototype.clone = function () {
  3442. var result = new Observable();
  3443. result._observers = this._observers.slice(0);
  3444. return result;
  3445. };
  3446. Observable._pooledEventState = null;
  3447. return Observable;
  3448. })();
  3449. BABYLON.Observable = Observable;
  3450. })(BABYLON || (BABYLON = {}));
  3451. var BABYLON;
  3452. (function (BABYLON) {
  3453. var Database = (function () {
  3454. function Database(urlToScene, callbackManifestChecked) {
  3455. // Handling various flavors of prefixed version of IndexedDB
  3456. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3457. this.callbackManifestChecked = callbackManifestChecked;
  3458. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3459. this.db = null;
  3460. this.enableSceneOffline = false;
  3461. this.enableTexturesOffline = false;
  3462. this.manifestVersionFound = 0;
  3463. this.mustUpdateRessources = false;
  3464. this.hasReachedQuota = false;
  3465. if (!Database.IDBStorageEnabled) {
  3466. this.callbackManifestChecked(true);
  3467. }
  3468. else {
  3469. this.checkManifestFile();
  3470. }
  3471. }
  3472. Database.prototype.checkManifestFile = function () {
  3473. var _this = this;
  3474. function noManifestFile() {
  3475. that.enableSceneOffline = false;
  3476. that.enableTexturesOffline = false;
  3477. that.callbackManifestChecked(false);
  3478. }
  3479. var that = this;
  3480. var timeStampUsed = false;
  3481. var manifestURL = this.currentSceneUrl + ".manifest";
  3482. var xhr = new XMLHttpRequest();
  3483. if (navigator.onLine) {
  3484. // Adding a timestamp to by-pass browsers' cache
  3485. timeStampUsed = true;
  3486. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3487. }
  3488. xhr.open("GET", manifestURL, true);
  3489. xhr.addEventListener("load", function () {
  3490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3491. try {
  3492. var manifestFile = JSON.parse(xhr.response);
  3493. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3494. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3496. _this.manifestVersionFound = manifestFile.version;
  3497. }
  3498. if (_this.callbackManifestChecked) {
  3499. _this.callbackManifestChecked(true);
  3500. }
  3501. }
  3502. catch (ex) {
  3503. noManifestFile();
  3504. }
  3505. }
  3506. else {
  3507. noManifestFile();
  3508. }
  3509. }, false);
  3510. xhr.addEventListener("error", function (event) {
  3511. if (timeStampUsed) {
  3512. timeStampUsed = false;
  3513. // Let's retry without the timeStamp
  3514. // It could fail when coupled with HTML5 Offline API
  3515. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3516. xhr.open("GET", retryManifestURL, true);
  3517. xhr.send();
  3518. }
  3519. else {
  3520. noManifestFile();
  3521. }
  3522. }, false);
  3523. try {
  3524. xhr.send();
  3525. }
  3526. catch (ex) {
  3527. BABYLON.Tools.Error("Error on XHR send request.");
  3528. that.callbackManifestChecked(false);
  3529. }
  3530. };
  3531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3532. var _this = this;
  3533. function handleError() {
  3534. that.isSupported = false;
  3535. if (errorCallback)
  3536. errorCallback();
  3537. }
  3538. var that = this;
  3539. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3540. // Your browser doesn't support IndexedDB
  3541. this.isSupported = false;
  3542. if (errorCallback)
  3543. errorCallback();
  3544. }
  3545. else {
  3546. // If the DB hasn't been opened or created yet
  3547. if (!this.db) {
  3548. this.hasReachedQuota = false;
  3549. this.isSupported = true;
  3550. var request = this.idbFactory.open("babylonjs", 1);
  3551. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3552. request.onerror = function (event) {
  3553. handleError();
  3554. };
  3555. // executes when a version change transaction cannot complete due to other active transactions
  3556. request.onblocked = function (event) {
  3557. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3558. handleError();
  3559. };
  3560. // DB has been opened successfully
  3561. request.onsuccess = function (event) {
  3562. _this.db = request.result;
  3563. successCallback();
  3564. };
  3565. // Initialization of the DB. Creating Scenes & Textures stores
  3566. request.onupgradeneeded = function (event) {
  3567. _this.db = (event.target).result;
  3568. try {
  3569. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3570. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3571. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3572. }
  3573. catch (ex) {
  3574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3575. handleError();
  3576. }
  3577. };
  3578. }
  3579. else {
  3580. if (successCallback)
  3581. successCallback();
  3582. }
  3583. }
  3584. };
  3585. Database.prototype.loadImageFromDB = function (url, image) {
  3586. var _this = this;
  3587. var completeURL = Database.ReturnFullUrlLocation(url);
  3588. var saveAndLoadImage = function () {
  3589. if (!_this.hasReachedQuota && _this.db !== null) {
  3590. // the texture is not yet in the DB, let's try to save it
  3591. _this._saveImageIntoDBAsync(completeURL, image);
  3592. }
  3593. else {
  3594. image.src = url;
  3595. }
  3596. };
  3597. if (!this.mustUpdateRessources) {
  3598. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3599. }
  3600. else {
  3601. saveAndLoadImage();
  3602. }
  3603. };
  3604. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3605. if (this.isSupported && this.db !== null) {
  3606. var texture;
  3607. var transaction = this.db.transaction(["textures"]);
  3608. transaction.onabort = function (event) {
  3609. image.src = url;
  3610. };
  3611. transaction.oncomplete = function (event) {
  3612. var blobTextureURL;
  3613. if (texture) {
  3614. var URL = window.URL || window.webkitURL;
  3615. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3616. image.onerror = function () {
  3617. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3618. image.src = url;
  3619. };
  3620. image.src = blobTextureURL;
  3621. }
  3622. else {
  3623. notInDBCallback();
  3624. }
  3625. };
  3626. var getRequest = transaction.objectStore("textures").get(url);
  3627. getRequest.onsuccess = function (event) {
  3628. texture = (event.target).result;
  3629. };
  3630. getRequest.onerror = function (event) {
  3631. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3632. image.src = url;
  3633. };
  3634. }
  3635. else {
  3636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3637. image.src = url;
  3638. }
  3639. };
  3640. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3641. var _this = this;
  3642. if (this.isSupported) {
  3643. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3644. var generateBlobUrl = function () {
  3645. var blobTextureURL;
  3646. if (blob) {
  3647. var URL = window.URL || window.webkitURL;
  3648. try {
  3649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3650. }
  3651. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3652. catch (ex) {
  3653. blobTextureURL = URL.createObjectURL(blob);
  3654. }
  3655. }
  3656. image.src = blobTextureURL;
  3657. };
  3658. if (Database.IsUASupportingBlobStorage) {
  3659. var xhr = new XMLHttpRequest(), blob;
  3660. xhr.open("GET", url, true);
  3661. xhr.responseType = "blob";
  3662. xhr.addEventListener("load", function () {
  3663. if (xhr.status === 200) {
  3664. // Blob as response (XHR2)
  3665. blob = xhr.response;
  3666. var transaction = _this.db.transaction(["textures"], "readwrite");
  3667. // the transaction could abort because of a QuotaExceededError error
  3668. transaction.onabort = function (event) {
  3669. try {
  3670. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3671. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3672. this.hasReachedQuota = true;
  3673. }
  3674. }
  3675. catch (ex) { }
  3676. generateBlobUrl();
  3677. };
  3678. transaction.oncomplete = function (event) {
  3679. generateBlobUrl();
  3680. };
  3681. var newTexture = { textureUrl: url, data: blob };
  3682. try {
  3683. // Put the blob into the dabase
  3684. var addRequest = transaction.objectStore("textures").put(newTexture);
  3685. addRequest.onsuccess = function (event) {
  3686. };
  3687. addRequest.onerror = function (event) {
  3688. generateBlobUrl();
  3689. };
  3690. }
  3691. catch (ex) {
  3692. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3693. if (ex.code === 25) {
  3694. Database.IsUASupportingBlobStorage = false;
  3695. }
  3696. image.src = url;
  3697. }
  3698. }
  3699. else {
  3700. image.src = url;
  3701. }
  3702. }, false);
  3703. xhr.addEventListener("error", function (event) {
  3704. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3705. image.src = url;
  3706. }, false);
  3707. xhr.send();
  3708. }
  3709. else {
  3710. image.src = url;
  3711. }
  3712. }
  3713. else {
  3714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3715. image.src = url;
  3716. }
  3717. };
  3718. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3719. var _this = this;
  3720. var updateVersion = function (event) {
  3721. // the version is not yet in the DB or we need to update it
  3722. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3723. };
  3724. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3725. };
  3726. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3727. var _this = this;
  3728. if (this.isSupported) {
  3729. var version;
  3730. try {
  3731. var transaction = this.db.transaction(["versions"]);
  3732. transaction.oncomplete = function (event) {
  3733. if (version) {
  3734. // If the version in the JSON file is > than the version in DB
  3735. if (_this.manifestVersionFound > version.data) {
  3736. _this.mustUpdateRessources = true;
  3737. updateInDBCallback();
  3738. }
  3739. else {
  3740. callback(version.data);
  3741. }
  3742. }
  3743. else {
  3744. _this.mustUpdateRessources = true;
  3745. updateInDBCallback();
  3746. }
  3747. };
  3748. transaction.onabort = function (event) {
  3749. callback(-1);
  3750. };
  3751. var getRequest = transaction.objectStore("versions").get(url);
  3752. getRequest.onsuccess = function (event) {
  3753. version = (event.target).result;
  3754. };
  3755. getRequest.onerror = function (event) {
  3756. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3757. callback(-1);
  3758. };
  3759. }
  3760. catch (ex) {
  3761. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3762. callback(-1);
  3763. }
  3764. }
  3765. else {
  3766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3767. callback(-1);
  3768. }
  3769. };
  3770. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3771. var _this = this;
  3772. if (this.isSupported && !this.hasReachedQuota) {
  3773. try {
  3774. // Open a transaction to the database
  3775. var transaction = this.db.transaction(["versions"], "readwrite");
  3776. // the transaction could abort because of a QuotaExceededError error
  3777. transaction.onabort = function (event) {
  3778. try {
  3779. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3780. _this.hasReachedQuota = true;
  3781. }
  3782. }
  3783. catch (ex) { }
  3784. callback(-1);
  3785. };
  3786. transaction.oncomplete = function (event) {
  3787. callback(_this.manifestVersionFound);
  3788. };
  3789. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3790. // Put the scene into the database
  3791. var addRequest = transaction.objectStore("versions").put(newVersion);
  3792. addRequest.onsuccess = function (event) {
  3793. };
  3794. addRequest.onerror = function (event) {
  3795. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3796. };
  3797. }
  3798. catch (ex) {
  3799. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3800. callback(-1);
  3801. }
  3802. }
  3803. else {
  3804. callback(-1);
  3805. }
  3806. };
  3807. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3808. var _this = this;
  3809. var completeUrl = Database.ReturnFullUrlLocation(url);
  3810. var saveAndLoadFile = function (event) {
  3811. // the scene is not yet in the DB, let's try to save it
  3812. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3813. };
  3814. this._checkVersionFromDB(completeUrl, function (version) {
  3815. if (version !== -1) {
  3816. if (!_this.mustUpdateRessources) {
  3817. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3818. }
  3819. else {
  3820. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3821. }
  3822. }
  3823. else {
  3824. errorCallback();
  3825. }
  3826. });
  3827. };
  3828. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3829. if (this.isSupported) {
  3830. var targetStore;
  3831. if (url.indexOf(".babylon") !== -1) {
  3832. targetStore = "scenes";
  3833. }
  3834. else {
  3835. targetStore = "textures";
  3836. }
  3837. var file;
  3838. var transaction = this.db.transaction([targetStore]);
  3839. transaction.oncomplete = function (event) {
  3840. if (file) {
  3841. callback(file.data);
  3842. }
  3843. else {
  3844. notInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. notInDBCallback();
  3849. };
  3850. var getRequest = transaction.objectStore(targetStore).get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. file = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3856. notInDBCallback();
  3857. };
  3858. }
  3859. else {
  3860. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3861. callback();
  3862. }
  3863. };
  3864. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3865. var _this = this;
  3866. if (this.isSupported) {
  3867. var targetStore;
  3868. if (url.indexOf(".babylon") !== -1) {
  3869. targetStore = "scenes";
  3870. }
  3871. else {
  3872. targetStore = "textures";
  3873. }
  3874. // Create XHR
  3875. var xhr = new XMLHttpRequest(), fileData;
  3876. xhr.open("GET", url, true);
  3877. if (useArrayBuffer) {
  3878. xhr.responseType = "arraybuffer";
  3879. }
  3880. xhr.onprogress = progressCallback;
  3881. xhr.addEventListener("load", function () {
  3882. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3883. // Blob as response (XHR2)
  3884. //fileData = xhr.responseText;
  3885. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3886. if (!_this.hasReachedQuota) {
  3887. // Open a transaction to the database
  3888. var transaction = _this.db.transaction([targetStore], "readwrite");
  3889. // the transaction could abort because of a QuotaExceededError error
  3890. transaction.onabort = function (event) {
  3891. try {
  3892. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3893. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3894. this.hasReachedQuota = true;
  3895. }
  3896. }
  3897. catch (ex) { }
  3898. callback(fileData);
  3899. };
  3900. transaction.oncomplete = function (event) {
  3901. callback(fileData);
  3902. };
  3903. var newFile;
  3904. if (targetStore === "scenes") {
  3905. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3906. }
  3907. else {
  3908. newFile = { textureUrl: url, data: fileData };
  3909. }
  3910. try {
  3911. // Put the scene into the database
  3912. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3913. addRequest.onsuccess = function (event) {
  3914. };
  3915. addRequest.onerror = function (event) {
  3916. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3917. };
  3918. }
  3919. catch (ex) {
  3920. callback(fileData);
  3921. }
  3922. }
  3923. else {
  3924. callback(fileData);
  3925. }
  3926. }
  3927. else {
  3928. callback();
  3929. }
  3930. }, false);
  3931. xhr.addEventListener("error", function (event) {
  3932. BABYLON.Tools.Error("error on XHR request.");
  3933. callback();
  3934. }, false);
  3935. xhr.send();
  3936. }
  3937. else {
  3938. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3939. callback();
  3940. }
  3941. };
  3942. Database.IsUASupportingBlobStorage = true;
  3943. Database.IDBStorageEnabled = true;
  3944. Database.parseURL = function (url) {
  3945. var a = document.createElement('a');
  3946. a.href = url;
  3947. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3948. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3949. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3950. return absLocation;
  3951. };
  3952. Database.ReturnFullUrlLocation = function (url) {
  3953. if (url.indexOf("http:/") === -1) {
  3954. return (Database.parseURL(window.location.href) + url);
  3955. }
  3956. else {
  3957. return url;
  3958. }
  3959. };
  3960. return Database;
  3961. })();
  3962. BABYLON.Database = Database;
  3963. })(BABYLON || (BABYLON = {}));
  3964. var BABYLON;
  3965. (function (BABYLON) {
  3966. var Internals;
  3967. (function (Internals) {
  3968. /*
  3969. * Based on jsTGALoader - Javascript loader for TGA file
  3970. * By Vincent Thibault
  3971. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3972. */
  3973. var TGATools = (function () {
  3974. function TGATools() {
  3975. }
  3976. TGATools.GetTGAHeader = function (data) {
  3977. var offset = 0;
  3978. var header = {
  3979. id_length: data[offset++],
  3980. colormap_type: data[offset++],
  3981. image_type: data[offset++],
  3982. colormap_index: data[offset++] | data[offset++] << 8,
  3983. colormap_length: data[offset++] | data[offset++] << 8,
  3984. colormap_size: data[offset++],
  3985. origin: [
  3986. data[offset++] | data[offset++] << 8,
  3987. data[offset++] | data[offset++] << 8
  3988. ],
  3989. width: data[offset++] | data[offset++] << 8,
  3990. height: data[offset++] | data[offset++] << 8,
  3991. pixel_size: data[offset++],
  3992. flags: data[offset++]
  3993. };
  3994. return header;
  3995. };
  3996. TGATools.UploadContent = function (gl, data) {
  3997. // Not enough data to contain header ?
  3998. if (data.length < 19) {
  3999. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4000. return;
  4001. }
  4002. // Read Header
  4003. var offset = 18;
  4004. var header = TGATools.GetTGAHeader(data);
  4005. // Assume it's a valid Targa file.
  4006. if (header.id_length + offset > data.length) {
  4007. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4008. return;
  4009. }
  4010. // Skip not needed data
  4011. offset += header.id_length;
  4012. var use_rle = false;
  4013. var use_pal = false;
  4014. var use_rgb = false;
  4015. var use_grey = false;
  4016. // Get some informations.
  4017. switch (header.image_type) {
  4018. case TGATools._TYPE_RLE_INDEXED:
  4019. use_rle = true;
  4020. case TGATools._TYPE_INDEXED:
  4021. use_pal = true;
  4022. break;
  4023. case TGATools._TYPE_RLE_RGB:
  4024. use_rle = true;
  4025. case TGATools._TYPE_RGB:
  4026. use_rgb = true;
  4027. break;
  4028. case TGATools._TYPE_RLE_GREY:
  4029. use_rle = true;
  4030. case TGATools._TYPE_GREY:
  4031. use_grey = true;
  4032. break;
  4033. }
  4034. var pixel_data;
  4035. var numAlphaBits = header.flags & 0xf;
  4036. var pixel_size = header.pixel_size >> 3;
  4037. var pixel_total = header.width * header.height * pixel_size;
  4038. // Read palettes
  4039. var palettes;
  4040. if (use_pal) {
  4041. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4042. }
  4043. // Read LRE
  4044. if (use_rle) {
  4045. pixel_data = new Uint8Array(pixel_total);
  4046. var c, count, i;
  4047. var localOffset = 0;
  4048. var pixels = new Uint8Array(pixel_size);
  4049. while (offset < pixel_total && localOffset < pixel_total) {
  4050. c = data[offset++];
  4051. count = (c & 0x7f) + 1;
  4052. // RLE pixels
  4053. if (c & 0x80) {
  4054. // Bind pixel tmp array
  4055. for (i = 0; i < pixel_size; ++i) {
  4056. pixels[i] = data[offset++];
  4057. }
  4058. // Copy pixel array
  4059. for (i = 0; i < count; ++i) {
  4060. pixel_data.set(pixels, localOffset + i * pixel_size);
  4061. }
  4062. localOffset += pixel_size * count;
  4063. }
  4064. else {
  4065. count *= pixel_size;
  4066. for (i = 0; i < count; ++i) {
  4067. pixel_data[localOffset + i] = data[offset++];
  4068. }
  4069. localOffset += count;
  4070. }
  4071. }
  4072. }
  4073. else {
  4074. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4075. }
  4076. // Load to texture
  4077. var x_start, y_start, x_step, y_step, y_end, x_end;
  4078. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4079. default:
  4080. case TGATools._ORIGIN_UL:
  4081. x_start = 0;
  4082. x_step = 1;
  4083. x_end = header.width;
  4084. y_start = 0;
  4085. y_step = 1;
  4086. y_end = header.height;
  4087. break;
  4088. case TGATools._ORIGIN_BL:
  4089. x_start = 0;
  4090. x_step = 1;
  4091. x_end = header.width;
  4092. y_start = header.height - 1;
  4093. y_step = -1;
  4094. y_end = -1;
  4095. break;
  4096. case TGATools._ORIGIN_UR:
  4097. x_start = header.width - 1;
  4098. x_step = -1;
  4099. x_end = -1;
  4100. y_start = 0;
  4101. y_step = 1;
  4102. y_end = header.height;
  4103. break;
  4104. case TGATools._ORIGIN_BR:
  4105. x_start = header.width - 1;
  4106. x_step = -1;
  4107. x_end = -1;
  4108. y_start = header.height - 1;
  4109. y_step = -1;
  4110. y_end = -1;
  4111. break;
  4112. }
  4113. // Load the specify method
  4114. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4115. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4116. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4117. };
  4118. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4119. var image = pixel_data, colormap = palettes;
  4120. var width = header.width, height = header.height;
  4121. var color, i = 0, x, y;
  4122. var imageData = new Uint8Array(width * height * 4);
  4123. for (y = y_start; y !== y_end; y += y_step) {
  4124. for (x = x_start; x !== x_end; x += x_step, i++) {
  4125. color = image[i];
  4126. imageData[(x + width * y) * 4 + 3] = 255;
  4127. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4128. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4129. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4130. }
  4131. }
  4132. return imageData;
  4133. };
  4134. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4135. var image = pixel_data;
  4136. var width = header.width, height = header.height;
  4137. var color, i = 0, x, y;
  4138. var imageData = new Uint8Array(width * height * 4);
  4139. for (y = y_start; y !== y_end; y += y_step) {
  4140. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4141. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4142. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4143. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4144. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4145. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4146. }
  4147. }
  4148. return imageData;
  4149. };
  4150. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4151. var image = pixel_data;
  4152. var width = header.width, height = header.height;
  4153. var i = 0, x, y;
  4154. var imageData = new Uint8Array(width * height * 4);
  4155. for (y = y_start; y !== y_end; y += y_step) {
  4156. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4157. imageData[(x + width * y) * 4 + 3] = 255;
  4158. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4159. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4160. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4161. }
  4162. }
  4163. return imageData;
  4164. };
  4165. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4166. var image = pixel_data;
  4167. var width = header.width, height = header.height;
  4168. var i = 0, x, y;
  4169. var imageData = new Uint8Array(width * height * 4);
  4170. for (y = y_start; y !== y_end; y += y_step) {
  4171. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4172. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4173. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4174. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4175. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4176. }
  4177. }
  4178. return imageData;
  4179. };
  4180. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4181. var image = pixel_data;
  4182. var width = header.width, height = header.height;
  4183. var color, i = 0, x, y;
  4184. var imageData = new Uint8Array(width * height * 4);
  4185. for (y = y_start; y !== y_end; y += y_step) {
  4186. for (x = x_start; x !== x_end; x += x_step, i++) {
  4187. color = image[i];
  4188. imageData[(x + width * y) * 4 + 0] = color;
  4189. imageData[(x + width * y) * 4 + 1] = color;
  4190. imageData[(x + width * y) * 4 + 2] = color;
  4191. imageData[(x + width * y) * 4 + 3] = 255;
  4192. }
  4193. }
  4194. return imageData;
  4195. };
  4196. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4197. var image = pixel_data;
  4198. var width = header.width, height = header.height;
  4199. var i = 0, x, y;
  4200. var imageData = new Uint8Array(width * height * 4);
  4201. for (y = y_start; y !== y_end; y += y_step) {
  4202. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4203. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4204. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4205. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4206. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4207. }
  4208. }
  4209. return imageData;
  4210. };
  4211. TGATools._TYPE_NO_DATA = 0;
  4212. TGATools._TYPE_INDEXED = 1;
  4213. TGATools._TYPE_RGB = 2;
  4214. TGATools._TYPE_GREY = 3;
  4215. TGATools._TYPE_RLE_INDEXED = 9;
  4216. TGATools._TYPE_RLE_RGB = 10;
  4217. TGATools._TYPE_RLE_GREY = 11;
  4218. TGATools._ORIGIN_MASK = 0x30;
  4219. TGATools._ORIGIN_SHIFT = 0x04;
  4220. TGATools._ORIGIN_BL = 0x00;
  4221. TGATools._ORIGIN_BR = 0x01;
  4222. TGATools._ORIGIN_UL = 0x02;
  4223. TGATools._ORIGIN_UR = 0x03;
  4224. return TGATools;
  4225. })();
  4226. Internals.TGATools = TGATools;
  4227. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4228. })(BABYLON || (BABYLON = {}));
  4229. var BABYLON;
  4230. (function (BABYLON) {
  4231. var SmartArray = (function () {
  4232. function SmartArray(capacity) {
  4233. this.length = 0;
  4234. this._duplicateId = 0;
  4235. this.data = new Array(capacity);
  4236. this._id = SmartArray._GlobalId++;
  4237. }
  4238. SmartArray.prototype.push = function (value) {
  4239. this.data[this.length++] = value;
  4240. if (this.length > this.data.length) {
  4241. this.data.length *= 2;
  4242. }
  4243. if (!value.__smartArrayFlags) {
  4244. value.__smartArrayFlags = {};
  4245. }
  4246. value.__smartArrayFlags[this._id] = this._duplicateId;
  4247. };
  4248. SmartArray.prototype.pushNoDuplicate = function (value) {
  4249. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4250. return false;
  4251. }
  4252. this.push(value);
  4253. return true;
  4254. };
  4255. SmartArray.prototype.sort = function (compareFn) {
  4256. this.data.sort(compareFn);
  4257. };
  4258. SmartArray.prototype.reset = function () {
  4259. this.length = 0;
  4260. this._duplicateId++;
  4261. };
  4262. SmartArray.prototype.concat = function (array) {
  4263. if (array.length === 0) {
  4264. return;
  4265. }
  4266. if (this.length + array.length > this.data.length) {
  4267. this.data.length = (this.length + array.length) * 2;
  4268. }
  4269. for (var index = 0; index < array.length; index++) {
  4270. this.data[this.length++] = (array.data || array)[index];
  4271. }
  4272. };
  4273. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4274. if (array.length === 0) {
  4275. return;
  4276. }
  4277. if (this.length + array.length > this.data.length) {
  4278. this.data.length = (this.length + array.length) * 2;
  4279. }
  4280. for (var index = 0; index < array.length; index++) {
  4281. var item = (array.data || array)[index];
  4282. this.pushNoDuplicate(item);
  4283. }
  4284. };
  4285. SmartArray.prototype.indexOf = function (value) {
  4286. var position = this.data.indexOf(value);
  4287. if (position >= this.length) {
  4288. return -1;
  4289. }
  4290. return position;
  4291. };
  4292. // Statics
  4293. SmartArray._GlobalId = 0;
  4294. return SmartArray;
  4295. })();
  4296. BABYLON.SmartArray = SmartArray;
  4297. })(BABYLON || (BABYLON = {}));
  4298. var BABYLON;
  4299. (function (BABYLON) {
  4300. /**
  4301. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4302. * The underlying implementation relies on an associative array to ensure the best performances.
  4303. * The value can be anything including 'null' but except 'undefined'
  4304. */
  4305. var StringDictionary = (function () {
  4306. function StringDictionary() {
  4307. this._count = 0;
  4308. this._data = {};
  4309. }
  4310. /**
  4311. * Get a value based from its key
  4312. * @param key the given key to get the matching value from
  4313. * @return the value if found, otherwise undefined is returned
  4314. */
  4315. StringDictionary.prototype.get = function (key) {
  4316. var val = this._data[key];
  4317. if (val !== undefined) {
  4318. return val;
  4319. }
  4320. return undefined;
  4321. };
  4322. /**
  4323. * Get a value from its key or add it if it doesn't exist.
  4324. * This method will ensure you that a given key/data will be present in the dictionary.
  4325. * @param key the given key to get the matching value from
  4326. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4327. * The factory will only be invoked if there's no data for the given key.
  4328. * @return the value corresponding to the key.
  4329. */
  4330. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4331. var val = this.get(key);
  4332. if (val !== undefined) {
  4333. return val;
  4334. }
  4335. val = factory(key);
  4336. if (val) {
  4337. this.add(key, val);
  4338. }
  4339. return val;
  4340. };
  4341. /**
  4342. * Get a value from its key if present in the dictionary otherwise add it
  4343. * @param key the key to get the value from
  4344. * @param val if there's no such key/value pair in the dictionary add it with this value
  4345. * @return the value corresponding to the key
  4346. */
  4347. StringDictionary.prototype.getOrAdd = function (key, val) {
  4348. var curVal = this.get(key);
  4349. if (curVal !== undefined) {
  4350. return curVal;
  4351. }
  4352. this.add(key, val);
  4353. return val;
  4354. };
  4355. /**
  4356. * Check if there's a given key in the dictionary
  4357. * @param key the key to check for
  4358. * @return true if the key is present, false otherwise
  4359. */
  4360. StringDictionary.prototype.contains = function (key) {
  4361. return this._data[key] !== undefined;
  4362. };
  4363. /**
  4364. * Add a new key and its corresponding value
  4365. * @param key the key to add
  4366. * @param value the value corresponding to the key
  4367. * @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
  4368. */
  4369. StringDictionary.prototype.add = function (key, value) {
  4370. if (this._data[key] !== undefined) {
  4371. return false;
  4372. }
  4373. this._data[key] = value;
  4374. ++this._count;
  4375. return true;
  4376. };
  4377. StringDictionary.prototype.set = function (key, value) {
  4378. if (this._data[key] === undefined) {
  4379. return false;
  4380. }
  4381. this._data[key] = value;
  4382. return true;
  4383. };
  4384. /**
  4385. * Remove a key/value from the dictionary.
  4386. * @param key the key to remove
  4387. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4388. */
  4389. StringDictionary.prototype.remove = function (key) {
  4390. if (this.contains(key)) {
  4391. delete this._data[key];
  4392. --this._count;
  4393. return true;
  4394. }
  4395. return false;
  4396. };
  4397. /**
  4398. * Clear the whole content of the dictionary
  4399. */
  4400. StringDictionary.prototype.clear = function () {
  4401. this._data = {};
  4402. this._count = 0;
  4403. };
  4404. Object.defineProperty(StringDictionary.prototype, "count", {
  4405. get: function () {
  4406. return this._count;
  4407. },
  4408. enumerable: true,
  4409. configurable: true
  4410. });
  4411. /**
  4412. * Execute a callback on each key/val of the dictionary.
  4413. * Note that you can remove any element in this dictionary in the callback implementation
  4414. * @param callback the callback to execute on a given key/value pair
  4415. */
  4416. StringDictionary.prototype.forEach = function (callback) {
  4417. for (var cur in this._data) {
  4418. var val = this._data[cur];
  4419. callback(cur, val);
  4420. }
  4421. };
  4422. /**
  4423. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4424. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4425. * Note that you can remove any element in this dictionary in the callback implementation
  4426. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4427. */
  4428. StringDictionary.prototype.first = function (callback) {
  4429. for (var cur in this._data) {
  4430. var val = this._data[cur];
  4431. var res = callback(cur, val);
  4432. if (res) {
  4433. return res;
  4434. }
  4435. }
  4436. return null;
  4437. };
  4438. return StringDictionary;
  4439. })();
  4440. BABYLON.StringDictionary = StringDictionary;
  4441. })(BABYLON || (BABYLON = {}));
  4442. var BABYLON;
  4443. (function (BABYLON) {
  4444. // Screenshots
  4445. var screenshotCanvas;
  4446. var cloneValue = function (source, destinationObject) {
  4447. if (!source)
  4448. return null;
  4449. if (source instanceof BABYLON.Mesh) {
  4450. return null;
  4451. }
  4452. if (source instanceof BABYLON.SubMesh) {
  4453. return source.clone(destinationObject);
  4454. }
  4455. else if (source.clone) {
  4456. return source.clone();
  4457. }
  4458. return null;
  4459. };
  4460. var Tools = (function () {
  4461. function Tools() {
  4462. }
  4463. Tools.Instantiate = function (className) {
  4464. var arr = className.split(".");
  4465. var fn = (window || this);
  4466. for (var i = 0, len = arr.length; i < len; i++) {
  4467. fn = fn[arr[i]];
  4468. }
  4469. if (typeof fn !== "function") {
  4470. return null;
  4471. }
  4472. return fn;
  4473. };
  4474. Tools.SetImmediate = function (action) {
  4475. if (window.setImmediate) {
  4476. window.setImmediate(action);
  4477. }
  4478. else {
  4479. setTimeout(action, 1);
  4480. }
  4481. };
  4482. Tools.IsExponentOfTwo = function (value) {
  4483. var count = 1;
  4484. do {
  4485. count *= 2;
  4486. } while (count < value);
  4487. return count === value;
  4488. };
  4489. Tools.GetExponentOfTwo = function (value, max) {
  4490. var count = 1;
  4491. do {
  4492. count *= 2;
  4493. } while (count < value);
  4494. if (count > max)
  4495. count = max;
  4496. return count;
  4497. };
  4498. Tools.GetFilename = function (path) {
  4499. var index = path.lastIndexOf("/");
  4500. if (index < 0)
  4501. return path;
  4502. return path.substring(index + 1);
  4503. };
  4504. Tools.GetDOMTextContent = function (element) {
  4505. var result = "";
  4506. var child = element.firstChild;
  4507. while (child) {
  4508. if (child.nodeType === 3) {
  4509. result += child.textContent;
  4510. }
  4511. child = child.nextSibling;
  4512. }
  4513. return result;
  4514. };
  4515. Tools.ToDegrees = function (angle) {
  4516. return angle * 180 / Math.PI;
  4517. };
  4518. Tools.ToRadians = function (angle) {
  4519. return angle * Math.PI / 180;
  4520. };
  4521. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4522. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4523. var output = "";
  4524. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4525. var i = 0;
  4526. var bytes = new Uint8Array(buffer);
  4527. while (i < bytes.length) {
  4528. chr1 = bytes[i++];
  4529. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4530. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4531. enc1 = chr1 >> 2;
  4532. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4533. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4534. enc4 = chr3 & 63;
  4535. if (isNaN(chr2)) {
  4536. enc3 = enc4 = 64;
  4537. }
  4538. else if (isNaN(chr3)) {
  4539. enc4 = 64;
  4540. }
  4541. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4542. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4543. }
  4544. return "data:image/png;base64," + output;
  4545. };
  4546. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4547. if (bias === void 0) { bias = null; }
  4548. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4549. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4550. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4551. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4552. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4553. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4554. }
  4555. if (bias) {
  4556. minimum.x -= minimum.x * bias.x + bias.y;
  4557. minimum.y -= minimum.y * bias.x + bias.y;
  4558. minimum.z -= minimum.z * bias.x + bias.y;
  4559. maximum.x += maximum.x * bias.x + bias.y;
  4560. maximum.y += maximum.y * bias.x + bias.y;
  4561. maximum.z += maximum.z * bias.x + bias.y;
  4562. }
  4563. return {
  4564. minimum: minimum,
  4565. maximum: maximum
  4566. };
  4567. };
  4568. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4569. if (bias === void 0) { bias = null; }
  4570. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4571. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4572. if (!stride) {
  4573. stride = 3;
  4574. }
  4575. for (var index = start; index < start + count; index++) {
  4576. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4577. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4578. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4579. }
  4580. if (bias) {
  4581. minimum.x -= minimum.x * bias.x + bias.y;
  4582. minimum.y -= minimum.y * bias.x + bias.y;
  4583. minimum.z -= minimum.z * bias.x + bias.y;
  4584. maximum.x += maximum.x * bias.x + bias.y;
  4585. maximum.y += maximum.y * bias.x + bias.y;
  4586. maximum.z += maximum.z * bias.x + bias.y;
  4587. }
  4588. return {
  4589. minimum: minimum,
  4590. maximum: maximum
  4591. };
  4592. };
  4593. Tools.Vector2ArrayFeeder = function (array) {
  4594. return function (index) {
  4595. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4596. var length = isFloatArray ? array.length / 2 : array.length;
  4597. if (index >= length) {
  4598. return null;
  4599. }
  4600. if (isFloatArray) {
  4601. var fa = array;
  4602. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4603. }
  4604. var a = array;
  4605. return a[index];
  4606. };
  4607. };
  4608. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4609. if (bias === void 0) { bias = null; }
  4610. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4611. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4612. var i = 0;
  4613. var cur = feeder(i++);
  4614. while (cur) {
  4615. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4616. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4617. cur = feeder(i++);
  4618. }
  4619. if (bias) {
  4620. minimum.x -= minimum.x * bias.x + bias.y;
  4621. minimum.y -= minimum.y * bias.x + bias.y;
  4622. maximum.x += maximum.x * bias.x + bias.y;
  4623. maximum.y += maximum.y * bias.x + bias.y;
  4624. }
  4625. return {
  4626. minimum: minimum,
  4627. maximum: maximum
  4628. };
  4629. };
  4630. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4631. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4632. return undefined;
  4633. return Array.isArray(obj) ? obj : [obj];
  4634. };
  4635. // Misc.
  4636. Tools.GetPointerPrefix = function () {
  4637. var eventPrefix = "pointer";
  4638. // Check if pointer events are supported
  4639. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4640. eventPrefix = "mouse";
  4641. }
  4642. return eventPrefix;
  4643. };
  4644. Tools.QueueNewFrame = function (func) {
  4645. if (window.requestAnimationFrame)
  4646. window.requestAnimationFrame(func);
  4647. else if (window.msRequestAnimationFrame)
  4648. window.msRequestAnimationFrame(func);
  4649. else if (window.webkitRequestAnimationFrame)
  4650. window.webkitRequestAnimationFrame(func);
  4651. else if (window.mozRequestAnimationFrame)
  4652. window.mozRequestAnimationFrame(func);
  4653. else if (window.oRequestAnimationFrame)
  4654. window.oRequestAnimationFrame(func);
  4655. else {
  4656. window.setTimeout(func, 16);
  4657. }
  4658. };
  4659. Tools.RequestFullscreen = function (element, options) {
  4660. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4661. if (!requestFunction)
  4662. return;
  4663. requestFunction.call(element, options);
  4664. };
  4665. Tools.ExitFullscreen = function () {
  4666. if (document.exitFullscreen) {
  4667. document.exitFullscreen();
  4668. }
  4669. else if (document.mozCancelFullScreen) {
  4670. document.mozCancelFullScreen();
  4671. }
  4672. else if (document.webkitCancelFullScreen) {
  4673. document.webkitCancelFullScreen();
  4674. }
  4675. else if (document.msCancelFullScreen) {
  4676. document.msCancelFullScreen();
  4677. }
  4678. };
  4679. // External files
  4680. Tools.CleanUrl = function (url) {
  4681. url = url.replace(/#/mg, "%23");
  4682. return url;
  4683. };
  4684. Tools.LoadImage = function (url, onload, onerror, database) {
  4685. if (url instanceof ArrayBuffer) {
  4686. url = Tools.EncodeArrayBufferTobase64(url);
  4687. }
  4688. url = Tools.CleanUrl(url);
  4689. var img = new Image();
  4690. if (url.substr(0, 5) !== "data:") {
  4691. if (Tools.CorsBehavior) {
  4692. switch (typeof (Tools.CorsBehavior)) {
  4693. case "function":
  4694. var result = Tools.CorsBehavior(url);
  4695. if (result) {
  4696. img.crossOrigin = result;
  4697. }
  4698. break;
  4699. case "string":
  4700. default:
  4701. img.crossOrigin = Tools.CorsBehavior;
  4702. break;
  4703. }
  4704. }
  4705. }
  4706. img.onload = function () {
  4707. onload(img);
  4708. };
  4709. img.onerror = function (err) {
  4710. Tools.Error("Error while trying to load texture: " + url);
  4711. if (Tools.UseFallbackTexture) {
  4712. 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";
  4713. onload(img);
  4714. }
  4715. else {
  4716. onerror();
  4717. }
  4718. };
  4719. var noIndexedDB = function () {
  4720. img.src = url;
  4721. };
  4722. var loadFromIndexedDB = function () {
  4723. database.loadImageFromDB(url, img);
  4724. };
  4725. //ANY database to do!
  4726. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4727. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4728. }
  4729. else {
  4730. if (url.indexOf("file:") === -1) {
  4731. noIndexedDB();
  4732. }
  4733. else {
  4734. try {
  4735. var textureName = url.substring(5).toLowerCase();
  4736. var blobURL;
  4737. try {
  4738. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4739. }
  4740. catch (ex) {
  4741. // Chrome doesn't support oneTimeOnly parameter
  4742. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4743. }
  4744. img.src = blobURL;
  4745. }
  4746. catch (e) {
  4747. img.src = null;
  4748. }
  4749. }
  4750. }
  4751. return img;
  4752. };
  4753. //ANY
  4754. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4755. url = Tools.CleanUrl(url);
  4756. var noIndexedDB = function () {
  4757. var request = new XMLHttpRequest();
  4758. var loadUrl = Tools.BaseUrl + url;
  4759. request.open('GET', loadUrl, true);
  4760. if (useArrayBuffer) {
  4761. request.responseType = "arraybuffer";
  4762. }
  4763. request.onprogress = progressCallBack;
  4764. request.onreadystatechange = function () {
  4765. if (request.readyState === 4) {
  4766. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4767. callback(!useArrayBuffer ? request.responseText : request.response);
  4768. }
  4769. else {
  4770. if (onError) {
  4771. onError();
  4772. }
  4773. else {
  4774. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4775. }
  4776. }
  4777. }
  4778. };
  4779. request.send(null);
  4780. };
  4781. var loadFromIndexedDB = function () {
  4782. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4783. };
  4784. if (url.indexOf("file:") !== -1) {
  4785. var fileName = url.substring(5).toLowerCase();
  4786. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4787. }
  4788. else {
  4789. // Caching all files
  4790. if (database && database.enableSceneOffline) {
  4791. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4792. }
  4793. else {
  4794. noIndexedDB();
  4795. }
  4796. }
  4797. };
  4798. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4799. var reader = new FileReader();
  4800. reader.onload = function (e) {
  4801. //target doesn't have result from ts 1.3
  4802. callback(e.target['result']);
  4803. };
  4804. reader.onprogress = progressCallback;
  4805. reader.readAsDataURL(fileToLoad);
  4806. };
  4807. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4808. var reader = new FileReader();
  4809. reader.onerror = function (e) {
  4810. Tools.Log("Error while reading file: " + fileToLoad.name);
  4811. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4812. };
  4813. reader.onload = function (e) {
  4814. //target doesn't have result from ts 1.3
  4815. callback(e.target['result']);
  4816. };
  4817. reader.onprogress = progressCallBack;
  4818. if (!useArrayBuffer) {
  4819. // Asynchronous read
  4820. reader.readAsText(fileToLoad);
  4821. }
  4822. else {
  4823. reader.readAsArrayBuffer(fileToLoad);
  4824. }
  4825. };
  4826. //returns a downloadable url to a file content.
  4827. Tools.FileAsURL = function (content) {
  4828. var fileBlob = new Blob([content]);
  4829. var url = window.URL || window.webkitURL;
  4830. var link = url.createObjectURL(fileBlob);
  4831. return link;
  4832. };
  4833. // Misc.
  4834. Tools.Format = function (value, decimals) {
  4835. if (decimals === void 0) { decimals = 2; }
  4836. return value.toFixed(decimals);
  4837. };
  4838. Tools.CheckExtends = function (v, min, max) {
  4839. if (v.x < min.x)
  4840. min.x = v.x;
  4841. if (v.y < min.y)
  4842. min.y = v.y;
  4843. if (v.z < min.z)
  4844. min.z = v.z;
  4845. if (v.x > max.x)
  4846. max.x = v.x;
  4847. if (v.y > max.y)
  4848. max.y = v.y;
  4849. if (v.z > max.z)
  4850. max.z = v.z;
  4851. };
  4852. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4853. for (var prop in source) {
  4854. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4855. continue;
  4856. }
  4857. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4858. continue;
  4859. }
  4860. var sourceValue = source[prop];
  4861. var typeOfSourceValue = typeof sourceValue;
  4862. if (typeOfSourceValue === "function") {
  4863. continue;
  4864. }
  4865. if (typeOfSourceValue === "object") {
  4866. if (sourceValue instanceof Array) {
  4867. destination[prop] = [];
  4868. if (sourceValue.length > 0) {
  4869. if (typeof sourceValue[0] == "object") {
  4870. for (var index = 0; index < sourceValue.length; index++) {
  4871. var clonedValue = cloneValue(sourceValue[index], destination);
  4872. if (destination[prop].indexOf(clonedValue) === -1) {
  4873. destination[prop].push(clonedValue);
  4874. }
  4875. }
  4876. }
  4877. else {
  4878. destination[prop] = sourceValue.slice(0);
  4879. }
  4880. }
  4881. }
  4882. else {
  4883. destination[prop] = cloneValue(sourceValue, destination);
  4884. }
  4885. }
  4886. else {
  4887. destination[prop] = sourceValue;
  4888. }
  4889. }
  4890. };
  4891. Tools.IsEmpty = function (obj) {
  4892. for (var i in obj) {
  4893. return false;
  4894. }
  4895. return true;
  4896. };
  4897. Tools.RegisterTopRootEvents = function (events) {
  4898. for (var index = 0; index < events.length; index++) {
  4899. var event = events[index];
  4900. window.addEventListener(event.name, event.handler, false);
  4901. try {
  4902. if (window.parent) {
  4903. window.parent.addEventListener(event.name, event.handler, false);
  4904. }
  4905. }
  4906. catch (e) {
  4907. }
  4908. }
  4909. };
  4910. Tools.UnregisterTopRootEvents = function (events) {
  4911. for (var index = 0; index < events.length; index++) {
  4912. var event = events[index];
  4913. window.removeEventListener(event.name, event.handler);
  4914. try {
  4915. if (window.parent) {
  4916. window.parent.removeEventListener(event.name, event.handler);
  4917. }
  4918. }
  4919. catch (e) {
  4920. }
  4921. }
  4922. };
  4923. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4924. // Read the contents of the framebuffer
  4925. var numberOfChannelsByLine = width * 4;
  4926. var halfHeight = height / 2;
  4927. //Reading datas from WebGL
  4928. var data = engine.readPixels(0, 0, width, height);
  4929. //To flip image on Y axis.
  4930. for (var i = 0; i < halfHeight; i++) {
  4931. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4932. var currentCell = j + i * numberOfChannelsByLine;
  4933. var targetLine = height - i - 1;
  4934. var targetCell = j + targetLine * numberOfChannelsByLine;
  4935. var temp = data[currentCell];
  4936. data[currentCell] = data[targetCell];
  4937. data[targetCell] = temp;
  4938. }
  4939. }
  4940. // Create a 2D canvas to store the result
  4941. if (!screenshotCanvas) {
  4942. screenshotCanvas = document.createElement('canvas');
  4943. }
  4944. screenshotCanvas.width = width;
  4945. screenshotCanvas.height = height;
  4946. var context = screenshotCanvas.getContext('2d');
  4947. // Copy the pixels to a 2D canvas
  4948. var imageData = context.createImageData(width, height);
  4949. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4950. var castData = imageData.data;
  4951. castData.set(data);
  4952. context.putImageData(imageData, 0, 0);
  4953. var base64Image = screenshotCanvas.toDataURL();
  4954. if (successCallback) {
  4955. successCallback(base64Image);
  4956. }
  4957. else {
  4958. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4959. if (("download" in document.createElement("a"))) {
  4960. var a = window.document.createElement("a");
  4961. a.href = base64Image;
  4962. var date = new Date();
  4963. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4964. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4965. window.document.body.appendChild(a);
  4966. a.addEventListener("click", function () {
  4967. a.parentElement.removeChild(a);
  4968. });
  4969. a.click();
  4970. }
  4971. else {
  4972. var newWindow = window.open("");
  4973. var img = newWindow.document.createElement("img");
  4974. img.src = base64Image;
  4975. newWindow.document.body.appendChild(img);
  4976. }
  4977. }
  4978. };
  4979. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4980. var width;
  4981. var height;
  4982. //If a precision value is specified
  4983. if (size.precision) {
  4984. width = Math.round(engine.getRenderWidth() * size.precision);
  4985. height = Math.round(width / engine.getAspectRatio(camera));
  4986. size = { width: width, height: height };
  4987. }
  4988. else if (size.width && size.height) {
  4989. width = size.width;
  4990. height = size.height;
  4991. }
  4992. else if (size.width && !size.height) {
  4993. width = size.width;
  4994. height = Math.round(width / engine.getAspectRatio(camera));
  4995. size = { width: width, height: height };
  4996. }
  4997. else if (size.height && !size.width) {
  4998. height = size.height;
  4999. width = Math.round(height * engine.getAspectRatio(camera));
  5000. size = { width: width, height: height };
  5001. }
  5002. else if (!isNaN(size)) {
  5003. height = size;
  5004. width = size;
  5005. }
  5006. else {
  5007. Tools.Error("Invalid 'size' parameter !");
  5008. return;
  5009. }
  5010. var scene = camera.getScene();
  5011. var previousCamera = null;
  5012. if (scene.activeCamera !== camera) {
  5013. previousCamera = scene.activeCamera;
  5014. scene.activeCamera = camera;
  5015. }
  5016. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5017. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5018. texture.renderList = scene.meshes;
  5019. texture.onAfterRenderObservable.add(function () {
  5020. Tools.DumpFramebuffer(width, height, engine, successCallback);
  5021. });
  5022. scene.incrementRenderId();
  5023. scene.resetCachedMaterial();
  5024. texture.render(true);
  5025. texture.dispose();
  5026. if (previousCamera) {
  5027. scene.activeCamera = previousCamera;
  5028. }
  5029. camera.getProjectionMatrix(true); // Force cache refresh;
  5030. };
  5031. // XHR response validator for local file scenario
  5032. Tools.ValidateXHRData = function (xhr, dataType) {
  5033. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5034. if (dataType === void 0) { dataType = 7; }
  5035. try {
  5036. if (dataType & 1) {
  5037. if (xhr.responseText && xhr.responseText.length > 0) {
  5038. return true;
  5039. }
  5040. else if (dataType === 1) {
  5041. return false;
  5042. }
  5043. }
  5044. if (dataType & 2) {
  5045. // Check header width and height since there is no "TGA" magic number
  5046. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5047. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5048. return true;
  5049. }
  5050. else if (dataType === 2) {
  5051. return false;
  5052. }
  5053. }
  5054. if (dataType & 4) {
  5055. // Check for the "DDS" magic number
  5056. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5057. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5058. return true;
  5059. }
  5060. else {
  5061. return false;
  5062. }
  5063. }
  5064. }
  5065. catch (e) {
  5066. }
  5067. return false;
  5068. };
  5069. Object.defineProperty(Tools, "NoneLogLevel", {
  5070. get: function () {
  5071. return Tools._NoneLogLevel;
  5072. },
  5073. enumerable: true,
  5074. configurable: true
  5075. });
  5076. Object.defineProperty(Tools, "MessageLogLevel", {
  5077. get: function () {
  5078. return Tools._MessageLogLevel;
  5079. },
  5080. enumerable: true,
  5081. configurable: true
  5082. });
  5083. Object.defineProperty(Tools, "WarningLogLevel", {
  5084. get: function () {
  5085. return Tools._WarningLogLevel;
  5086. },
  5087. enumerable: true,
  5088. configurable: true
  5089. });
  5090. Object.defineProperty(Tools, "ErrorLogLevel", {
  5091. get: function () {
  5092. return Tools._ErrorLogLevel;
  5093. },
  5094. enumerable: true,
  5095. configurable: true
  5096. });
  5097. Object.defineProperty(Tools, "AllLogLevel", {
  5098. get: function () {
  5099. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5100. },
  5101. enumerable: true,
  5102. configurable: true
  5103. });
  5104. Tools._AddLogEntry = function (entry) {
  5105. Tools._LogCache = entry + Tools._LogCache;
  5106. if (Tools.OnNewCacheEntry) {
  5107. Tools.OnNewCacheEntry(entry);
  5108. }
  5109. };
  5110. Tools._FormatMessage = function (message) {
  5111. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5112. var date = new Date();
  5113. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5114. };
  5115. Tools._LogDisabled = function (message) {
  5116. // nothing to do
  5117. };
  5118. Tools._LogEnabled = function (message) {
  5119. var formattedMessage = Tools._FormatMessage(message);
  5120. console.log("BJS - " + formattedMessage);
  5121. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5122. Tools._AddLogEntry(entry);
  5123. };
  5124. Tools._WarnDisabled = function (message) {
  5125. // nothing to do
  5126. };
  5127. Tools._WarnEnabled = function (message) {
  5128. var formattedMessage = Tools._FormatMessage(message);
  5129. console.warn("BJS - " + formattedMessage);
  5130. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5131. Tools._AddLogEntry(entry);
  5132. };
  5133. Tools._ErrorDisabled = function (message) {
  5134. // nothing to do
  5135. };
  5136. Tools._ErrorEnabled = function (message) {
  5137. Tools.errorsCount++;
  5138. var formattedMessage = Tools._FormatMessage(message);
  5139. console.error("BJS - " + formattedMessage);
  5140. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5141. Tools._AddLogEntry(entry);
  5142. };
  5143. Object.defineProperty(Tools, "LogCache", {
  5144. get: function () {
  5145. return Tools._LogCache;
  5146. },
  5147. enumerable: true,
  5148. configurable: true
  5149. });
  5150. Tools.ClearLogCache = function () {
  5151. Tools._LogCache = "";
  5152. Tools.errorsCount = 0;
  5153. };
  5154. Object.defineProperty(Tools, "LogLevels", {
  5155. set: function (level) {
  5156. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5157. Tools.Log = Tools._LogEnabled;
  5158. }
  5159. else {
  5160. Tools.Log = Tools._LogDisabled;
  5161. }
  5162. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5163. Tools.Warn = Tools._WarnEnabled;
  5164. }
  5165. else {
  5166. Tools.Warn = Tools._WarnDisabled;
  5167. }
  5168. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5169. Tools.Error = Tools._ErrorEnabled;
  5170. }
  5171. else {
  5172. Tools.Error = Tools._ErrorDisabled;
  5173. }
  5174. },
  5175. enumerable: true,
  5176. configurable: true
  5177. });
  5178. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5179. get: function () {
  5180. return Tools._PerformanceNoneLogLevel;
  5181. },
  5182. enumerable: true,
  5183. configurable: true
  5184. });
  5185. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5186. get: function () {
  5187. return Tools._PerformanceUserMarkLogLevel;
  5188. },
  5189. enumerable: true,
  5190. configurable: true
  5191. });
  5192. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5193. get: function () {
  5194. return Tools._PerformanceConsoleLogLevel;
  5195. },
  5196. enumerable: true,
  5197. configurable: true
  5198. });
  5199. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5200. set: function (level) {
  5201. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5202. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5203. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5204. return;
  5205. }
  5206. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5207. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5208. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5209. return;
  5210. }
  5211. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5212. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5213. },
  5214. enumerable: true,
  5215. configurable: true
  5216. });
  5217. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5218. };
  5219. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._StartUserMark = function (counterName, condition) {
  5222. if (condition === void 0) { condition = true; }
  5223. if (!condition || !Tools._performance.mark) {
  5224. return;
  5225. }
  5226. Tools._performance.mark(counterName + "-Begin");
  5227. };
  5228. Tools._EndUserMark = function (counterName, condition) {
  5229. if (condition === void 0) { condition = true; }
  5230. if (!condition || !Tools._performance.mark) {
  5231. return;
  5232. }
  5233. Tools._performance.mark(counterName + "-End");
  5234. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5235. };
  5236. Tools._StartPerformanceConsole = function (counterName, condition) {
  5237. if (condition === void 0) { condition = true; }
  5238. if (!condition) {
  5239. return;
  5240. }
  5241. Tools._StartUserMark(counterName, condition);
  5242. if (console.time) {
  5243. console.time(counterName);
  5244. }
  5245. };
  5246. Tools._EndPerformanceConsole = function (counterName, condition) {
  5247. if (condition === void 0) { condition = true; }
  5248. if (!condition) {
  5249. return;
  5250. }
  5251. Tools._EndUserMark(counterName, condition);
  5252. if (console.time) {
  5253. console.timeEnd(counterName);
  5254. }
  5255. };
  5256. Object.defineProperty(Tools, "Now", {
  5257. get: function () {
  5258. if (window.performance && window.performance.now) {
  5259. return window.performance.now();
  5260. }
  5261. return new Date().getTime();
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. /**
  5267. * This method will return the name of the class used to create the instance of the given object.
  5268. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5269. * @param object the object to get the class name from
  5270. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5271. */
  5272. Tools.getClassName = function (object, isType) {
  5273. if (isType === void 0) { isType = false; }
  5274. var name = null;
  5275. if (!isType && object.getClassName) {
  5276. name = object.getClassName();
  5277. }
  5278. else {
  5279. if (object instanceof Object) {
  5280. var classObj = isType ? object : Object.getPrototypeOf(object);
  5281. name = classObj.constructor["__bjsclassName__"];
  5282. }
  5283. if (!name) {
  5284. name = typeof object;
  5285. }
  5286. }
  5287. return name;
  5288. };
  5289. Tools.first = function (array, predicate) {
  5290. for (var _i = 0; _i < array.length; _i++) {
  5291. var el = array[_i];
  5292. if (predicate(el)) {
  5293. return el;
  5294. }
  5295. }
  5296. };
  5297. /**
  5298. * 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.
  5299. * @param array
  5300. */
  5301. Tools.arrayOrStringFeeder = function (array) {
  5302. return function (index) {
  5303. if (index >= array.length) {
  5304. return null;
  5305. }
  5306. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5307. if (val && val.getHashCode) {
  5308. val = val.getHashCode();
  5309. }
  5310. if (typeof val === "string") {
  5311. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5312. }
  5313. return val;
  5314. };
  5315. };
  5316. /**
  5317. * Compute the hashCode of a stream of number
  5318. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5319. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5320. * @return the hash code computed
  5321. */
  5322. Tools.hashCodeFromStream = function (feeder) {
  5323. // Based from here: http://stackoverflow.com/a/7616484/802124
  5324. var hash = 0;
  5325. var index = 0;
  5326. var chr = feeder(index++);
  5327. while (chr != null) {
  5328. hash = ((hash << 5) - hash) + chr;
  5329. hash |= 0; // Convert to 32bit integer
  5330. chr = feeder(index++);
  5331. }
  5332. return hash;
  5333. };
  5334. Tools.BaseUrl = "";
  5335. Tools.CorsBehavior = "anonymous";
  5336. Tools.UseFallbackTexture = true;
  5337. // Logs
  5338. Tools._NoneLogLevel = 0;
  5339. Tools._MessageLogLevel = 1;
  5340. Tools._WarningLogLevel = 2;
  5341. Tools._ErrorLogLevel = 4;
  5342. Tools._LogCache = "";
  5343. Tools.errorsCount = 0;
  5344. Tools.Log = Tools._LogEnabled;
  5345. Tools.Warn = Tools._WarnEnabled;
  5346. Tools.Error = Tools._ErrorEnabled;
  5347. // Performances
  5348. Tools._PerformanceNoneLogLevel = 0;
  5349. Tools._PerformanceUserMarkLogLevel = 1;
  5350. Tools._PerformanceConsoleLogLevel = 2;
  5351. Tools._performance = window.performance;
  5352. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5353. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5354. return Tools;
  5355. })();
  5356. BABYLON.Tools = Tools;
  5357. /**
  5358. * This class is used to track a performance counter which is number based.
  5359. * The user has access to many properties which give statistics of different nature
  5360. *
  5361. * The implementer can track two kinds of Performance Counter: time and count
  5362. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  5363. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  5364. */
  5365. var PerfCounter = (function () {
  5366. function PerfCounter() {
  5367. this._startMonitoringTime = 0;
  5368. this._min = 0;
  5369. this._max = 0;
  5370. this._average = 0;
  5371. this._lastSecAverage = 0;
  5372. this._current = 0;
  5373. this._totalValueCount = 0;
  5374. this._totalAccumulated = 0;
  5375. this._lastSecAccumulated = 0;
  5376. this._lastSecTime = 0;
  5377. this._lastSecValueCount = 0;
  5378. }
  5379. Object.defineProperty(PerfCounter.prototype, "min", {
  5380. /**
  5381. * Returns the smallest value ever
  5382. */
  5383. get: function () {
  5384. return this._min;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(PerfCounter.prototype, "max", {
  5390. /**
  5391. * Returns the biggest value ever
  5392. */
  5393. get: function () {
  5394. return this._max;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Object.defineProperty(PerfCounter.prototype, "average", {
  5400. /**
  5401. * Returns the average value since the performance counter is running
  5402. */
  5403. get: function () {
  5404. return this._average;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5410. /**
  5411. * Returns the average value of the last second the counter was monitored
  5412. */
  5413. get: function () {
  5414. return this._lastSecAverage;
  5415. },
  5416. enumerable: true,
  5417. configurable: true
  5418. });
  5419. Object.defineProperty(PerfCounter.prototype, "current", {
  5420. /**
  5421. * Returns the current value
  5422. */
  5423. get: function () {
  5424. return this._current;
  5425. },
  5426. enumerable: true,
  5427. configurable: true
  5428. });
  5429. Object.defineProperty(PerfCounter.prototype, "total", {
  5430. get: function () {
  5431. return this._totalAccumulated;
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. /**
  5437. * Call this method to start monitoring a new frame.
  5438. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  5439. */
  5440. PerfCounter.prototype.fetchNewFrame = function () {
  5441. this._totalValueCount++;
  5442. this._current = 0;
  5443. this._lastSecValueCount++;
  5444. };
  5445. /**
  5446. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5447. * @param newCount the count value to add to the monitored count
  5448. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  5449. */
  5450. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5451. this._current += newCount;
  5452. if (fetchResult) {
  5453. this._fetchResult();
  5454. }
  5455. };
  5456. /**
  5457. * Start monitoring this performance counter
  5458. */
  5459. PerfCounter.prototype.beginMonitoring = function () {
  5460. this._startMonitoringTime = Tools.Now;
  5461. };
  5462. /**
  5463. * Compute the time lapsed since the previous beginMonitoring() call.
  5464. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  5465. */
  5466. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5467. if (newFrame === void 0) { newFrame = true; }
  5468. if (newFrame) {
  5469. this.fetchNewFrame();
  5470. }
  5471. var currentTime = Tools.Now;
  5472. this._current = currentTime - this._startMonitoringTime;
  5473. if (newFrame) {
  5474. this._fetchResult();
  5475. }
  5476. };
  5477. PerfCounter.prototype._fetchResult = function () {
  5478. this._totalAccumulated += this._current;
  5479. this._lastSecAccumulated += this._current;
  5480. // Min/Max update
  5481. this._min = Math.min(this._min, this._current);
  5482. this._max = Math.max(this._max, this._current);
  5483. this._average = this._totalAccumulated / this._totalValueCount;
  5484. // Reset last sec?
  5485. var now = Tools.Now;
  5486. if ((now - this._lastSecTime) > 1000) {
  5487. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5488. this._lastSecTime = now;
  5489. this._lastSecAccumulated = 0;
  5490. this._lastSecValueCount = 0;
  5491. }
  5492. };
  5493. return PerfCounter;
  5494. })();
  5495. BABYLON.PerfCounter = PerfCounter;
  5496. /**
  5497. * Use this className as a decorator on a given class definition to add it a name.
  5498. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5499. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5500. * @param name
  5501. */
  5502. function className(name) {
  5503. return function (target) {
  5504. target["__bjsclassName__"] = name;
  5505. };
  5506. }
  5507. BABYLON.className = className;
  5508. /**
  5509. * An implementation of a loop for asynchronous functions.
  5510. */
  5511. var AsyncLoop = (function () {
  5512. /**
  5513. * Constroctor.
  5514. * @param iterations the number of iterations.
  5515. * @param _fn the function to run each iteration
  5516. * @param _successCallback the callback that will be called upon succesful execution
  5517. * @param offset starting offset.
  5518. */
  5519. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5520. if (offset === void 0) { offset = 0; }
  5521. this.iterations = iterations;
  5522. this._fn = _fn;
  5523. this._successCallback = _successCallback;
  5524. this.index = offset - 1;
  5525. this._done = false;
  5526. }
  5527. /**
  5528. * Execute the next iteration. Must be called after the last iteration was finished.
  5529. */
  5530. AsyncLoop.prototype.executeNext = function () {
  5531. if (!this._done) {
  5532. if (this.index + 1 < this.iterations) {
  5533. ++this.index;
  5534. this._fn(this);
  5535. }
  5536. else {
  5537. this.breakLoop();
  5538. }
  5539. }
  5540. };
  5541. /**
  5542. * Break the loop and run the success callback.
  5543. */
  5544. AsyncLoop.prototype.breakLoop = function () {
  5545. this._done = true;
  5546. this._successCallback();
  5547. };
  5548. /**
  5549. * Helper function
  5550. */
  5551. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5552. if (offset === void 0) { offset = 0; }
  5553. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5554. loop.executeNext();
  5555. return loop;
  5556. };
  5557. /**
  5558. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5559. * @param iterations total number of iterations
  5560. * @param syncedIterations number of synchronous iterations in each async iteration.
  5561. * @param fn the function to call each iteration.
  5562. * @param callback a success call back that will be called when iterating stops.
  5563. * @param breakFunction a break condition (optional)
  5564. * @param timeout timeout settings for the setTimeout function. default - 0.
  5565. * @constructor
  5566. */
  5567. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5568. if (timeout === void 0) { timeout = 0; }
  5569. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5570. if (breakFunction && breakFunction())
  5571. loop.breakLoop();
  5572. else {
  5573. setTimeout(function () {
  5574. for (var i = 0; i < syncedIterations; ++i) {
  5575. var iteration = (loop.index * syncedIterations) + i;
  5576. if (iteration >= iterations)
  5577. break;
  5578. fn(iteration);
  5579. if (breakFunction && breakFunction()) {
  5580. loop.breakLoop();
  5581. break;
  5582. }
  5583. }
  5584. loop.executeNext();
  5585. }, timeout);
  5586. }
  5587. }, callback);
  5588. };
  5589. return AsyncLoop;
  5590. })();
  5591. BABYLON.AsyncLoop = AsyncLoop;
  5592. })(BABYLON || (BABYLON = {}));
  5593. var BABYLON;
  5594. (function (BABYLON) {
  5595. var Internals;
  5596. (function (Internals) {
  5597. var _AlphaState = (function () {
  5598. function _AlphaState() {
  5599. this._isAlphaBlendDirty = false;
  5600. this._isBlendFunctionParametersDirty = false;
  5601. this._alphaBlend = false;
  5602. this._blendFunctionParameters = new Array(4);
  5603. }
  5604. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5605. get: function () {
  5606. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5607. },
  5608. enumerable: true,
  5609. configurable: true
  5610. });
  5611. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5612. get: function () {
  5613. return this._alphaBlend;
  5614. },
  5615. set: function (value) {
  5616. if (this._alphaBlend === value) {
  5617. return;
  5618. }
  5619. this._alphaBlend = value;
  5620. this._isAlphaBlendDirty = true;
  5621. },
  5622. enumerable: true,
  5623. configurable: true
  5624. });
  5625. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5626. if (this._blendFunctionParameters[0] === value0 &&
  5627. this._blendFunctionParameters[1] === value1 &&
  5628. this._blendFunctionParameters[2] === value2 &&
  5629. this._blendFunctionParameters[3] === value3) {
  5630. return;
  5631. }
  5632. this._blendFunctionParameters[0] = value0;
  5633. this._blendFunctionParameters[1] = value1;
  5634. this._blendFunctionParameters[2] = value2;
  5635. this._blendFunctionParameters[3] = value3;
  5636. this._isBlendFunctionParametersDirty = true;
  5637. };
  5638. _AlphaState.prototype.reset = function () {
  5639. this._alphaBlend = false;
  5640. this._blendFunctionParameters[0] = null;
  5641. this._blendFunctionParameters[1] = null;
  5642. this._blendFunctionParameters[2] = null;
  5643. this._blendFunctionParameters[3] = null;
  5644. this._isAlphaBlendDirty = true;
  5645. this._isBlendFunctionParametersDirty = false;
  5646. };
  5647. _AlphaState.prototype.apply = function (gl) {
  5648. if (!this.isDirty) {
  5649. return;
  5650. }
  5651. // Alpha blend
  5652. if (this._isAlphaBlendDirty) {
  5653. if (this._alphaBlend) {
  5654. gl.enable(gl.BLEND);
  5655. }
  5656. else {
  5657. gl.disable(gl.BLEND);
  5658. }
  5659. this._isAlphaBlendDirty = false;
  5660. }
  5661. // Alpha function
  5662. if (this._isBlendFunctionParametersDirty) {
  5663. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5664. this._isBlendFunctionParametersDirty = false;
  5665. }
  5666. };
  5667. return _AlphaState;
  5668. })();
  5669. Internals._AlphaState = _AlphaState;
  5670. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5671. })(BABYLON || (BABYLON = {}));
  5672. var BABYLON;
  5673. (function (BABYLON) {
  5674. var Internals;
  5675. (function (Internals) {
  5676. var _DepthCullingState = (function () {
  5677. function _DepthCullingState() {
  5678. this._isDepthTestDirty = false;
  5679. this._isDepthMaskDirty = false;
  5680. this._isDepthFuncDirty = false;
  5681. this._isCullFaceDirty = false;
  5682. this._isCullDirty = false;
  5683. this._isZOffsetDirty = false;
  5684. }
  5685. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5686. get: function () {
  5687. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5693. get: function () {
  5694. return this._zOffset;
  5695. },
  5696. set: function (value) {
  5697. if (this._zOffset === value) {
  5698. return;
  5699. }
  5700. this._zOffset = value;
  5701. this._isZOffsetDirty = true;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5707. get: function () {
  5708. return this._cullFace;
  5709. },
  5710. set: function (value) {
  5711. if (this._cullFace === value) {
  5712. return;
  5713. }
  5714. this._cullFace = value;
  5715. this._isCullFaceDirty = true;
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5721. get: function () {
  5722. return this._cull;
  5723. },
  5724. set: function (value) {
  5725. if (this._cull === value) {
  5726. return;
  5727. }
  5728. this._cull = value;
  5729. this._isCullDirty = true;
  5730. },
  5731. enumerable: true,
  5732. configurable: true
  5733. });
  5734. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5735. get: function () {
  5736. return this._depthFunc;
  5737. },
  5738. set: function (value) {
  5739. if (this._depthFunc === value) {
  5740. return;
  5741. }
  5742. this._depthFunc = value;
  5743. this._isDepthFuncDirty = true;
  5744. },
  5745. enumerable: true,
  5746. configurable: true
  5747. });
  5748. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5749. get: function () {
  5750. return this._depthMask;
  5751. },
  5752. set: function (value) {
  5753. if (this._depthMask === value) {
  5754. return;
  5755. }
  5756. this._depthMask = value;
  5757. this._isDepthMaskDirty = true;
  5758. },
  5759. enumerable: true,
  5760. configurable: true
  5761. });
  5762. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5763. get: function () {
  5764. return this._depthTest;
  5765. },
  5766. set: function (value) {
  5767. if (this._depthTest === value) {
  5768. return;
  5769. }
  5770. this._depthTest = value;
  5771. this._isDepthTestDirty = true;
  5772. },
  5773. enumerable: true,
  5774. configurable: true
  5775. });
  5776. _DepthCullingState.prototype.reset = function () {
  5777. this._depthMask = true;
  5778. this._depthTest = true;
  5779. this._depthFunc = null;
  5780. this._cullFace = null;
  5781. this._cull = null;
  5782. this._zOffset = 0;
  5783. this._isDepthTestDirty = true;
  5784. this._isDepthMaskDirty = true;
  5785. this._isDepthFuncDirty = false;
  5786. this._isCullFaceDirty = false;
  5787. this._isCullDirty = false;
  5788. this._isZOffsetDirty = false;
  5789. };
  5790. _DepthCullingState.prototype.apply = function (gl) {
  5791. if (!this.isDirty) {
  5792. return;
  5793. }
  5794. // Cull
  5795. if (this._isCullDirty) {
  5796. if (this.cull) {
  5797. gl.enable(gl.CULL_FACE);
  5798. }
  5799. else {
  5800. gl.disable(gl.CULL_FACE);
  5801. }
  5802. this._isCullDirty = false;
  5803. }
  5804. // Cull face
  5805. if (this._isCullFaceDirty) {
  5806. gl.cullFace(this.cullFace);
  5807. this._isCullFaceDirty = false;
  5808. }
  5809. // Depth mask
  5810. if (this._isDepthMaskDirty) {
  5811. gl.depthMask(this.depthMask);
  5812. this._isDepthMaskDirty = false;
  5813. }
  5814. // Depth test
  5815. if (this._isDepthTestDirty) {
  5816. if (this.depthTest) {
  5817. gl.enable(gl.DEPTH_TEST);
  5818. }
  5819. else {
  5820. gl.disable(gl.DEPTH_TEST);
  5821. }
  5822. this._isDepthTestDirty = false;
  5823. }
  5824. // Depth func
  5825. if (this._isDepthFuncDirty) {
  5826. gl.depthFunc(this.depthFunc);
  5827. this._isDepthFuncDirty = false;
  5828. }
  5829. // zOffset
  5830. if (this._isZOffsetDirty) {
  5831. if (this.zOffset) {
  5832. gl.enable(gl.POLYGON_OFFSET_FILL);
  5833. gl.polygonOffset(this.zOffset, 0);
  5834. }
  5835. else {
  5836. gl.disable(gl.POLYGON_OFFSET_FILL);
  5837. }
  5838. this._isZOffsetDirty = false;
  5839. }
  5840. };
  5841. return _DepthCullingState;
  5842. })();
  5843. Internals._DepthCullingState = _DepthCullingState;
  5844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5845. })(BABYLON || (BABYLON = {}));
  5846. var BABYLON;
  5847. (function (BABYLON) {
  5848. var compileShader = function (gl, source, type, defines) {
  5849. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5850. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5851. gl.compileShader(shader);
  5852. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5853. throw new Error(gl.getShaderInfoLog(shader));
  5854. }
  5855. return shader;
  5856. };
  5857. var getWebGLTextureType = function (gl, type) {
  5858. var textureType = gl.UNSIGNED_BYTE;
  5859. if (type === Engine.TEXTURETYPE_FLOAT)
  5860. textureType = gl.FLOAT;
  5861. return textureType;
  5862. };
  5863. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5864. var magFilter = gl.NEAREST;
  5865. var minFilter = gl.NEAREST;
  5866. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5867. magFilter = gl.LINEAR;
  5868. if (generateMipMaps) {
  5869. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5870. }
  5871. else {
  5872. minFilter = gl.LINEAR;
  5873. }
  5874. }
  5875. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5876. magFilter = gl.LINEAR;
  5877. if (generateMipMaps) {
  5878. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5879. }
  5880. else {
  5881. minFilter = gl.LINEAR;
  5882. }
  5883. }
  5884. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5885. magFilter = gl.NEAREST;
  5886. if (generateMipMaps) {
  5887. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5888. }
  5889. else {
  5890. minFilter = gl.NEAREST;
  5891. }
  5892. }
  5893. return {
  5894. min: minFilter,
  5895. mag: magFilter
  5896. };
  5897. };
  5898. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5900. var engine = scene.getEngine();
  5901. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5902. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5903. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5904. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5905. texture._baseWidth = width;
  5906. texture._baseHeight = height;
  5907. texture._width = potWidth;
  5908. texture._height = potHeight;
  5909. texture.isReady = true;
  5910. processFunction(potWidth, potHeight);
  5911. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5914. if (!noMipmap && !isCompressed) {
  5915. gl.generateMipmap(gl.TEXTURE_2D);
  5916. }
  5917. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5918. engine.resetTextureCache();
  5919. scene._removePendingData(texture);
  5920. if (onLoad) {
  5921. onLoad();
  5922. }
  5923. };
  5924. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5925. var img;
  5926. var onload = function () {
  5927. loadedImages[index] = img;
  5928. loadedImages._internalCount++;
  5929. scene._removePendingData(img);
  5930. if (loadedImages._internalCount === 6) {
  5931. onfinish(loadedImages);
  5932. }
  5933. };
  5934. var onerror = function () {
  5935. scene._removePendingData(img);
  5936. };
  5937. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5938. scene._addPendingData(img);
  5939. };
  5940. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5941. var loadedImages = [];
  5942. loadedImages._internalCount = 0;
  5943. for (var index = 0; index < 6; index++) {
  5944. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5945. }
  5946. };
  5947. var InstancingAttributeInfo = (function () {
  5948. function InstancingAttributeInfo() {
  5949. }
  5950. return InstancingAttributeInfo;
  5951. })();
  5952. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5953. var EngineCapabilities = (function () {
  5954. function EngineCapabilities() {
  5955. }
  5956. return EngineCapabilities;
  5957. })();
  5958. BABYLON.EngineCapabilities = EngineCapabilities;
  5959. /**
  5960. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5961. */
  5962. var Engine = (function () {
  5963. /**
  5964. * @constructor
  5965. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5966. * @param {boolean} [antialias] - enable antialias
  5967. * @param options - further options to be sent to the getContext function
  5968. */
  5969. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5970. var _this = this;
  5971. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5972. // Public members
  5973. this.isFullscreen = false;
  5974. this.isPointerLock = false;
  5975. this.cullBackFaces = true;
  5976. this.renderEvenInBackground = true;
  5977. // To enable/disable IDB support and avoid XHR on .manifest
  5978. this.enableOfflineSupport = true;
  5979. this.scenes = new Array();
  5980. this._windowIsBackground = false;
  5981. this._webGLVersion = "1.0";
  5982. this._drawCalls = new BABYLON.PerfCounter();
  5983. this._renderingQueueLaunched = false;
  5984. this._activeRenderLoops = [];
  5985. // FPS
  5986. this.fpsRange = 60;
  5987. this.previousFramesDuration = [];
  5988. this.fps = 60;
  5989. this.deltaTime = 0;
  5990. // States
  5991. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5992. this._alphaState = new BABYLON.Internals._AlphaState();
  5993. this._alphaMode = Engine.ALPHA_DISABLE;
  5994. // Cache
  5995. this._loadedTexturesCache = new Array();
  5996. this._maxTextureChannels = 16;
  5997. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5998. this._compiledEffects = {};
  5999. this._uintIndicesCurrentlySet = false;
  6000. this._currentBoundBuffer = new Array();
  6001. this._currentBufferPointers = [];
  6002. this._currentInstanceLocations = new Array();
  6003. this._currentInstanceBuffers = new Array();
  6004. this._renderingCanvas = canvas;
  6005. this._externalData = new BABYLON.StringDictionary();
  6006. options = options || {};
  6007. options.antialias = antialias;
  6008. if (options.preserveDrawingBuffer === undefined) {
  6009. options.preserveDrawingBuffer = false;
  6010. }
  6011. // GL
  6012. //try {
  6013. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6014. // if (this._gl) {
  6015. // this._webGLVersion = "2.0";
  6016. // }
  6017. //} catch (e) {
  6018. // // Do nothing
  6019. //}
  6020. if (!this._gl) {
  6021. try {
  6022. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6023. }
  6024. catch (e) {
  6025. throw new Error("WebGL not supported");
  6026. }
  6027. }
  6028. if (!this._gl) {
  6029. throw new Error("WebGL not supported");
  6030. }
  6031. this._onBlur = function () {
  6032. _this._windowIsBackground = true;
  6033. };
  6034. this._onFocus = function () {
  6035. _this._windowIsBackground = false;
  6036. };
  6037. window.addEventListener("blur", this._onBlur);
  6038. window.addEventListener("focus", this._onFocus);
  6039. // Viewport
  6040. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6041. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6042. this.resize();
  6043. // Caps
  6044. this._caps = new EngineCapabilities();
  6045. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6046. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6047. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6048. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6049. // Infos
  6050. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6051. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6052. if (rendererInfo != null) {
  6053. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6054. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6055. }
  6056. if (!this._glVendor) {
  6057. this._glVendor = "Unknown vendor";
  6058. }
  6059. if (!this._glRenderer) {
  6060. this._glRenderer = "Unknown renderer";
  6061. }
  6062. // Extensions
  6063. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6064. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6065. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6066. 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');
  6067. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6068. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6069. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6070. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6071. this._caps.highPrecisionShaderSupported = true;
  6072. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6073. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6074. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6075. if (this._gl.getShaderPrecisionFormat) {
  6076. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6077. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6078. }
  6079. // Depth buffer
  6080. this.setDepthBuffer(true);
  6081. this.setDepthFunctionToLessOrEqual();
  6082. this.setDepthWrite(true);
  6083. // Fullscreen
  6084. this._onFullscreenChange = function () {
  6085. if (document.fullscreen !== undefined) {
  6086. _this.isFullscreen = document.fullscreen;
  6087. }
  6088. else if (document.mozFullScreen !== undefined) {
  6089. _this.isFullscreen = document.mozFullScreen;
  6090. }
  6091. else if (document.webkitIsFullScreen !== undefined) {
  6092. _this.isFullscreen = document.webkitIsFullScreen;
  6093. }
  6094. else if (document.msIsFullScreen !== undefined) {
  6095. _this.isFullscreen = document.msIsFullScreen;
  6096. }
  6097. // Pointer lock
  6098. if (_this.isFullscreen && _this._pointerLockRequested) {
  6099. canvas.requestPointerLock = canvas.requestPointerLock ||
  6100. canvas.msRequestPointerLock ||
  6101. canvas.mozRequestPointerLock ||
  6102. canvas.webkitRequestPointerLock;
  6103. if (canvas.requestPointerLock) {
  6104. canvas.requestPointerLock();
  6105. }
  6106. }
  6107. };
  6108. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6109. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6110. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6111. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6112. // Pointer lock
  6113. this._onPointerLockChange = function () {
  6114. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6115. document.webkitPointerLockElement === canvas ||
  6116. document.msPointerLockElement === canvas ||
  6117. document.pointerLockElement === canvas);
  6118. };
  6119. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6120. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6121. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6122. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6123. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6124. Engine.audioEngine = new BABYLON.AudioEngine();
  6125. }
  6126. //default loading screen
  6127. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6128. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6129. }
  6130. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6131. get: function () {
  6132. return Engine._ALPHA_DISABLE;
  6133. },
  6134. enumerable: true,
  6135. configurable: true
  6136. });
  6137. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6138. get: function () {
  6139. return Engine._ALPHA_ONEONE;
  6140. },
  6141. enumerable: true,
  6142. configurable: true
  6143. });
  6144. Object.defineProperty(Engine, "ALPHA_ADD", {
  6145. get: function () {
  6146. return Engine._ALPHA_ADD;
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6152. get: function () {
  6153. return Engine._ALPHA_COMBINE;
  6154. },
  6155. enumerable: true,
  6156. configurable: true
  6157. });
  6158. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6159. get: function () {
  6160. return Engine._ALPHA_SUBTRACT;
  6161. },
  6162. enumerable: true,
  6163. configurable: true
  6164. });
  6165. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6166. get: function () {
  6167. return Engine._ALPHA_MULTIPLY;
  6168. },
  6169. enumerable: true,
  6170. configurable: true
  6171. });
  6172. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6173. get: function () {
  6174. return Engine._ALPHA_MAXIMIZED;
  6175. },
  6176. enumerable: true,
  6177. configurable: true
  6178. });
  6179. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6180. get: function () {
  6181. return Engine._DELAYLOADSTATE_NONE;
  6182. },
  6183. enumerable: true,
  6184. configurable: true
  6185. });
  6186. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6187. get: function () {
  6188. return Engine._DELAYLOADSTATE_LOADED;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6194. get: function () {
  6195. return Engine._DELAYLOADSTATE_LOADING;
  6196. },
  6197. enumerable: true,
  6198. configurable: true
  6199. });
  6200. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6201. get: function () {
  6202. return Engine._DELAYLOADSTATE_NOTLOADED;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6208. get: function () {
  6209. return Engine._TEXTUREFORMAT_ALPHA;
  6210. },
  6211. enumerable: true,
  6212. configurable: true
  6213. });
  6214. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6215. get: function () {
  6216. return Engine._TEXTUREFORMAT_LUMINANCE;
  6217. },
  6218. enumerable: true,
  6219. configurable: true
  6220. });
  6221. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6222. get: function () {
  6223. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6224. },
  6225. enumerable: true,
  6226. configurable: true
  6227. });
  6228. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6229. get: function () {
  6230. return Engine._TEXTUREFORMAT_RGB;
  6231. },
  6232. enumerable: true,
  6233. configurable: true
  6234. });
  6235. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6236. get: function () {
  6237. return Engine._TEXTUREFORMAT_RGBA;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6243. get: function () {
  6244. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6245. },
  6246. enumerable: true,
  6247. configurable: true
  6248. });
  6249. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6250. get: function () {
  6251. return Engine._TEXTURETYPE_FLOAT;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. Object.defineProperty(Engine, "Version", {
  6257. get: function () {
  6258. return "2.5-alpha";
  6259. },
  6260. enumerable: true,
  6261. configurable: true
  6262. });
  6263. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6264. get: function () {
  6265. return this._webGLVersion;
  6266. },
  6267. enumerable: true,
  6268. configurable: true
  6269. });
  6270. Engine.prototype._prepareWorkingCanvas = function () {
  6271. if (this._workingCanvas) {
  6272. return;
  6273. }
  6274. this._workingCanvas = document.createElement("canvas");
  6275. this._workingContext = this._workingCanvas.getContext("2d");
  6276. };
  6277. Engine.prototype.resetTextureCache = function () {
  6278. for (var index = 0; index < this._maxTextureChannels; index++) {
  6279. this._activeTexturesCache[index] = null;
  6280. }
  6281. };
  6282. Engine.prototype.getGlInfo = function () {
  6283. return {
  6284. vendor: this._glVendor,
  6285. renderer: this._glRenderer,
  6286. version: this._glVersion
  6287. };
  6288. };
  6289. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6290. if (useScreen === void 0) { useScreen = false; }
  6291. var viewport = camera.viewport;
  6292. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6293. };
  6294. Engine.prototype.getRenderWidth = function (useScreen) {
  6295. if (useScreen === void 0) { useScreen = false; }
  6296. if (!useScreen && this._currentRenderTarget) {
  6297. return this._currentRenderTarget._width;
  6298. }
  6299. return this._renderingCanvas.width;
  6300. };
  6301. Engine.prototype.getRenderHeight = function (useScreen) {
  6302. if (useScreen === void 0) { useScreen = false; }
  6303. if (!useScreen && this._currentRenderTarget) {
  6304. return this._currentRenderTarget._height;
  6305. }
  6306. return this._renderingCanvas.height;
  6307. };
  6308. Engine.prototype.getRenderingCanvas = function () {
  6309. return this._renderingCanvas;
  6310. };
  6311. Engine.prototype.getRenderingCanvasClientRect = function () {
  6312. return this._renderingCanvas.getBoundingClientRect();
  6313. };
  6314. Engine.prototype.setHardwareScalingLevel = function (level) {
  6315. this._hardwareScalingLevel = level;
  6316. this.resize();
  6317. };
  6318. Engine.prototype.getHardwareScalingLevel = function () {
  6319. return this._hardwareScalingLevel;
  6320. };
  6321. Engine.prototype.getLoadedTexturesCache = function () {
  6322. return this._loadedTexturesCache;
  6323. };
  6324. Engine.prototype.getCaps = function () {
  6325. return this._caps;
  6326. };
  6327. Object.defineProperty(Engine.prototype, "drawCalls", {
  6328. get: function () {
  6329. return this._drawCalls.current;
  6330. },
  6331. enumerable: true,
  6332. configurable: true
  6333. });
  6334. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6335. get: function () {
  6336. return this._drawCalls;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. Engine.prototype.getDepthFunction = function () {
  6342. return this._depthCullingState.depthFunc;
  6343. };
  6344. Engine.prototype.setDepthFunction = function (depthFunc) {
  6345. this._depthCullingState.depthFunc = depthFunc;
  6346. };
  6347. Engine.prototype.setDepthFunctionToGreater = function () {
  6348. this._depthCullingState.depthFunc = this._gl.GREATER;
  6349. };
  6350. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6351. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6352. };
  6353. Engine.prototype.setDepthFunctionToLess = function () {
  6354. this._depthCullingState.depthFunc = this._gl.LESS;
  6355. };
  6356. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6357. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6358. };
  6359. /**
  6360. * stop executing a render loop function and remove it from the execution array
  6361. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6362. */
  6363. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6364. if (!renderFunction) {
  6365. this._activeRenderLoops = [];
  6366. return;
  6367. }
  6368. var index = this._activeRenderLoops.indexOf(renderFunction);
  6369. if (index >= 0) {
  6370. this._activeRenderLoops.splice(index, 1);
  6371. }
  6372. };
  6373. Engine.prototype._renderLoop = function () {
  6374. var shouldRender = true;
  6375. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6376. shouldRender = false;
  6377. }
  6378. if (shouldRender) {
  6379. // Start new frame
  6380. this.beginFrame();
  6381. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6382. var renderFunction = this._activeRenderLoops[index];
  6383. renderFunction();
  6384. }
  6385. // Present
  6386. this.endFrame();
  6387. }
  6388. if (this._activeRenderLoops.length > 0) {
  6389. // Register new frame
  6390. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6391. }
  6392. else {
  6393. this._renderingQueueLaunched = false;
  6394. }
  6395. };
  6396. /**
  6397. * Register and execute a render loop. The engine can have more than one render function.
  6398. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6399. * @example
  6400. * engine.runRenderLoop(function () {
  6401. * scene.render()
  6402. * })
  6403. */
  6404. Engine.prototype.runRenderLoop = function (renderFunction) {
  6405. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6406. return;
  6407. }
  6408. this._activeRenderLoops.push(renderFunction);
  6409. if (!this._renderingQueueLaunched) {
  6410. this._renderingQueueLaunched = true;
  6411. this._bindedRenderFunction = this._renderLoop.bind(this);
  6412. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6413. }
  6414. };
  6415. /**
  6416. * Toggle full screen mode.
  6417. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6418. * @param {any} options - an options object to be sent to the requestFullscreen function
  6419. */
  6420. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6421. if (this.isFullscreen) {
  6422. BABYLON.Tools.ExitFullscreen();
  6423. }
  6424. else {
  6425. this._pointerLockRequested = requestPointerLock;
  6426. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6427. }
  6428. };
  6429. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6430. this.applyStates();
  6431. if (backBuffer) {
  6432. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6433. }
  6434. if (depthStencil && this._depthCullingState.depthMask) {
  6435. this._gl.clearDepth(1.0);
  6436. }
  6437. var mode = 0;
  6438. if (backBuffer) {
  6439. mode |= this._gl.COLOR_BUFFER_BIT;
  6440. }
  6441. if (depthStencil && this._depthCullingState.depthMask) {
  6442. mode |= this._gl.DEPTH_BUFFER_BIT;
  6443. }
  6444. this._gl.clear(mode);
  6445. };
  6446. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6447. var gl = this._gl;
  6448. // Save state
  6449. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6450. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6451. // Change state
  6452. gl.enable(gl.SCISSOR_TEST);
  6453. gl.scissor(x, y, width, height);
  6454. // Clear
  6455. this.clear(clearColor, true, true);
  6456. // Restore state
  6457. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6458. if (curScissor === true) {
  6459. gl.enable(gl.SCISSOR_TEST);
  6460. }
  6461. else {
  6462. gl.disable(gl.SCISSOR_TEST);
  6463. }
  6464. };
  6465. /**
  6466. * Set the WebGL's viewport
  6467. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6468. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6469. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6470. */
  6471. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6472. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6473. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6474. var x = viewport.x || 0;
  6475. var y = viewport.y || 0;
  6476. this._cachedViewport = viewport;
  6477. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6478. };
  6479. /**
  6480. * Directly set the WebGL Viewport
  6481. * The x, y, width & height are directly passed to the WebGL call
  6482. * @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.
  6483. */
  6484. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6485. var currentViewport = this._cachedViewport;
  6486. this._cachedViewport = null;
  6487. this._gl.viewport(x, y, width, height);
  6488. return currentViewport;
  6489. };
  6490. Engine.prototype.beginFrame = function () {
  6491. this._measureFps();
  6492. };
  6493. Engine.prototype.endFrame = function () {
  6494. //this.flushFramebuffer();
  6495. };
  6496. /**
  6497. * resize the view according to the canvas' size.
  6498. * @example
  6499. * window.addEventListener("resize", function () {
  6500. * engine.resize();
  6501. * });
  6502. */
  6503. Engine.prototype.resize = function () {
  6504. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6505. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6506. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6507. for (var index = 0; index < this.scenes.length; index++) {
  6508. var scene = this.scenes[index];
  6509. if (scene.debugLayer.isVisible()) {
  6510. scene.debugLayer._syncPositions();
  6511. }
  6512. }
  6513. };
  6514. /**
  6515. * force a specific size of the canvas
  6516. * @param {number} width - the new canvas' width
  6517. * @param {number} height - the new canvas' height
  6518. */
  6519. Engine.prototype.setSize = function (width, height) {
  6520. this._renderingCanvas.width = width;
  6521. this._renderingCanvas.height = height;
  6522. for (var index = 0; index < this.scenes.length; index++) {
  6523. var scene = this.scenes[index];
  6524. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6525. var cam = scene.cameras[camIndex];
  6526. cam._currentRenderId = 0;
  6527. }
  6528. }
  6529. };
  6530. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6531. this._currentRenderTarget = texture;
  6532. var gl = this._gl;
  6533. this.bindUnboundFramebuffer(texture._framebuffer);
  6534. if (texture.isCube) {
  6535. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6536. }
  6537. else {
  6538. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6539. }
  6540. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6541. this.wipeCaches();
  6542. };
  6543. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6544. if (this._currentFramebuffer !== framebuffer) {
  6545. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6546. this._currentFramebuffer = framebuffer;
  6547. }
  6548. };
  6549. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6550. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6551. this._currentRenderTarget = null;
  6552. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6553. var gl = this._gl;
  6554. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6555. gl.generateMipmap(gl.TEXTURE_2D);
  6556. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6557. }
  6558. this.bindUnboundFramebuffer(null);
  6559. };
  6560. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6561. if (texture.generateMipMaps) {
  6562. var gl = this._gl;
  6563. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6564. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6565. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6566. }
  6567. };
  6568. Engine.prototype.flushFramebuffer = function () {
  6569. this._gl.flush();
  6570. };
  6571. Engine.prototype.restoreDefaultFramebuffer = function () {
  6572. this._currentRenderTarget = null;
  6573. this.bindUnboundFramebuffer(null);
  6574. this.setViewport(this._cachedViewport);
  6575. this.wipeCaches();
  6576. };
  6577. // VBOs
  6578. Engine.prototype._resetVertexBufferBinding = function () {
  6579. this.bindArrayBuffer(null);
  6580. this._cachedVertexBuffers = null;
  6581. };
  6582. Engine.prototype.createVertexBuffer = function (vertices) {
  6583. var vbo = this._gl.createBuffer();
  6584. this.bindArrayBuffer(vbo);
  6585. if (vertices instanceof Float32Array) {
  6586. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6587. }
  6588. else {
  6589. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6590. }
  6591. this._resetVertexBufferBinding();
  6592. vbo.references = 1;
  6593. return vbo;
  6594. };
  6595. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6596. var vbo = this._gl.createBuffer();
  6597. this.bindArrayBuffer(vbo);
  6598. if (vertices instanceof Float32Array) {
  6599. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6600. }
  6601. else {
  6602. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6603. }
  6604. this._resetVertexBufferBinding();
  6605. vbo.references = 1;
  6606. return vbo;
  6607. };
  6608. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6609. this.bindArrayBuffer(vertexBuffer);
  6610. if (offset === undefined) {
  6611. offset = 0;
  6612. }
  6613. if (count === undefined) {
  6614. if (vertices instanceof Float32Array) {
  6615. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6616. }
  6617. else {
  6618. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6619. }
  6620. }
  6621. else {
  6622. if (vertices instanceof Float32Array) {
  6623. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6624. }
  6625. else {
  6626. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6627. }
  6628. }
  6629. this._resetVertexBufferBinding();
  6630. };
  6631. Engine.prototype._resetIndexBufferBinding = function () {
  6632. this.bindIndexBuffer(null);
  6633. this._cachedIndexBuffer = null;
  6634. };
  6635. Engine.prototype.createIndexBuffer = function (indices) {
  6636. var vbo = this._gl.createBuffer();
  6637. this.bindIndexBuffer(vbo);
  6638. // Check for 32 bits indices
  6639. var arrayBuffer;
  6640. var need32Bits = false;
  6641. if (this._caps.uintIndices) {
  6642. for (var index = 0; index < indices.length; index++) {
  6643. if (indices[index] > 65535) {
  6644. need32Bits = true;
  6645. break;
  6646. }
  6647. }
  6648. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6649. }
  6650. else {
  6651. arrayBuffer = new Uint16Array(indices);
  6652. }
  6653. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6654. this._resetIndexBufferBinding();
  6655. vbo.references = 1;
  6656. vbo.is32Bits = need32Bits;
  6657. return vbo;
  6658. };
  6659. Engine.prototype.bindArrayBuffer = function (buffer) {
  6660. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6661. };
  6662. Engine.prototype.bindIndexBuffer = function (buffer) {
  6663. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6664. };
  6665. Engine.prototype.bindBuffer = function (buffer, target) {
  6666. if (this._currentBoundBuffer[target] !== buffer) {
  6667. this._gl.bindBuffer(target, buffer);
  6668. this._currentBoundBuffer[target] = buffer;
  6669. }
  6670. };
  6671. Engine.prototype.updateArrayBuffer = function (data) {
  6672. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6673. };
  6674. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6675. var pointer = this._currentBufferPointers[indx];
  6676. var changed = false;
  6677. if (!pointer) {
  6678. changed = true;
  6679. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6680. }
  6681. else {
  6682. if (pointer.buffer !== buffer) {
  6683. pointer.buffer = buffer;
  6684. changed = true;
  6685. }
  6686. if (pointer.size !== size) {
  6687. pointer.size = size;
  6688. changed = true;
  6689. }
  6690. if (pointer.type !== type) {
  6691. pointer.type = type;
  6692. changed = true;
  6693. }
  6694. if (pointer.normalized !== normalized) {
  6695. pointer.normalized = normalized;
  6696. changed = true;
  6697. }
  6698. if (pointer.stride !== stride) {
  6699. pointer.stride = stride;
  6700. changed = true;
  6701. }
  6702. if (pointer.offset !== offset) {
  6703. pointer.offset = offset;
  6704. changed = true;
  6705. }
  6706. }
  6707. if (changed) {
  6708. this.bindArrayBuffer(buffer);
  6709. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6710. }
  6711. };
  6712. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6713. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6714. this._cachedVertexBuffers = vertexBuffer;
  6715. this._cachedEffectForVertexBuffers = effect;
  6716. var offset = 0;
  6717. for (var index = 0; index < vertexDeclaration.length; index++) {
  6718. var order = effect.getAttributeLocation(index);
  6719. if (order >= 0) {
  6720. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6721. }
  6722. offset += vertexDeclaration[index] * 4;
  6723. }
  6724. }
  6725. if (this._cachedIndexBuffer !== indexBuffer) {
  6726. this._cachedIndexBuffer = indexBuffer;
  6727. this.bindIndexBuffer(indexBuffer);
  6728. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6729. }
  6730. };
  6731. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6732. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6733. this._cachedVertexBuffers = vertexBuffers;
  6734. this._cachedEffectForVertexBuffers = effect;
  6735. var attributes = effect.getAttributesNames();
  6736. for (var index = 0; index < attributes.length; index++) {
  6737. var order = effect.getAttributeLocation(index);
  6738. if (order >= 0) {
  6739. var vertexBuffer = vertexBuffers[attributes[index]];
  6740. if (!vertexBuffer) {
  6741. continue;
  6742. }
  6743. var buffer = vertexBuffer.getBuffer();
  6744. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6745. if (vertexBuffer.getIsInstanced()) {
  6746. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6747. this._currentInstanceLocations.push(order);
  6748. this._currentInstanceBuffers.push(buffer);
  6749. }
  6750. }
  6751. }
  6752. }
  6753. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6754. this._cachedIndexBuffer = indexBuffer;
  6755. this.bindIndexBuffer(indexBuffer);
  6756. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6757. }
  6758. };
  6759. Engine.prototype.unbindInstanceAttributes = function () {
  6760. var boundBuffer;
  6761. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6762. var instancesBuffer = this._currentInstanceBuffers[i];
  6763. if (boundBuffer != instancesBuffer) {
  6764. boundBuffer = instancesBuffer;
  6765. this.bindArrayBuffer(instancesBuffer);
  6766. }
  6767. var offsetLocation = this._currentInstanceLocations[i];
  6768. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6769. }
  6770. this._currentInstanceBuffers.length = 0;
  6771. this._currentInstanceLocations.length = 0;
  6772. };
  6773. Engine.prototype._releaseBuffer = function (buffer) {
  6774. buffer.references--;
  6775. if (buffer.references === 0) {
  6776. this._gl.deleteBuffer(buffer);
  6777. return true;
  6778. }
  6779. return false;
  6780. };
  6781. Engine.prototype.createInstancesBuffer = function (capacity) {
  6782. var buffer = this._gl.createBuffer();
  6783. buffer.capacity = capacity;
  6784. this.bindArrayBuffer(buffer);
  6785. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6786. return buffer;
  6787. };
  6788. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6789. this._gl.deleteBuffer(buffer);
  6790. };
  6791. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6792. this.bindArrayBuffer(instancesBuffer);
  6793. if (data) {
  6794. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6795. }
  6796. if (offsetLocations[0].index !== undefined) {
  6797. var stride = 0;
  6798. for (var i = 0; i < offsetLocations.length; i++) {
  6799. var ai = offsetLocations[i];
  6800. stride += ai.attributeSize * 4;
  6801. }
  6802. for (var i = 0; i < offsetLocations.length; i++) {
  6803. var ai = offsetLocations[i];
  6804. this._gl.enableVertexAttribArray(ai.index);
  6805. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6806. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6807. this._currentInstanceLocations.push(ai.index);
  6808. this._currentInstanceBuffers.push(instancesBuffer);
  6809. }
  6810. }
  6811. else {
  6812. for (var index = 0; index < 4; index++) {
  6813. var offsetLocation = offsetLocations[index];
  6814. this._gl.enableVertexAttribArray(offsetLocation);
  6815. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6816. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6817. this._currentInstanceLocations.push(offsetLocation);
  6818. this._currentInstanceBuffers.push(instancesBuffer);
  6819. }
  6820. }
  6821. };
  6822. Engine.prototype.applyStates = function () {
  6823. this._depthCullingState.apply(this._gl);
  6824. this._alphaState.apply(this._gl);
  6825. };
  6826. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6827. // Apply states
  6828. this.applyStates();
  6829. this._drawCalls.addCount(1, false);
  6830. // Render
  6831. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6832. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6833. if (instancesCount) {
  6834. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6835. return;
  6836. }
  6837. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6838. };
  6839. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6840. // Apply states
  6841. this.applyStates();
  6842. this._drawCalls.addCount(1, false);
  6843. if (instancesCount) {
  6844. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6845. return;
  6846. }
  6847. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6848. };
  6849. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6850. // Apply states
  6851. this.applyStates();
  6852. this._drawCalls.addCount(1, false);
  6853. if (instancesCount) {
  6854. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6855. return;
  6856. }
  6857. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6858. };
  6859. // Shaders
  6860. Engine.prototype._releaseEffect = function (effect) {
  6861. if (this._compiledEffects[effect._key]) {
  6862. delete this._compiledEffects[effect._key];
  6863. if (effect.getProgram()) {
  6864. this._gl.deleteProgram(effect.getProgram());
  6865. }
  6866. }
  6867. };
  6868. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6869. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6870. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6871. var name = vertex + "+" + fragment + "@" + defines;
  6872. if (this._compiledEffects[name]) {
  6873. return this._compiledEffects[name];
  6874. }
  6875. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6876. effect._key = name;
  6877. this._compiledEffects[name] = effect;
  6878. return effect;
  6879. };
  6880. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6881. if (uniformsNames === void 0) { uniformsNames = []; }
  6882. if (samplers === void 0) { samplers = []; }
  6883. if (defines === void 0) { defines = ""; }
  6884. return this.createEffect({
  6885. vertex: "particles",
  6886. fragmentElement: fragmentName
  6887. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6888. };
  6889. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6890. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6891. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6892. var shaderProgram = this._gl.createProgram();
  6893. this._gl.attachShader(shaderProgram, vertexShader);
  6894. this._gl.attachShader(shaderProgram, fragmentShader);
  6895. this._gl.linkProgram(shaderProgram);
  6896. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6897. if (!linked) {
  6898. var error = this._gl.getProgramInfoLog(shaderProgram);
  6899. if (error) {
  6900. throw new Error(error);
  6901. }
  6902. }
  6903. this._gl.deleteShader(vertexShader);
  6904. this._gl.deleteShader(fragmentShader);
  6905. return shaderProgram;
  6906. };
  6907. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6908. var results = [];
  6909. for (var index = 0; index < uniformsNames.length; index++) {
  6910. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6911. }
  6912. return results;
  6913. };
  6914. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6915. var results = [];
  6916. for (var index = 0; index < attributesNames.length; index++) {
  6917. try {
  6918. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6919. }
  6920. catch (e) {
  6921. results.push(-1);
  6922. }
  6923. }
  6924. return results;
  6925. };
  6926. Engine.prototype.enableEffect = function (effect) {
  6927. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6928. if (effect && effect.onBind) {
  6929. effect.onBind(effect);
  6930. }
  6931. return;
  6932. }
  6933. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6934. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6935. // Use program
  6936. this.setProgram(effect.getProgram());
  6937. var i, ul;
  6938. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6939. this._vertexAttribArraysToUse[i] = false;
  6940. }
  6941. var attributesCount = effect.getAttributesCount();
  6942. for (i = 0; i < attributesCount; i++) {
  6943. // Attributes
  6944. var order = effect.getAttributeLocation(i);
  6945. if (order >= 0) {
  6946. this._vertexAttribArraysToUse[order] = true;
  6947. }
  6948. }
  6949. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6950. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6951. continue;
  6952. }
  6953. this._vertexAttribArraysEnabled[i] = false;
  6954. this._gl.disableVertexAttribArray(i);
  6955. }
  6956. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6957. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6958. this._vertexAttribArraysEnabled[i] = true;
  6959. this._gl.enableVertexAttribArray(i);
  6960. }
  6961. }
  6962. this._currentEffect = effect;
  6963. if (effect.onBind) {
  6964. effect.onBind(effect);
  6965. }
  6966. };
  6967. Engine.prototype.setArray = function (uniform, array) {
  6968. if (!uniform)
  6969. return;
  6970. this._gl.uniform1fv(uniform, array);
  6971. };
  6972. Engine.prototype.setArray2 = function (uniform, array) {
  6973. if (!uniform || array.length % 2 !== 0)
  6974. return;
  6975. this._gl.uniform2fv(uniform, array);
  6976. };
  6977. Engine.prototype.setArray3 = function (uniform, array) {
  6978. if (!uniform || array.length % 3 !== 0)
  6979. return;
  6980. this._gl.uniform3fv(uniform, array);
  6981. };
  6982. Engine.prototype.setArray4 = function (uniform, array) {
  6983. if (!uniform || array.length % 4 !== 0)
  6984. return;
  6985. this._gl.uniform4fv(uniform, array);
  6986. };
  6987. Engine.prototype.setMatrices = function (uniform, matrices) {
  6988. if (!uniform)
  6989. return;
  6990. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6991. };
  6992. Engine.prototype.setMatrix = function (uniform, matrix) {
  6993. if (!uniform)
  6994. return;
  6995. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6996. };
  6997. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6998. if (!uniform)
  6999. return;
  7000. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7001. };
  7002. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7003. if (!uniform)
  7004. return;
  7005. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7006. };
  7007. Engine.prototype.setFloat = function (uniform, value) {
  7008. if (!uniform)
  7009. return;
  7010. this._gl.uniform1f(uniform, value);
  7011. };
  7012. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7013. if (!uniform)
  7014. return;
  7015. this._gl.uniform2f(uniform, x, y);
  7016. };
  7017. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7018. if (!uniform)
  7019. return;
  7020. this._gl.uniform3f(uniform, x, y, z);
  7021. };
  7022. Engine.prototype.setBool = function (uniform, bool) {
  7023. if (!uniform)
  7024. return;
  7025. this._gl.uniform1i(uniform, bool);
  7026. };
  7027. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7028. if (!uniform)
  7029. return;
  7030. this._gl.uniform4f(uniform, x, y, z, w);
  7031. };
  7032. Engine.prototype.setColor3 = function (uniform, color3) {
  7033. if (!uniform)
  7034. return;
  7035. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7036. };
  7037. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7038. if (!uniform)
  7039. return;
  7040. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7041. };
  7042. // States
  7043. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7044. if (zOffset === void 0) { zOffset = 0; }
  7045. if (reverseSide === void 0) { reverseSide = false; }
  7046. // Culling
  7047. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7048. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7049. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7050. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7051. if (culling) {
  7052. this._depthCullingState.cullFace = cullFace;
  7053. this._depthCullingState.cull = true;
  7054. }
  7055. else {
  7056. this._depthCullingState.cull = false;
  7057. }
  7058. }
  7059. // Z offset
  7060. this._depthCullingState.zOffset = zOffset;
  7061. };
  7062. Engine.prototype.setDepthBuffer = function (enable) {
  7063. this._depthCullingState.depthTest = enable;
  7064. };
  7065. Engine.prototype.getDepthWrite = function () {
  7066. return this._depthCullingState.depthMask;
  7067. };
  7068. Engine.prototype.setDepthWrite = function (enable) {
  7069. this._depthCullingState.depthMask = enable;
  7070. };
  7071. Engine.prototype.setColorWrite = function (enable) {
  7072. this._gl.colorMask(enable, enable, enable, enable);
  7073. };
  7074. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7075. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7076. if (this._alphaMode === mode) {
  7077. return;
  7078. }
  7079. switch (mode) {
  7080. case Engine.ALPHA_DISABLE:
  7081. this._alphaState.alphaBlend = false;
  7082. break;
  7083. case Engine.ALPHA_COMBINE:
  7084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7085. this._alphaState.alphaBlend = true;
  7086. break;
  7087. case Engine.ALPHA_ONEONE:
  7088. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7089. this._alphaState.alphaBlend = true;
  7090. break;
  7091. case Engine.ALPHA_ADD:
  7092. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7093. this._alphaState.alphaBlend = true;
  7094. break;
  7095. case Engine.ALPHA_SUBTRACT:
  7096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7097. this._alphaState.alphaBlend = true;
  7098. break;
  7099. case Engine.ALPHA_MULTIPLY:
  7100. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7101. this._alphaState.alphaBlend = true;
  7102. break;
  7103. case Engine.ALPHA_MAXIMIZED:
  7104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7105. this._alphaState.alphaBlend = true;
  7106. break;
  7107. }
  7108. if (!noDepthWriteChange) {
  7109. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7110. }
  7111. this._alphaMode = mode;
  7112. };
  7113. Engine.prototype.getAlphaMode = function () {
  7114. return this._alphaMode;
  7115. };
  7116. Engine.prototype.setAlphaTesting = function (enable) {
  7117. this._alphaTest = enable;
  7118. };
  7119. Engine.prototype.getAlphaTesting = function () {
  7120. return this._alphaTest;
  7121. };
  7122. // Textures
  7123. Engine.prototype.wipeCaches = function () {
  7124. this.resetTextureCache();
  7125. this._currentEffect = null;
  7126. this._depthCullingState.reset();
  7127. this.setDepthFunctionToLessOrEqual();
  7128. this._alphaState.reset();
  7129. this._cachedVertexBuffers = null;
  7130. this._cachedIndexBuffer = null;
  7131. this._cachedEffectForVertexBuffers = null;
  7132. };
  7133. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7134. var gl = this._gl;
  7135. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7136. var magFilter = gl.NEAREST;
  7137. var minFilter = gl.NEAREST;
  7138. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7139. magFilter = gl.LINEAR;
  7140. minFilter = gl.LINEAR;
  7141. }
  7142. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7143. magFilter = gl.LINEAR;
  7144. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7145. }
  7146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7148. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7149. texture.samplingMode = samplingMode;
  7150. };
  7151. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7152. var _this = this;
  7153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7154. if (onLoad === void 0) { onLoad = null; }
  7155. if (onError === void 0) { onError = null; }
  7156. if (buffer === void 0) { buffer = null; }
  7157. var texture = this._gl.createTexture();
  7158. var extension;
  7159. var fromData = false;
  7160. if (url.substr(0, 5) === "data:") {
  7161. fromData = true;
  7162. }
  7163. if (!fromData)
  7164. extension = url.substr(url.length - 4, 4).toLowerCase();
  7165. else {
  7166. var oldUrl = url;
  7167. fromData = oldUrl.split(':');
  7168. url = oldUrl;
  7169. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7170. }
  7171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7172. var isTGA = (extension === ".tga");
  7173. scene._addPendingData(texture);
  7174. texture.url = url;
  7175. texture.noMipmap = noMipmap;
  7176. texture.references = 1;
  7177. texture.samplingMode = samplingMode;
  7178. this._loadedTexturesCache.push(texture);
  7179. var onerror = function () {
  7180. scene._removePendingData(texture);
  7181. if (onError) {
  7182. onError();
  7183. }
  7184. };
  7185. var callback;
  7186. if (isTGA) {
  7187. callback = function (arrayBuffer) {
  7188. var data = new Uint8Array(arrayBuffer);
  7189. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7190. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7191. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7192. }, onLoad, samplingMode);
  7193. };
  7194. if (!(fromData instanceof Array))
  7195. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7196. callback(arrayBuffer);
  7197. }, onerror, scene.database, true);
  7198. else
  7199. callback(buffer);
  7200. }
  7201. else if (isDDS) {
  7202. callback = function (data) {
  7203. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7204. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7205. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7206. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7207. }, onLoad, samplingMode);
  7208. };
  7209. if (!(fromData instanceof Array))
  7210. BABYLON.Tools.LoadFile(url, function (data) {
  7211. callback(data);
  7212. }, onerror, scene.database, true);
  7213. else
  7214. callback(buffer);
  7215. }
  7216. else {
  7217. var onload = function (img) {
  7218. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7219. var isPot = (img.width === potWidth && img.height === potHeight);
  7220. if (!isPot) {
  7221. _this._prepareWorkingCanvas();
  7222. _this._workingCanvas.width = potWidth;
  7223. _this._workingCanvas.height = potHeight;
  7224. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7225. _this._workingContext.imageSmoothingEnabled = false;
  7226. _this._workingContext.mozImageSmoothingEnabled = false;
  7227. _this._workingContext.oImageSmoothingEnabled = false;
  7228. _this._workingContext.webkitImageSmoothingEnabled = false;
  7229. _this._workingContext.msImageSmoothingEnabled = false;
  7230. }
  7231. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7232. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7233. _this._workingContext.imageSmoothingEnabled = true;
  7234. _this._workingContext.mozImageSmoothingEnabled = true;
  7235. _this._workingContext.oImageSmoothingEnabled = true;
  7236. _this._workingContext.webkitImageSmoothingEnabled = true;
  7237. _this._workingContext.msImageSmoothingEnabled = true;
  7238. }
  7239. }
  7240. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7241. }, onLoad, samplingMode);
  7242. };
  7243. if (!(fromData instanceof Array))
  7244. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7245. else
  7246. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7247. }
  7248. return texture;
  7249. };
  7250. Engine.prototype._getInternalFormat = function (format) {
  7251. var internalFormat = this._gl.RGBA;
  7252. switch (format) {
  7253. case Engine.TEXTUREFORMAT_ALPHA:
  7254. internalFormat = this._gl.ALPHA;
  7255. break;
  7256. case Engine.TEXTUREFORMAT_LUMINANCE:
  7257. internalFormat = this._gl.LUMINANCE;
  7258. break;
  7259. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7260. internalFormat = this._gl.LUMINANCE_ALPHA;
  7261. break;
  7262. case Engine.TEXTUREFORMAT_RGB:
  7263. internalFormat = this._gl.RGB;
  7264. break;
  7265. case Engine.TEXTUREFORMAT_RGBA:
  7266. internalFormat = this._gl.RGBA;
  7267. break;
  7268. }
  7269. return internalFormat;
  7270. };
  7271. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7272. if (compression === void 0) { compression = null; }
  7273. var internalFormat = this._getInternalFormat(format);
  7274. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7275. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7276. if (texture._width % 4 !== 0) {
  7277. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7278. }
  7279. if (compression) {
  7280. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7281. }
  7282. else {
  7283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7284. }
  7285. if (texture.generateMipMaps) {
  7286. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7287. }
  7288. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7289. this.resetTextureCache();
  7290. texture.isReady = true;
  7291. };
  7292. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7293. if (compression === void 0) { compression = null; }
  7294. var texture = this._gl.createTexture();
  7295. texture._baseWidth = width;
  7296. texture._baseHeight = height;
  7297. texture._width = width;
  7298. texture._height = height;
  7299. texture.references = 1;
  7300. this.updateRawTexture(texture, data, format, invertY, compression);
  7301. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7302. // Filters
  7303. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7306. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7307. texture.samplingMode = samplingMode;
  7308. this._loadedTexturesCache.push(texture);
  7309. return texture;
  7310. };
  7311. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7312. var texture = this._gl.createTexture();
  7313. texture._baseWidth = width;
  7314. texture._baseHeight = height;
  7315. if (generateMipMaps) {
  7316. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7317. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7318. }
  7319. this.resetTextureCache();
  7320. texture._width = width;
  7321. texture._height = height;
  7322. texture.isReady = false;
  7323. texture.generateMipMaps = generateMipMaps;
  7324. texture.references = 1;
  7325. texture.samplingMode = samplingMode;
  7326. this.updateTextureSamplingMode(samplingMode, texture);
  7327. this._loadedTexturesCache.push(texture);
  7328. return texture;
  7329. };
  7330. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7331. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7332. if (texture.isCube) {
  7333. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7334. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7335. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7336. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7337. }
  7338. else {
  7339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7340. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7341. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7342. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7343. }
  7344. };
  7345. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7346. if (premulAlpha === void 0) { premulAlpha = false; }
  7347. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7348. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7349. if (premulAlpha) {
  7350. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7351. }
  7352. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7353. if (texture.generateMipMaps) {
  7354. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7355. }
  7356. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7357. this.resetTextureCache();
  7358. texture.isReady = true;
  7359. };
  7360. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7361. if (texture._isDisabled) {
  7362. return;
  7363. }
  7364. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7365. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7366. try {
  7367. // Testing video texture support
  7368. if (this._videoTextureSupported === undefined) {
  7369. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7370. if (this._gl.getError() !== 0) {
  7371. this._videoTextureSupported = false;
  7372. }
  7373. else {
  7374. this._videoTextureSupported = true;
  7375. }
  7376. }
  7377. // Copy video through the current working canvas if video texture is not supported
  7378. if (!this._videoTextureSupported) {
  7379. if (!texture._workingCanvas) {
  7380. texture._workingCanvas = document.createElement("canvas");
  7381. texture._workingContext = texture._workingCanvas.getContext("2d");
  7382. texture._workingCanvas.width = texture._width;
  7383. texture._workingCanvas.height = texture._height;
  7384. }
  7385. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7386. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7387. }
  7388. else {
  7389. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7390. }
  7391. if (texture.generateMipMaps) {
  7392. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7393. }
  7394. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7395. this.resetTextureCache();
  7396. texture.isReady = true;
  7397. }
  7398. catch (ex) {
  7399. // Something unexpected
  7400. // Let's disable the texture
  7401. texture._isDisabled = true;
  7402. }
  7403. };
  7404. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7405. // old version had a "generateMipMaps" arg instead of options.
  7406. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7407. // in the same way, generateDepthBuffer is defaulted to true
  7408. var generateMipMaps = false;
  7409. var generateDepthBuffer = true;
  7410. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7411. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7412. if (options !== undefined) {
  7413. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7414. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7415. type = options.type === undefined ? type : options.type;
  7416. if (options.samplingMode !== undefined) {
  7417. samplingMode = options.samplingMode;
  7418. }
  7419. if (type === Engine.TEXTURETYPE_FLOAT) {
  7420. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7421. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7422. }
  7423. }
  7424. var gl = this._gl;
  7425. var texture = gl.createTexture();
  7426. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7427. var width = size.width || size;
  7428. var height = size.height || size;
  7429. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7430. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7431. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7432. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7433. }
  7434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7438. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7439. var depthBuffer;
  7440. // Create the depth buffer
  7441. if (generateDepthBuffer) {
  7442. depthBuffer = gl.createRenderbuffer();
  7443. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7444. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7445. }
  7446. // Create the framebuffer
  7447. var framebuffer = gl.createFramebuffer();
  7448. this.bindUnboundFramebuffer(framebuffer);
  7449. if (generateDepthBuffer) {
  7450. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7451. }
  7452. if (generateMipMaps) {
  7453. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7454. }
  7455. // Unbind
  7456. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7457. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7458. this.bindUnboundFramebuffer(null);
  7459. texture._framebuffer = framebuffer;
  7460. if (generateDepthBuffer) {
  7461. texture._depthBuffer = depthBuffer;
  7462. }
  7463. texture._baseWidth = width;
  7464. texture._baseHeight = height;
  7465. texture._width = width;
  7466. texture._height = height;
  7467. texture.isReady = true;
  7468. texture.generateMipMaps = generateMipMaps;
  7469. texture.references = 1;
  7470. texture.samplingMode = samplingMode;
  7471. this.resetTextureCache();
  7472. this._loadedTexturesCache.push(texture);
  7473. return texture;
  7474. };
  7475. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7476. var gl = this._gl;
  7477. var texture = gl.createTexture();
  7478. var generateMipMaps = true;
  7479. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7480. if (options !== undefined) {
  7481. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7482. if (options.samplingMode !== undefined) {
  7483. samplingMode = options.samplingMode;
  7484. }
  7485. }
  7486. texture.isCube = true;
  7487. texture.references = 1;
  7488. texture.generateMipMaps = generateMipMaps;
  7489. texture.references = 1;
  7490. texture.samplingMode = samplingMode;
  7491. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7492. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7493. for (var face = 0; face < 6; face++) {
  7494. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7495. }
  7496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7500. // Create the depth buffer
  7501. var depthBuffer = gl.createRenderbuffer();
  7502. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7503. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7504. // Create the framebuffer
  7505. var framebuffer = gl.createFramebuffer();
  7506. this.bindUnboundFramebuffer(framebuffer);
  7507. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7508. // Mipmaps
  7509. if (texture.generateMipMaps) {
  7510. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7511. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7512. }
  7513. // Unbind
  7514. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7515. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7516. this.bindUnboundFramebuffer(null);
  7517. texture._framebuffer = framebuffer;
  7518. texture._depthBuffer = depthBuffer;
  7519. this.resetTextureCache();
  7520. texture._width = size;
  7521. texture._height = size;
  7522. texture.isReady = true;
  7523. return texture;
  7524. };
  7525. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7526. var _this = this;
  7527. var gl = this._gl;
  7528. var texture = gl.createTexture();
  7529. texture.isCube = true;
  7530. texture.url = rootUrl;
  7531. texture.references = 1;
  7532. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7533. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7534. if (isDDS) {
  7535. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7536. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7537. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7538. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7539. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7540. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7541. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7542. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7543. }
  7544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7548. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7549. _this.resetTextureCache();
  7550. texture._width = info.width;
  7551. texture._height = info.height;
  7552. texture.isReady = true;
  7553. }, null, null, true);
  7554. }
  7555. else {
  7556. cascadeLoad(rootUrl, scene, function (imgs) {
  7557. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7558. var height = width;
  7559. _this._prepareWorkingCanvas();
  7560. _this._workingCanvas.width = width;
  7561. _this._workingCanvas.height = height;
  7562. var faces = [
  7563. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7564. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7565. ];
  7566. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7567. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7568. for (var index = 0; index < faces.length; index++) {
  7569. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7570. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7571. }
  7572. if (!noMipmap) {
  7573. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7574. }
  7575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7578. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7579. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7580. _this.resetTextureCache();
  7581. texture._width = width;
  7582. texture._height = height;
  7583. texture.isReady = true;
  7584. }, files);
  7585. }
  7586. return texture;
  7587. };
  7588. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7589. texture._width = width;
  7590. texture._height = height;
  7591. texture._size = width * height;
  7592. texture._baseWidth = width;
  7593. texture._baseHeight = height;
  7594. };
  7595. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7596. var _this = this;
  7597. var gl = this._gl;
  7598. var texture = gl.createTexture();
  7599. scene._addPendingData(texture);
  7600. texture.isCube = true;
  7601. texture.references = 1;
  7602. texture.url = url;
  7603. var internalFormat = this._getInternalFormat(format);
  7604. var textureType = gl.UNSIGNED_BYTE;
  7605. if (type === Engine.TEXTURETYPE_FLOAT) {
  7606. textureType = gl.FLOAT;
  7607. }
  7608. var width = size;
  7609. var height = width;
  7610. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7611. texture._width = width;
  7612. texture._height = height;
  7613. var onerror = function () {
  7614. scene._removePendingData(texture);
  7615. };
  7616. var internalCallback = function (data) {
  7617. var rgbeDataArrays = callback(data);
  7618. var facesIndex = [
  7619. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7620. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7621. ];
  7622. width = texture._width;
  7623. height = texture._height;
  7624. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7626. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7627. if (!noMipmap && isPot) {
  7628. if (mipmmapGenerator) {
  7629. var arrayTemp = [];
  7630. // Data are known to be in +X +Y +Z -X -Y -Z
  7631. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7632. arrayTemp.push(rgbeDataArrays[0]); // +X
  7633. arrayTemp.push(rgbeDataArrays[3]); // -X
  7634. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7635. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7636. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7637. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7638. var mipData = mipmmapGenerator(arrayTemp);
  7639. for (var level = 0; level < mipData.length; level++) {
  7640. var mipSize = width >> level;
  7641. // mipData is order in +X -X +Y -Y +Z -Z
  7642. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7643. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7644. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7645. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7646. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7647. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7648. }
  7649. }
  7650. else {
  7651. // Data are known to be in +X +Y +Z -X -Y -Z
  7652. for (var index = 0; index < facesIndex.length; index++) {
  7653. var faceData = rgbeDataArrays[index];
  7654. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7655. }
  7656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7657. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7658. // By following the webgl standard changes from Revision 7, 2014/11/24
  7659. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7660. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7661. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7662. // Data are known to be in +X +Y +Z -X -Y -Z
  7663. for (var index = 0; index < facesIndex.length; index++) {
  7664. var faceData = rgbeDataArrays[index];
  7665. // Create a new RGBA Face.
  7666. var newFaceData = new Float32Array(width * height * 4);
  7667. for (var x = 0; x < width; x++) {
  7668. for (var y = 0; y < height; y++) {
  7669. var index_1 = (y * width + x) * 3;
  7670. var newIndex = (y * width + x) * 4;
  7671. // Map Old Value to new value.
  7672. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7673. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7674. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7675. // Add fully opaque alpha channel.
  7676. newFaceData[newIndex + 3] = 1;
  7677. }
  7678. }
  7679. // Reupload the face.
  7680. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7681. }
  7682. // Try to generate mipmap again.
  7683. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7684. }
  7685. }
  7686. }
  7687. else {
  7688. noMipmap = true;
  7689. }
  7690. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7693. }
  7694. else {
  7695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7697. }
  7698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7700. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7701. texture.isReady = true;
  7702. _this.resetTextureCache();
  7703. scene._removePendingData(texture);
  7704. };
  7705. BABYLON.Tools.LoadFile(url, function (data) {
  7706. internalCallback(data);
  7707. }, onerror, scene.database, true);
  7708. return texture;
  7709. };
  7710. ;
  7711. Engine.prototype._releaseTexture = function (texture) {
  7712. var gl = this._gl;
  7713. if (texture._framebuffer) {
  7714. gl.deleteFramebuffer(texture._framebuffer);
  7715. }
  7716. if (texture._depthBuffer) {
  7717. gl.deleteRenderbuffer(texture._depthBuffer);
  7718. }
  7719. gl.deleteTexture(texture);
  7720. // Unbind channels
  7721. this.unbindAllTextures();
  7722. var index = this._loadedTexturesCache.indexOf(texture);
  7723. if (index !== -1) {
  7724. this._loadedTexturesCache.splice(index, 1);
  7725. }
  7726. };
  7727. Engine.prototype.setProgram = function (program) {
  7728. if (this._currentProgram !== program) {
  7729. this._gl.useProgram(program);
  7730. this._currentProgram = program;
  7731. }
  7732. };
  7733. Engine.prototype.bindSamplers = function (effect) {
  7734. this.setProgram(effect.getProgram());
  7735. var samplers = effect.getSamplers();
  7736. for (var index = 0; index < samplers.length; index++) {
  7737. var uniform = effect.getUniform(samplers[index]);
  7738. this._gl.uniform1i(uniform, index);
  7739. }
  7740. this._currentEffect = null;
  7741. };
  7742. Engine.prototype.activateTexture = function (texture) {
  7743. if (this._activeTexture !== texture) {
  7744. this._gl.activeTexture(texture);
  7745. this._activeTexture = texture;
  7746. }
  7747. };
  7748. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7749. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7750. this._gl.bindTexture(target, texture);
  7751. this._activeTexturesCache[this._activeTexture] = texture;
  7752. }
  7753. };
  7754. Engine.prototype._bindTexture = function (channel, texture) {
  7755. if (channel < 0) {
  7756. return;
  7757. }
  7758. this.activateTexture(this._gl["TEXTURE" + channel]);
  7759. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7760. };
  7761. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7762. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7763. };
  7764. Engine.prototype.unbindAllTextures = function () {
  7765. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7766. this.activateTexture(this._gl["TEXTURE" + channel]);
  7767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7769. }
  7770. };
  7771. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7772. if (channel < 0) {
  7773. return;
  7774. }
  7775. this._gl.uniform1i(uniform, channel);
  7776. this._setTexture(channel, texture);
  7777. };
  7778. Engine.prototype._setTexture = function (channel, texture) {
  7779. // Not ready?
  7780. if (!texture || !texture.isReady()) {
  7781. if (this._activeTexturesCache[channel] != null) {
  7782. this.activateTexture(this._gl["TEXTURE" + channel]);
  7783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7784. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7785. }
  7786. return;
  7787. }
  7788. // Video
  7789. var alreadyActivated = false;
  7790. if (texture instanceof BABYLON.VideoTexture) {
  7791. this.activateTexture(this._gl["TEXTURE" + channel]);
  7792. alreadyActivated = true;
  7793. texture.update();
  7794. }
  7795. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7796. texture.delayLoad();
  7797. return;
  7798. }
  7799. var internalTexture = texture.getInternalTexture();
  7800. if (this._activeTexturesCache[channel] === internalTexture) {
  7801. return;
  7802. }
  7803. if (!alreadyActivated) {
  7804. this.activateTexture(this._gl["TEXTURE" + channel]);
  7805. }
  7806. if (internalTexture.isCube) {
  7807. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7808. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7809. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7810. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7811. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7812. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7813. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7814. }
  7815. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7816. }
  7817. else {
  7818. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7819. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7820. internalTexture._cachedWrapU = texture.wrapU;
  7821. switch (texture.wrapU) {
  7822. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7823. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7824. break;
  7825. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7826. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7827. break;
  7828. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7830. break;
  7831. }
  7832. }
  7833. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7834. internalTexture._cachedWrapV = texture.wrapV;
  7835. switch (texture.wrapV) {
  7836. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7837. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7838. break;
  7839. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7840. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7841. break;
  7842. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7843. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7844. break;
  7845. }
  7846. }
  7847. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7848. }
  7849. };
  7850. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7851. if (channel < 0) {
  7852. return;
  7853. }
  7854. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7855. this._textureUnits = new Int32Array(textures.length);
  7856. }
  7857. for (var i = 0; i < textures.length; i++) {
  7858. this._textureUnits[i] = channel + i;
  7859. }
  7860. this._gl.uniform1iv(uniform, this._textureUnits);
  7861. for (var index = 0; index < textures.length; index++) {
  7862. this._setTexture(channel + index, textures[index]);
  7863. }
  7864. };
  7865. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7866. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7867. var value = texture.anisotropicFilteringLevel;
  7868. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7869. value = 1;
  7870. }
  7871. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7872. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7873. texture._cachedAnisotropicFilteringLevel = value;
  7874. }
  7875. };
  7876. Engine.prototype.readPixels = function (x, y, width, height) {
  7877. var data = new Uint8Array(height * width * 4);
  7878. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7879. return data;
  7880. };
  7881. /**
  7882. * Add an externaly attached data from its key.
  7883. * This method call will fail and return false, if such key already exists.
  7884. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7885. * @param key the unique key that identifies the data
  7886. * @param data the data object to associate to the key for this Engine instance
  7887. * @return true if no such key were already present and the data was added successfully, false otherwise
  7888. */
  7889. Engine.prototype.addExternalData = function (key, data) {
  7890. return this._externalData.add(key, data);
  7891. };
  7892. /**
  7893. * Get an externaly attached data from its key
  7894. * @param key the unique key that identifies the data
  7895. * @return the associated data, if present (can be null), or undefined if not present
  7896. */
  7897. Engine.prototype.getExternalData = function (key) {
  7898. return this._externalData.get(key);
  7899. };
  7900. /**
  7901. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7902. * @param key the unique key that identifies the data
  7903. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7904. * @return the associated data, can be null if the factory returned null.
  7905. */
  7906. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7907. return this._externalData.getOrAddWithFactory(key, factory);
  7908. };
  7909. /**
  7910. * Remove an externaly attached data from the Engine instance
  7911. * @param key the unique key that identifies the data
  7912. * @return true if the data was successfully removed, false if it doesn't exist
  7913. */
  7914. Engine.prototype.removeExternalData = function (key) {
  7915. return this._externalData.remove(key);
  7916. };
  7917. Engine.prototype.releaseInternalTexture = function (texture) {
  7918. if (!texture) {
  7919. return;
  7920. }
  7921. texture.references--;
  7922. // Final reference ?
  7923. if (texture.references === 0) {
  7924. var texturesCache = this.getLoadedTexturesCache();
  7925. var index = texturesCache.indexOf(texture);
  7926. if (index > -1) {
  7927. texturesCache.splice(index, 1);
  7928. }
  7929. this._releaseTexture(texture);
  7930. }
  7931. };
  7932. // Dispose
  7933. Engine.prototype.dispose = function () {
  7934. this.hideLoadingUI();
  7935. this.stopRenderLoop();
  7936. // Release scenes
  7937. while (this.scenes.length) {
  7938. this.scenes[0].dispose();
  7939. }
  7940. // Release audio engine
  7941. Engine.audioEngine.dispose();
  7942. // Release effects
  7943. for (var name in this._compiledEffects) {
  7944. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7945. }
  7946. // Unbind
  7947. if (this._vertexAttribArraysEnabled) {
  7948. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  7949. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  7950. continue;
  7951. }
  7952. this._gl.disableVertexAttribArray(i);
  7953. }
  7954. }
  7955. this._gl = null;
  7956. // Events
  7957. window.removeEventListener("blur", this._onBlur);
  7958. window.removeEventListener("focus", this._onFocus);
  7959. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7960. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7961. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7962. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7963. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7964. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7965. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7966. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7967. };
  7968. // Loading screen
  7969. Engine.prototype.displayLoadingUI = function () {
  7970. this._loadingScreen.displayLoadingUI();
  7971. };
  7972. Engine.prototype.hideLoadingUI = function () {
  7973. this._loadingScreen.hideLoadingUI();
  7974. };
  7975. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7976. get: function () {
  7977. return this._loadingScreen;
  7978. },
  7979. set: function (loadingScreen) {
  7980. this._loadingScreen = loadingScreen;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7986. set: function (text) {
  7987. this._loadingScreen.loadingUIText = text;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7993. set: function (color) {
  7994. this._loadingScreen.loadingUIBackgroundColor = color;
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. // FPS
  8000. Engine.prototype.getFps = function () {
  8001. return this.fps;
  8002. };
  8003. Engine.prototype.getDeltaTime = function () {
  8004. return this.deltaTime;
  8005. };
  8006. Engine.prototype._measureFps = function () {
  8007. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8008. var length = this.previousFramesDuration.length;
  8009. if (length >= 2) {
  8010. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8011. }
  8012. if (length >= this.fpsRange) {
  8013. if (length > this.fpsRange) {
  8014. this.previousFramesDuration.splice(0, 1);
  8015. length = this.previousFramesDuration.length;
  8016. }
  8017. var sum = 0;
  8018. for (var id = 0; id < length - 1; id++) {
  8019. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8020. }
  8021. this.fps = 1000.0 / (sum / (length - 1));
  8022. }
  8023. };
  8024. // Statics
  8025. Engine.isSupported = function () {
  8026. try {
  8027. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8028. if (navigator.isCocoonJS) {
  8029. return true;
  8030. }
  8031. var tempcanvas = document.createElement("canvas");
  8032. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8033. return gl != null && !!window.WebGLRenderingContext;
  8034. }
  8035. catch (e) {
  8036. return false;
  8037. }
  8038. };
  8039. // Const statics
  8040. Engine._ALPHA_DISABLE = 0;
  8041. Engine._ALPHA_ADD = 1;
  8042. Engine._ALPHA_COMBINE = 2;
  8043. Engine._ALPHA_SUBTRACT = 3;
  8044. Engine._ALPHA_MULTIPLY = 4;
  8045. Engine._ALPHA_MAXIMIZED = 5;
  8046. Engine._ALPHA_ONEONE = 6;
  8047. Engine._DELAYLOADSTATE_NONE = 0;
  8048. Engine._DELAYLOADSTATE_LOADED = 1;
  8049. Engine._DELAYLOADSTATE_LOADING = 2;
  8050. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8051. Engine._TEXTUREFORMAT_ALPHA = 0;
  8052. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8053. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8054. Engine._TEXTUREFORMAT_RGB = 4;
  8055. Engine._TEXTUREFORMAT_RGBA = 5;
  8056. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8057. Engine._TEXTURETYPE_FLOAT = 1;
  8058. // Updatable statics so stick with vars here
  8059. Engine.CollisionsEpsilon = 0.001;
  8060. Engine.CodeRepository = "src/";
  8061. Engine.ShadersRepository = "src/Shaders/";
  8062. return Engine;
  8063. })();
  8064. BABYLON.Engine = Engine;
  8065. })(BABYLON || (BABYLON = {}));
  8066. var BABYLON;
  8067. (function (BABYLON) {
  8068. /**
  8069. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8070. */
  8071. var Node = (function () {
  8072. /**
  8073. * @constructor
  8074. * @param {string} name - the name and id to be given to this node
  8075. * @param {BABYLON.Scene} the scene this node will be added to
  8076. */
  8077. function Node(name, scene) {
  8078. this.state = "";
  8079. this.animations = new Array();
  8080. this._ranges = {};
  8081. this._childrenFlag = -1;
  8082. this._isEnabled = true;
  8083. this._isReady = true;
  8084. this._currentRenderId = -1;
  8085. this._parentRenderId = -1;
  8086. this.name = name;
  8087. this.id = name;
  8088. this._scene = scene;
  8089. this._initCache();
  8090. }
  8091. Object.defineProperty(Node.prototype, "parent", {
  8092. get: function () {
  8093. return this._parentNode;
  8094. },
  8095. set: function (parent) {
  8096. if (this._parentNode === parent) {
  8097. return;
  8098. }
  8099. if (this._parentNode) {
  8100. var index = this._parentNode._children.indexOf(this);
  8101. if (index !== -1) {
  8102. this._parentNode._children.splice(index, 1);
  8103. }
  8104. }
  8105. this._parentNode = parent;
  8106. if (this._parentNode) {
  8107. if (!this._parentNode._children) {
  8108. this._parentNode._children = new Array();
  8109. }
  8110. this._parentNode._children.push(this);
  8111. }
  8112. },
  8113. enumerable: true,
  8114. configurable: true
  8115. });
  8116. Node.prototype.getScene = function () {
  8117. return this._scene;
  8118. };
  8119. Node.prototype.getEngine = function () {
  8120. return this._scene.getEngine();
  8121. };
  8122. // override it in derived class
  8123. Node.prototype.getWorldMatrix = function () {
  8124. return BABYLON.Matrix.Identity();
  8125. };
  8126. // override it in derived class if you add new variables to the cache
  8127. // and call the parent class method
  8128. Node.prototype._initCache = function () {
  8129. this._cache = {};
  8130. this._cache.parent = undefined;
  8131. };
  8132. Node.prototype.updateCache = function (force) {
  8133. if (!force && this.isSynchronized())
  8134. return;
  8135. this._cache.parent = this.parent;
  8136. this._updateCache();
  8137. };
  8138. // override it in derived class if you add new variables to the cache
  8139. // and call the parent class method if !ignoreParentClass
  8140. Node.prototype._updateCache = function (ignoreParentClass) {
  8141. };
  8142. // override it in derived class if you add new variables to the cache
  8143. Node.prototype._isSynchronized = function () {
  8144. return true;
  8145. };
  8146. Node.prototype._markSyncedWithParent = function () {
  8147. this._parentRenderId = this.parent._currentRenderId;
  8148. };
  8149. Node.prototype.isSynchronizedWithParent = function () {
  8150. if (!this.parent) {
  8151. return true;
  8152. }
  8153. if (this._parentRenderId !== this.parent._currentRenderId) {
  8154. return false;
  8155. }
  8156. return this.parent.isSynchronized();
  8157. };
  8158. Node.prototype.isSynchronized = function (updateCache) {
  8159. var check = this.hasNewParent();
  8160. check = check || !this.isSynchronizedWithParent();
  8161. check = check || !this._isSynchronized();
  8162. if (updateCache)
  8163. this.updateCache(true);
  8164. return !check;
  8165. };
  8166. Node.prototype.hasNewParent = function (update) {
  8167. if (this._cache.parent === this.parent)
  8168. return false;
  8169. if (update)
  8170. this._cache.parent = this.parent;
  8171. return true;
  8172. };
  8173. /**
  8174. * Is this node ready to be used/rendered
  8175. * @return {boolean} is it ready
  8176. */
  8177. Node.prototype.isReady = function () {
  8178. return this._isReady;
  8179. };
  8180. /**
  8181. * Is this node enabled.
  8182. * If the node has a parent and is enabled, the parent will be inspected as well.
  8183. * @return {boolean} whether this node (and its parent) is enabled.
  8184. * @see setEnabled
  8185. */
  8186. Node.prototype.isEnabled = function () {
  8187. if (!this._isEnabled) {
  8188. return false;
  8189. }
  8190. if (this.parent) {
  8191. return this.parent.isEnabled();
  8192. }
  8193. return true;
  8194. };
  8195. /**
  8196. * Set the enabled state of this node.
  8197. * @param {boolean} value - the new enabled state
  8198. * @see isEnabled
  8199. */
  8200. Node.prototype.setEnabled = function (value) {
  8201. this._isEnabled = value;
  8202. };
  8203. /**
  8204. * Is this node a descendant of the given node.
  8205. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8206. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8207. * @see parent
  8208. */
  8209. Node.prototype.isDescendantOf = function (ancestor) {
  8210. if (this.parent) {
  8211. if (this.parent === ancestor) {
  8212. return true;
  8213. }
  8214. return this.parent.isDescendantOf(ancestor);
  8215. }
  8216. return false;
  8217. };
  8218. /**
  8219. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8220. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8221. * @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.
  8222. * @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.
  8223. */
  8224. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8225. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8226. if (!this._children) {
  8227. return;
  8228. }
  8229. for (var index = 0; index < this._children.length; index++) {
  8230. var item = this._children[index];
  8231. if (!predicate || predicate(item)) {
  8232. results.push(item);
  8233. }
  8234. if (!directDescendantsOnly) {
  8235. item._getDescendants(results, false, predicate);
  8236. }
  8237. }
  8238. };
  8239. /**
  8240. * Will return all nodes that have this node as ascendant.
  8241. * @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.
  8242. * @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.
  8243. * @return {BABYLON.Node[]} all children nodes of all types.
  8244. */
  8245. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8246. var results = [];
  8247. this._getDescendants(results, directDescendantsOnly, predicate);
  8248. return results;
  8249. };
  8250. /**
  8251. * @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.
  8252. * @Deprecated, legacy support.
  8253. * use getDecendants instead.
  8254. */
  8255. Node.prototype.getChildren = function (predicate) {
  8256. return this.getDescendants(true, predicate);
  8257. };
  8258. /**
  8259. * Get all child-meshes of this node.
  8260. */
  8261. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8262. var results = [];
  8263. this._getDescendants(results, directDecendantsOnly, function (node) {
  8264. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8265. });
  8266. return results;
  8267. };
  8268. Node.prototype._setReady = function (state) {
  8269. if (state === this._isReady) {
  8270. return;
  8271. }
  8272. if (!state) {
  8273. this._isReady = false;
  8274. return;
  8275. }
  8276. this._isReady = true;
  8277. if (this.onReady) {
  8278. this.onReady(this);
  8279. }
  8280. };
  8281. Node.prototype.getAnimationByName = function (name) {
  8282. for (var i = 0; i < this.animations.length; i++) {
  8283. var animation = this.animations[i];
  8284. if (animation.name === name) {
  8285. return animation;
  8286. }
  8287. }
  8288. return null;
  8289. };
  8290. Node.prototype.createAnimationRange = function (name, from, to) {
  8291. // check name not already in use
  8292. if (!this._ranges[name]) {
  8293. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8294. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8295. if (this.animations[i]) {
  8296. this.animations[i].createRange(name, from, to);
  8297. }
  8298. }
  8299. }
  8300. };
  8301. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8302. if (deleteFrames === void 0) { deleteFrames = true; }
  8303. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8304. if (this.animations[i]) {
  8305. this.animations[i].deleteRange(name, deleteFrames);
  8306. }
  8307. }
  8308. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8309. };
  8310. Node.prototype.getAnimationRange = function (name) {
  8311. return this._ranges[name];
  8312. };
  8313. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8314. var range = this.getAnimationRange(name);
  8315. if (!range) {
  8316. return null;
  8317. }
  8318. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8319. };
  8320. Node.prototype.serializeAnimationRanges = function () {
  8321. var serializationRanges = [];
  8322. for (var name in this._ranges) {
  8323. var range = {};
  8324. range.name = name;
  8325. range.from = this._ranges[name].from;
  8326. range.to = this._ranges[name].to;
  8327. serializationRanges.push(range);
  8328. }
  8329. return serializationRanges;
  8330. };
  8331. Node.prototype.dispose = function () {
  8332. this.parent = null;
  8333. };
  8334. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8335. if (parsedNode.ranges) {
  8336. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8337. var data = parsedNode.ranges[index];
  8338. node.createAnimationRange(data.name, data.from, data.to);
  8339. }
  8340. }
  8341. };
  8342. __decorate([
  8343. BABYLON.serialize()
  8344. ], Node.prototype, "name", void 0);
  8345. __decorate([
  8346. BABYLON.serialize()
  8347. ], Node.prototype, "id", void 0);
  8348. __decorate([
  8349. BABYLON.serialize()
  8350. ], Node.prototype, "uniqueId", void 0);
  8351. __decorate([
  8352. BABYLON.serialize()
  8353. ], Node.prototype, "state", void 0);
  8354. return Node;
  8355. })();
  8356. BABYLON.Node = Node;
  8357. })(BABYLON || (BABYLON = {}));
  8358. var BABYLON;
  8359. (function (BABYLON) {
  8360. var FilesInput = (function () {
  8361. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8362. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8363. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8364. this._engine = p_engine;
  8365. this._canvas = p_canvas;
  8366. this._currentScene = p_scene;
  8367. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8368. this._progressCallback = p_progressCallback;
  8369. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8370. this._textureLoadingCallback = p_textureLoadingCallback;
  8371. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8372. }
  8373. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8374. var _this = this;
  8375. if (p_elementToMonitor) {
  8376. this._elementToMonitor = p_elementToMonitor;
  8377. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8378. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8379. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8380. }
  8381. };
  8382. FilesInput.prototype.renderFunction = function () {
  8383. if (this._additionnalRenderLoopLogicCallback) {
  8384. this._additionnalRenderLoopLogicCallback();
  8385. }
  8386. if (this._currentScene) {
  8387. if (this._textureLoadingCallback) {
  8388. var remaining = this._currentScene.getWaitingItemsCount();
  8389. if (remaining > 0) {
  8390. this._textureLoadingCallback(remaining);
  8391. }
  8392. }
  8393. this._currentScene.render();
  8394. }
  8395. };
  8396. FilesInput.prototype.drag = function (e) {
  8397. e.stopPropagation();
  8398. e.preventDefault();
  8399. };
  8400. FilesInput.prototype.drop = function (eventDrop) {
  8401. eventDrop.stopPropagation();
  8402. eventDrop.preventDefault();
  8403. this.loadFiles(eventDrop);
  8404. };
  8405. FilesInput.prototype.loadFiles = function (event) {
  8406. if (this._startingProcessingFilesCallback)
  8407. this._startingProcessingFilesCallback();
  8408. // Handling data transfer via drag'n'drop
  8409. if (event && event.dataTransfer && event.dataTransfer.files) {
  8410. this._filesToLoad = event.dataTransfer.files;
  8411. }
  8412. // Handling files from input files
  8413. if (event && event.target && event.target.files) {
  8414. this._filesToLoad = event.target.files;
  8415. }
  8416. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8417. for (var i = 0; i < this._filesToLoad.length; i++) {
  8418. switch (this._filesToLoad[i].type) {
  8419. case "image/jpeg":
  8420. case "image/png":
  8421. case "image/bmp":
  8422. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8423. break;
  8424. case "image/targa":
  8425. case "image/vnd.ms-dds":
  8426. case "audio/wav":
  8427. case "audio/x-wav":
  8428. case "audio/mp3":
  8429. case "audio/mpeg":
  8430. case "audio/mpeg3":
  8431. case "audio/x-mpeg-3":
  8432. case "audio/ogg":
  8433. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8434. break;
  8435. default:
  8436. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8437. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8438. }
  8439. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8440. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8441. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8442. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8443. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8444. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8445. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8446. this._sceneFileToLoad = this._filesToLoad[i];
  8447. }
  8448. break;
  8449. }
  8450. }
  8451. this.reload();
  8452. }
  8453. };
  8454. FilesInput.prototype.reload = function () {
  8455. var _this = this;
  8456. var that = this;
  8457. // If a ".babylon" file has been provided
  8458. if (this._sceneFileToLoad) {
  8459. if (this._currentScene) {
  8460. if (BABYLON.Tools.errorsCount > 0) {
  8461. BABYLON.Tools.ClearLogCache();
  8462. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8463. }
  8464. this._engine.stopRenderLoop();
  8465. this._currentScene.dispose();
  8466. }
  8467. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8468. that._currentScene = newScene;
  8469. // Wait for textures and shaders to be ready
  8470. that._currentScene.executeWhenReady(function () {
  8471. // Attach camera to canvas inputs
  8472. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8473. that._currentScene.createDefaultCameraOrLight();
  8474. }
  8475. that._currentScene.activeCamera.attachControl(that._canvas);
  8476. if (that._sceneLoadedCallback) {
  8477. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8478. }
  8479. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8480. });
  8481. }, function (progress) {
  8482. if (_this._progressCallback) {
  8483. _this._progressCallback(progress);
  8484. }
  8485. });
  8486. }
  8487. else {
  8488. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8489. }
  8490. };
  8491. FilesInput.FilesTextures = new Array();
  8492. FilesInput.FilesToLoad = new Array();
  8493. return FilesInput;
  8494. })();
  8495. BABYLON.FilesInput = FilesInput;
  8496. })(BABYLON || (BABYLON = {}));
  8497. var BABYLON;
  8498. (function (BABYLON) {
  8499. var IntersectionInfo = (function () {
  8500. function IntersectionInfo(bu, bv, distance) {
  8501. this.bu = bu;
  8502. this.bv = bv;
  8503. this.distance = distance;
  8504. this.faceId = 0;
  8505. this.subMeshId = 0;
  8506. }
  8507. return IntersectionInfo;
  8508. })();
  8509. BABYLON.IntersectionInfo = IntersectionInfo;
  8510. var PickingInfo = (function () {
  8511. function PickingInfo() {
  8512. this.hit = false;
  8513. this.distance = 0;
  8514. this.pickedPoint = null;
  8515. this.pickedMesh = null;
  8516. this.bu = 0;
  8517. this.bv = 0;
  8518. this.faceId = -1;
  8519. this.subMeshId = 0;
  8520. this.pickedSprite = null;
  8521. }
  8522. // Methods
  8523. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8524. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8525. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8526. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8527. return null;
  8528. }
  8529. var indices = this.pickedMesh.getIndices();
  8530. var result;
  8531. if (useVerticesNormals) {
  8532. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8533. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8534. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8535. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8536. normal0 = normal0.scale(this.bu);
  8537. normal1 = normal1.scale(this.bv);
  8538. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8539. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8540. }
  8541. else {
  8542. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8543. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8544. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8545. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8546. var p1p2 = vertex1.subtract(vertex2);
  8547. var p3p2 = vertex3.subtract(vertex2);
  8548. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8549. }
  8550. if (useWorldCoordinates) {
  8551. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8552. }
  8553. return BABYLON.Vector3.Normalize(result);
  8554. };
  8555. PickingInfo.prototype.getTextureCoordinates = function () {
  8556. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8557. return null;
  8558. }
  8559. var indices = this.pickedMesh.getIndices();
  8560. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8561. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8562. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8563. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8564. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8565. uv1 = uv1.scale(this.bu);
  8566. uv2 = uv2.scale(this.bv);
  8567. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8568. };
  8569. return PickingInfo;
  8570. })();
  8571. BABYLON.PickingInfo = PickingInfo;
  8572. })(BABYLON || (BABYLON = {}));
  8573. var BABYLON;
  8574. (function (BABYLON) {
  8575. var BoundingSphere = (function () {
  8576. function BoundingSphere(minimum, maximum) {
  8577. this.minimum = minimum;
  8578. this.maximum = maximum;
  8579. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8580. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8581. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8582. this.radius = distance * 0.5;
  8583. this.centerWorld = BABYLON.Vector3.Zero();
  8584. this._update(BABYLON.Matrix.Identity());
  8585. }
  8586. // Methods
  8587. BoundingSphere.prototype._update = function (world) {
  8588. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8589. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8590. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8591. };
  8592. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8593. for (var i = 0; i < 6; i++) {
  8594. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8595. return false;
  8596. }
  8597. return true;
  8598. };
  8599. BoundingSphere.prototype.intersectsPoint = function (point) {
  8600. var x = this.centerWorld.x - point.x;
  8601. var y = this.centerWorld.y - point.y;
  8602. var z = this.centerWorld.z - point.z;
  8603. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8604. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8605. return false;
  8606. return true;
  8607. };
  8608. // Statics
  8609. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8610. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8611. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8612. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8613. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8614. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8615. return false;
  8616. return true;
  8617. };
  8618. return BoundingSphere;
  8619. })();
  8620. BABYLON.BoundingSphere = BoundingSphere;
  8621. })(BABYLON || (BABYLON = {}));
  8622. var BABYLON;
  8623. (function (BABYLON) {
  8624. var BoundingBox = (function () {
  8625. function BoundingBox(minimum, maximum) {
  8626. this.minimum = minimum;
  8627. this.maximum = maximum;
  8628. this.vectors = new Array();
  8629. this.vectorsWorld = new Array();
  8630. // Bounding vectors
  8631. this.vectors.push(this.minimum.clone());
  8632. this.vectors.push(this.maximum.clone());
  8633. this.vectors.push(this.minimum.clone());
  8634. this.vectors[2].x = this.maximum.x;
  8635. this.vectors.push(this.minimum.clone());
  8636. this.vectors[3].y = this.maximum.y;
  8637. this.vectors.push(this.minimum.clone());
  8638. this.vectors[4].z = this.maximum.z;
  8639. this.vectors.push(this.maximum.clone());
  8640. this.vectors[5].z = this.minimum.z;
  8641. this.vectors.push(this.maximum.clone());
  8642. this.vectors[6].x = this.minimum.x;
  8643. this.vectors.push(this.maximum.clone());
  8644. this.vectors[7].y = this.minimum.y;
  8645. // OBB
  8646. this.center = this.maximum.add(this.minimum).scale(0.5);
  8647. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8648. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8649. // World
  8650. for (var index = 0; index < this.vectors.length; index++) {
  8651. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8652. }
  8653. this.minimumWorld = BABYLON.Vector3.Zero();
  8654. this.maximumWorld = BABYLON.Vector3.Zero();
  8655. this._update(BABYLON.Matrix.Identity());
  8656. }
  8657. // Methods
  8658. BoundingBox.prototype.getWorldMatrix = function () {
  8659. return this._worldMatrix;
  8660. };
  8661. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8662. this._worldMatrix.copyFrom(matrix);
  8663. return this;
  8664. };
  8665. BoundingBox.prototype._update = function (world) {
  8666. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8667. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8668. for (var index = 0; index < this.vectors.length; index++) {
  8669. var v = this.vectorsWorld[index];
  8670. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8671. if (v.x < this.minimumWorld.x)
  8672. this.minimumWorld.x = v.x;
  8673. if (v.y < this.minimumWorld.y)
  8674. this.minimumWorld.y = v.y;
  8675. if (v.z < this.minimumWorld.z)
  8676. this.minimumWorld.z = v.z;
  8677. if (v.x > this.maximumWorld.x)
  8678. this.maximumWorld.x = v.x;
  8679. if (v.y > this.maximumWorld.y)
  8680. this.maximumWorld.y = v.y;
  8681. if (v.z > this.maximumWorld.z)
  8682. this.maximumWorld.z = v.z;
  8683. }
  8684. // OBB
  8685. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8686. this.center.scaleInPlace(0.5);
  8687. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8688. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8689. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8690. this._worldMatrix = world;
  8691. };
  8692. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8693. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8694. };
  8695. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8696. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8697. };
  8698. BoundingBox.prototype.intersectsPoint = function (point) {
  8699. var delta = -BABYLON.Epsilon;
  8700. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8701. return false;
  8702. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8703. return false;
  8704. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8705. return false;
  8706. return true;
  8707. };
  8708. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8709. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8710. };
  8711. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8712. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8713. return false;
  8714. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8715. return false;
  8716. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8717. return false;
  8718. return true;
  8719. };
  8720. // Statics
  8721. BoundingBox.Intersects = function (box0, box1) {
  8722. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8723. return false;
  8724. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8725. return false;
  8726. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8727. return false;
  8728. return true;
  8729. };
  8730. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8731. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8732. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8733. return (num <= (sphereRadius * sphereRadius));
  8734. };
  8735. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8736. for (var p = 0; p < 6; p++) {
  8737. for (var i = 0; i < 8; i++) {
  8738. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8739. return false;
  8740. }
  8741. }
  8742. }
  8743. return true;
  8744. };
  8745. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8746. for (var p = 0; p < 6; p++) {
  8747. var inCount = 8;
  8748. for (var i = 0; i < 8; i++) {
  8749. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8750. --inCount;
  8751. }
  8752. else {
  8753. break;
  8754. }
  8755. }
  8756. if (inCount === 0)
  8757. return false;
  8758. }
  8759. return true;
  8760. };
  8761. return BoundingBox;
  8762. })();
  8763. BABYLON.BoundingBox = BoundingBox;
  8764. })(BABYLON || (BABYLON = {}));
  8765. var BABYLON;
  8766. (function (BABYLON) {
  8767. var computeBoxExtents = function (axis, box) {
  8768. var p = BABYLON.Vector3.Dot(box.center, axis);
  8769. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8770. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8771. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8772. var r = r0 + r1 + r2;
  8773. return {
  8774. min: p - r,
  8775. max: p + r
  8776. };
  8777. };
  8778. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8779. var axisOverlap = function (axis, box0, box1) {
  8780. var result0 = computeBoxExtents(axis, box0);
  8781. var result1 = computeBoxExtents(axis, box1);
  8782. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8783. };
  8784. var BoundingInfo = (function () {
  8785. function BoundingInfo(minimum, maximum) {
  8786. this.minimum = minimum;
  8787. this.maximum = maximum;
  8788. this._isLocked = false;
  8789. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8790. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8791. }
  8792. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8793. get: function () {
  8794. return this._isLocked;
  8795. },
  8796. set: function (value) {
  8797. this._isLocked = value;
  8798. },
  8799. enumerable: true,
  8800. configurable: true
  8801. });
  8802. // Methods
  8803. BoundingInfo.prototype.update = function (world) {
  8804. if (this._isLocked) {
  8805. return;
  8806. }
  8807. this.boundingBox._update(world);
  8808. this.boundingSphere._update(world);
  8809. };
  8810. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8811. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8812. return false;
  8813. return this.boundingBox.isInFrustum(frustumPlanes);
  8814. };
  8815. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8816. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8817. };
  8818. BoundingInfo.prototype._checkCollision = function (collider) {
  8819. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8820. };
  8821. BoundingInfo.prototype.intersectsPoint = function (point) {
  8822. if (!this.boundingSphere.centerWorld) {
  8823. return false;
  8824. }
  8825. if (!this.boundingSphere.intersectsPoint(point)) {
  8826. return false;
  8827. }
  8828. if (!this.boundingBox.intersectsPoint(point)) {
  8829. return false;
  8830. }
  8831. return true;
  8832. };
  8833. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8834. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8835. return false;
  8836. }
  8837. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8838. return false;
  8839. }
  8840. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8841. return false;
  8842. }
  8843. if (!precise) {
  8844. return true;
  8845. }
  8846. var box0 = this.boundingBox;
  8847. var box1 = boundingInfo.boundingBox;
  8848. if (!axisOverlap(box0.directions[0], box0, box1))
  8849. return false;
  8850. if (!axisOverlap(box0.directions[1], box0, box1))
  8851. return false;
  8852. if (!axisOverlap(box0.directions[2], box0, box1))
  8853. return false;
  8854. if (!axisOverlap(box1.directions[0], box0, box1))
  8855. return false;
  8856. if (!axisOverlap(box1.directions[1], box0, box1))
  8857. return false;
  8858. if (!axisOverlap(box1.directions[2], box0, box1))
  8859. return false;
  8860. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8861. return false;
  8862. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8863. return false;
  8864. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8865. return false;
  8866. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8867. return false;
  8868. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8869. return false;
  8870. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8871. return false;
  8872. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8873. return false;
  8874. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8875. return false;
  8876. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8877. return false;
  8878. return true;
  8879. };
  8880. return BoundingInfo;
  8881. })();
  8882. BABYLON.BoundingInfo = BoundingInfo;
  8883. })(BABYLON || (BABYLON = {}));
  8884. var BABYLON;
  8885. (function (BABYLON) {
  8886. var Ray = (function () {
  8887. function Ray(origin, direction, length) {
  8888. if (length === void 0) { length = Number.MAX_VALUE; }
  8889. this.origin = origin;
  8890. this.direction = direction;
  8891. this.length = length;
  8892. }
  8893. // Methods
  8894. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8895. var d = 0.0;
  8896. var maxValue = Number.MAX_VALUE;
  8897. var inv;
  8898. var min;
  8899. var max;
  8900. var temp;
  8901. if (Math.abs(this.direction.x) < 0.0000001) {
  8902. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8903. return false;
  8904. }
  8905. }
  8906. else {
  8907. inv = 1.0 / this.direction.x;
  8908. min = (minimum.x - this.origin.x) * inv;
  8909. max = (maximum.x - this.origin.x) * inv;
  8910. if (max === -Infinity) {
  8911. max = Infinity;
  8912. }
  8913. if (min > max) {
  8914. temp = min;
  8915. min = max;
  8916. max = temp;
  8917. }
  8918. d = Math.max(min, d);
  8919. maxValue = Math.min(max, maxValue);
  8920. if (d > maxValue) {
  8921. return false;
  8922. }
  8923. }
  8924. if (Math.abs(this.direction.y) < 0.0000001) {
  8925. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8926. return false;
  8927. }
  8928. }
  8929. else {
  8930. inv = 1.0 / this.direction.y;
  8931. min = (minimum.y - this.origin.y) * inv;
  8932. max = (maximum.y - this.origin.y) * inv;
  8933. if (max === -Infinity) {
  8934. max = Infinity;
  8935. }
  8936. if (min > max) {
  8937. temp = min;
  8938. min = max;
  8939. max = temp;
  8940. }
  8941. d = Math.max(min, d);
  8942. maxValue = Math.min(max, maxValue);
  8943. if (d > maxValue) {
  8944. return false;
  8945. }
  8946. }
  8947. if (Math.abs(this.direction.z) < 0.0000001) {
  8948. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8949. return false;
  8950. }
  8951. }
  8952. else {
  8953. inv = 1.0 / this.direction.z;
  8954. min = (minimum.z - this.origin.z) * inv;
  8955. max = (maximum.z - this.origin.z) * inv;
  8956. if (max === -Infinity) {
  8957. max = Infinity;
  8958. }
  8959. if (min > max) {
  8960. temp = min;
  8961. min = max;
  8962. max = temp;
  8963. }
  8964. d = Math.max(min, d);
  8965. maxValue = Math.min(max, maxValue);
  8966. if (d > maxValue) {
  8967. return false;
  8968. }
  8969. }
  8970. return true;
  8971. };
  8972. Ray.prototype.intersectsBox = function (box) {
  8973. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8974. };
  8975. Ray.prototype.intersectsSphere = function (sphere) {
  8976. var x = sphere.center.x - this.origin.x;
  8977. var y = sphere.center.y - this.origin.y;
  8978. var z = sphere.center.z - this.origin.z;
  8979. var pyth = (x * x) + (y * y) + (z * z);
  8980. var rr = sphere.radius * sphere.radius;
  8981. if (pyth <= rr) {
  8982. return true;
  8983. }
  8984. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8985. if (dot < 0.0) {
  8986. return false;
  8987. }
  8988. var temp = pyth - (dot * dot);
  8989. return temp <= rr;
  8990. };
  8991. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8992. if (!this._edge1) {
  8993. this._edge1 = BABYLON.Vector3.Zero();
  8994. this._edge2 = BABYLON.Vector3.Zero();
  8995. this._pvec = BABYLON.Vector3.Zero();
  8996. this._tvec = BABYLON.Vector3.Zero();
  8997. this._qvec = BABYLON.Vector3.Zero();
  8998. }
  8999. vertex1.subtractToRef(vertex0, this._edge1);
  9000. vertex2.subtractToRef(vertex0, this._edge2);
  9001. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9002. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9003. if (det === 0) {
  9004. return null;
  9005. }
  9006. var invdet = 1 / det;
  9007. this.origin.subtractToRef(vertex0, this._tvec);
  9008. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9009. if (bu < 0 || bu > 1.0) {
  9010. return null;
  9011. }
  9012. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9013. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9014. if (bv < 0 || bu + bv > 1.0) {
  9015. return null;
  9016. }
  9017. //check if the distance is longer than the predefined length.
  9018. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9019. if (distance > this.length) {
  9020. return null;
  9021. }
  9022. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9023. };
  9024. Ray.prototype.intersectsPlane = function (plane) {
  9025. var distance;
  9026. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9027. if (Math.abs(result1) < 9.99999997475243E-07) {
  9028. return null;
  9029. }
  9030. else {
  9031. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9032. distance = (-plane.d - result2) / result1;
  9033. if (distance < 0.0) {
  9034. if (distance < -9.99999997475243E-07) {
  9035. return null;
  9036. }
  9037. else {
  9038. return 0;
  9039. }
  9040. }
  9041. return distance;
  9042. }
  9043. };
  9044. /**
  9045. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9046. * @param sega the first point of the segment to test the intersection against
  9047. * @param segb the second point of the segment to test the intersection against
  9048. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9049. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9050. */
  9051. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9052. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9053. var u = segb.subtract(sega);
  9054. var v = rsegb.subtract(this.origin);
  9055. var w = sega.subtract(this.origin);
  9056. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9057. var b = BABYLON.Vector3.Dot(u, v);
  9058. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9059. var d = BABYLON.Vector3.Dot(u, w);
  9060. var e = BABYLON.Vector3.Dot(v, w);
  9061. var D = a * c - b * b; // always >= 0
  9062. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9063. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9064. // compute the line parameters of the two closest points
  9065. if (D < Ray.smallnum) {
  9066. sN = 0.0; // force using point P0 on segment S1
  9067. sD = 1.0; // to prevent possible division by 0.0 later
  9068. tN = e;
  9069. tD = c;
  9070. }
  9071. else {
  9072. sN = (b * e - c * d);
  9073. tN = (a * e - b * d);
  9074. if (sN < 0.0) {
  9075. sN = 0.0;
  9076. tN = e;
  9077. tD = c;
  9078. }
  9079. else if (sN > sD) {
  9080. sN = sD;
  9081. tN = e + b;
  9082. tD = c;
  9083. }
  9084. }
  9085. if (tN < 0.0) {
  9086. tN = 0.0;
  9087. // recompute sc for this edge
  9088. if (-d < 0.0) {
  9089. sN = 0.0;
  9090. }
  9091. else if (-d > a)
  9092. sN = sD;
  9093. else {
  9094. sN = -d;
  9095. sD = a;
  9096. }
  9097. }
  9098. else if (tN > tD) {
  9099. tN = tD;
  9100. // recompute sc for this edge
  9101. if ((-d + b) < 0.0) {
  9102. sN = 0;
  9103. }
  9104. else if ((-d + b) > a) {
  9105. sN = sD;
  9106. }
  9107. else {
  9108. sN = (-d + b);
  9109. sD = a;
  9110. }
  9111. }
  9112. // finally do the division to get sc and tc
  9113. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9114. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9115. // get the difference of the two closest points
  9116. var qtc = v.multiplyByFloats(tc, tc, tc);
  9117. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9118. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9119. if (isIntersected) {
  9120. return qtc.length();
  9121. }
  9122. return -1;
  9123. };
  9124. // Statics
  9125. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9126. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9127. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9128. var direction = end.subtract(start);
  9129. direction.normalize();
  9130. return new Ray(start, direction);
  9131. };
  9132. /**
  9133. * 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
  9134. * transformed to the given world matrix.
  9135. * @param origin The origin point
  9136. * @param end The end point
  9137. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9138. */
  9139. Ray.CreateNewFromTo = function (origin, end, world) {
  9140. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9141. var direction = end.subtract(origin);
  9142. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9143. direction.normalize();
  9144. return Ray.Transform(new Ray(origin, direction, length), world);
  9145. };
  9146. Ray.Transform = function (ray, matrix) {
  9147. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9148. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9149. newDirection.normalize();
  9150. return new Ray(newOrigin, newDirection, ray.length);
  9151. };
  9152. Ray.smallnum = 0.00000001;
  9153. Ray.rayl = 10e8;
  9154. return Ray;
  9155. })();
  9156. BABYLON.Ray = Ray;
  9157. })(BABYLON || (BABYLON = {}));
  9158. var BABYLON;
  9159. (function (BABYLON) {
  9160. var AbstractMesh = (function (_super) {
  9161. __extends(AbstractMesh, _super);
  9162. // Constructor
  9163. function AbstractMesh(name, scene) {
  9164. var _this = this;
  9165. _super.call(this, name, scene);
  9166. // Events
  9167. /**
  9168. * An event triggered when the mesh is disposed.
  9169. * @type {BABYLON.Observable}
  9170. */
  9171. this.onDisposeObservable = new BABYLON.Observable();
  9172. /**
  9173. * An event triggered when this mesh collides with another one
  9174. * @type {BABYLON.Observable}
  9175. */
  9176. this.onCollideObservable = new BABYLON.Observable();
  9177. /**
  9178. * An event triggered when the collision's position changes
  9179. * @type {BABYLON.Observable}
  9180. */
  9181. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9182. /**
  9183. * An event triggered after the world matrix is updated
  9184. * @type {BABYLON.Observable}
  9185. */
  9186. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9187. // Properties
  9188. this.definedFacingForward = true; // orientation for POV movement & rotation
  9189. this.position = new BABYLON.Vector3(0, 0, 0);
  9190. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9191. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9192. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9193. this.visibility = 1.0;
  9194. this.alphaIndex = Number.MAX_VALUE;
  9195. this.infiniteDistance = false;
  9196. this.isVisible = true;
  9197. this.isPickable = true;
  9198. this.showBoundingBox = false;
  9199. this.showSubMeshesBoundingBox = false;
  9200. this.isBlocker = false;
  9201. this.renderingGroupId = 0;
  9202. this.receiveShadows = false;
  9203. this.renderOutline = false;
  9204. this.outlineColor = BABYLON.Color3.Red();
  9205. this.outlineWidth = 0.02;
  9206. this.renderOverlay = false;
  9207. this.overlayColor = BABYLON.Color3.Red();
  9208. this.overlayAlpha = 0.5;
  9209. this.hasVertexAlpha = false;
  9210. this.useVertexColors = true;
  9211. this.applyFog = true;
  9212. this.computeBonesUsingShaders = true;
  9213. this.scalingDeterminant = 1;
  9214. this.numBoneInfluencers = 4;
  9215. this.useOctreeForRenderingSelection = true;
  9216. this.useOctreeForPicking = true;
  9217. this.useOctreeForCollisions = true;
  9218. this.layerMask = 0x0FFFFFFF;
  9219. this.alwaysSelectAsActiveMesh = false;
  9220. // Collisions
  9221. this._checkCollisions = false;
  9222. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9223. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9224. this._collider = new BABYLON.Collider();
  9225. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9226. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9227. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9228. // Edges
  9229. this.edgesWidth = 1;
  9230. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9231. // Cache
  9232. this._localWorld = BABYLON.Matrix.Zero();
  9233. this._worldMatrix = BABYLON.Matrix.Zero();
  9234. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9235. this._absolutePosition = BABYLON.Vector3.Zero();
  9236. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9237. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9238. this._isDirty = false;
  9239. this._pivotMatrix = BABYLON.Matrix.Identity();
  9240. this._isDisposed = false;
  9241. this._renderId = 0;
  9242. this._intersectionsInProgress = new Array();
  9243. this._isWorldMatrixFrozen = false;
  9244. this._unIndexed = false;
  9245. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9246. if (collidedMesh === void 0) { collidedMesh = null; }
  9247. //TODO move this to the collision coordinator!
  9248. if (_this.getScene().workerCollisions)
  9249. newPosition.multiplyInPlace(_this._collider.radius);
  9250. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9251. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9252. _this.position.addInPlace(_this._diffPositionForCollisions);
  9253. }
  9254. if (collidedMesh) {
  9255. _this.onCollideObservable.notifyObservers(collidedMesh);
  9256. }
  9257. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9258. };
  9259. scene.addMesh(this);
  9260. }
  9261. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9262. get: function () {
  9263. return AbstractMesh._BILLBOARDMODE_NONE;
  9264. },
  9265. enumerable: true,
  9266. configurable: true
  9267. });
  9268. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9269. get: function () {
  9270. return AbstractMesh._BILLBOARDMODE_X;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9276. get: function () {
  9277. return AbstractMesh._BILLBOARDMODE_Y;
  9278. },
  9279. enumerable: true,
  9280. configurable: true
  9281. });
  9282. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9283. get: function () {
  9284. return AbstractMesh._BILLBOARDMODE_Z;
  9285. },
  9286. enumerable: true,
  9287. configurable: true
  9288. });
  9289. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9290. get: function () {
  9291. return AbstractMesh._BILLBOARDMODE_ALL;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9297. set: function (callback) {
  9298. if (this._onDisposeObserver) {
  9299. this.onDisposeObservable.remove(this._onDisposeObserver);
  9300. }
  9301. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9307. set: function (callback) {
  9308. if (this._onCollideObserver) {
  9309. this.onCollideObservable.remove(this._onCollideObserver);
  9310. }
  9311. this._onCollideObserver = this.onCollideObservable.add(callback);
  9312. },
  9313. enumerable: true,
  9314. configurable: true
  9315. });
  9316. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9317. set: function (callback) {
  9318. if (this._onCollisionPositionChangeObserver) {
  9319. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9320. }
  9321. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9327. get: function () {
  9328. return this._skeleton;
  9329. },
  9330. set: function (value) {
  9331. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9332. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9333. }
  9334. if (value && value.needInitialSkinMatrix) {
  9335. value._registerMeshWithPoseMatrix(this);
  9336. }
  9337. this._skeleton = value;
  9338. if (!this._skeleton) {
  9339. this._bonesTransformMatrices = null;
  9340. }
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. /**
  9346. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9347. */
  9348. AbstractMesh.prototype.toString = function (fullDetails) {
  9349. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9350. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9351. if (this._skeleton) {
  9352. ret += ", skeleton: " + this._skeleton.name;
  9353. }
  9354. if (fullDetails) {
  9355. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9356. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9357. }
  9358. return ret;
  9359. };
  9360. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9361. /**
  9362. * Getting the rotation object.
  9363. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9364. */
  9365. get: function () {
  9366. return this._rotation;
  9367. },
  9368. set: function (newRotation) {
  9369. this._rotation = newRotation;
  9370. },
  9371. enumerable: true,
  9372. configurable: true
  9373. });
  9374. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9375. get: function () {
  9376. return this._scaling;
  9377. },
  9378. set: function (newScaling) {
  9379. this._scaling = newScaling;
  9380. if (this.physicsImpostor) {
  9381. this.physicsImpostor.forceUpdate();
  9382. }
  9383. },
  9384. enumerable: true,
  9385. configurable: true
  9386. });
  9387. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9388. get: function () {
  9389. return this._rotationQuaternion;
  9390. },
  9391. set: function (quaternion) {
  9392. this._rotationQuaternion = quaternion;
  9393. //reset the rotation vector.
  9394. if (quaternion && this.rotation.length()) {
  9395. this.rotation.copyFromFloats(0, 0, 0);
  9396. }
  9397. },
  9398. enumerable: true,
  9399. configurable: true
  9400. });
  9401. // Methods
  9402. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9403. this._poseMatrix.copyFrom(matrix);
  9404. };
  9405. AbstractMesh.prototype.getPoseMatrix = function () {
  9406. return this._poseMatrix;
  9407. };
  9408. AbstractMesh.prototype.disableEdgesRendering = function () {
  9409. if (this._edgesRenderer !== undefined) {
  9410. this._edgesRenderer.dispose();
  9411. this._edgesRenderer = undefined;
  9412. }
  9413. };
  9414. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9415. if (epsilon === void 0) { epsilon = 0.95; }
  9416. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9417. this.disableEdgesRendering();
  9418. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9419. };
  9420. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9421. get: function () {
  9422. return false;
  9423. },
  9424. enumerable: true,
  9425. configurable: true
  9426. });
  9427. AbstractMesh.prototype.getLOD = function (camera) {
  9428. return this;
  9429. };
  9430. AbstractMesh.prototype.getTotalVertices = function () {
  9431. return 0;
  9432. };
  9433. AbstractMesh.prototype.getIndices = function () {
  9434. return null;
  9435. };
  9436. AbstractMesh.prototype.getVerticesData = function (kind) {
  9437. return null;
  9438. };
  9439. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9440. return false;
  9441. };
  9442. AbstractMesh.prototype.getBoundingInfo = function () {
  9443. if (this._masterMesh) {
  9444. return this._masterMesh.getBoundingInfo();
  9445. }
  9446. if (!this._boundingInfo) {
  9447. this._updateBoundingInfo();
  9448. }
  9449. return this._boundingInfo;
  9450. };
  9451. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9452. this._boundingInfo = boundingInfo;
  9453. };
  9454. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9455. get: function () {
  9456. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. AbstractMesh.prototype._preActivate = function () {
  9462. };
  9463. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9464. };
  9465. AbstractMesh.prototype._activate = function (renderId) {
  9466. this._renderId = renderId;
  9467. };
  9468. AbstractMesh.prototype.getWorldMatrix = function () {
  9469. if (this._masterMesh) {
  9470. return this._masterMesh.getWorldMatrix();
  9471. }
  9472. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9473. this.computeWorldMatrix();
  9474. }
  9475. return this._worldMatrix;
  9476. };
  9477. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9478. get: function () {
  9479. return this._worldMatrix;
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9485. get: function () {
  9486. return this._absolutePosition;
  9487. },
  9488. enumerable: true,
  9489. configurable: true
  9490. });
  9491. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9492. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9493. this.computeWorldMatrix(true);
  9494. this._isWorldMatrixFrozen = true;
  9495. };
  9496. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9497. this._isWorldMatrixFrozen = false;
  9498. this.computeWorldMatrix(true);
  9499. };
  9500. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9501. get: function () {
  9502. return this._isWorldMatrixFrozen;
  9503. },
  9504. enumerable: true,
  9505. configurable: true
  9506. });
  9507. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9508. axis.normalize();
  9509. if (!this.rotationQuaternion) {
  9510. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9511. this.rotation = BABYLON.Vector3.Zero();
  9512. }
  9513. var rotationQuaternion;
  9514. if (!space || space === BABYLON.Space.LOCAL) {
  9515. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9516. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9517. }
  9518. else {
  9519. if (this.parent) {
  9520. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9521. invertParentWorldMatrix.invert();
  9522. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9523. }
  9524. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9525. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9526. }
  9527. };
  9528. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9529. var displacementVector = axis.scale(distance);
  9530. if (!space || space === BABYLON.Space.LOCAL) {
  9531. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9532. this.setPositionWithLocalVector(tempV3);
  9533. }
  9534. else {
  9535. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9536. }
  9537. };
  9538. AbstractMesh.prototype.getAbsolutePosition = function () {
  9539. this.computeWorldMatrix();
  9540. return this._absolutePosition;
  9541. };
  9542. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9543. if (!absolutePosition) {
  9544. return;
  9545. }
  9546. var absolutePositionX;
  9547. var absolutePositionY;
  9548. var absolutePositionZ;
  9549. if (absolutePosition.x === undefined) {
  9550. if (arguments.length < 3) {
  9551. return;
  9552. }
  9553. absolutePositionX = arguments[0];
  9554. absolutePositionY = arguments[1];
  9555. absolutePositionZ = arguments[2];
  9556. }
  9557. else {
  9558. absolutePositionX = absolutePosition.x;
  9559. absolutePositionY = absolutePosition.y;
  9560. absolutePositionZ = absolutePosition.z;
  9561. }
  9562. if (this.parent) {
  9563. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9564. invertParentWorldMatrix.invert();
  9565. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9566. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9567. }
  9568. else {
  9569. this.position.x = absolutePositionX;
  9570. this.position.y = absolutePositionY;
  9571. this.position.z = absolutePositionZ;
  9572. }
  9573. };
  9574. // ================================== Point of View Movement =================================
  9575. /**
  9576. * Perform relative position change from the point of view of behind the front of the mesh.
  9577. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9578. * Supports definition of mesh facing forward or backward.
  9579. * @param {number} amountRight
  9580. * @param {number} amountUp
  9581. * @param {number} amountForward
  9582. */
  9583. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9584. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9585. };
  9586. /**
  9587. * Calculate relative position change from the point of view of behind the front of the mesh.
  9588. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9589. * Supports definition of mesh facing forward or backward.
  9590. * @param {number} amountRight
  9591. * @param {number} amountUp
  9592. * @param {number} amountForward
  9593. */
  9594. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9595. var rotMatrix = new BABYLON.Matrix();
  9596. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9597. rotQuaternion.toRotationMatrix(rotMatrix);
  9598. var translationDelta = BABYLON.Vector3.Zero();
  9599. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9601. return translationDelta;
  9602. };
  9603. // ================================== Point of View Rotation =================================
  9604. /**
  9605. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9606. * Supports definition of mesh facing forward or backward.
  9607. * @param {number} flipBack
  9608. * @param {number} twirlClockwise
  9609. * @param {number} tiltRight
  9610. */
  9611. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9612. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9613. };
  9614. /**
  9615. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9616. * Supports definition of mesh facing forward or backward.
  9617. * @param {number} flipBack
  9618. * @param {number} twirlClockwise
  9619. * @param {number} tiltRight
  9620. */
  9621. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9622. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9623. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9624. };
  9625. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9626. this._pivotMatrix = matrix;
  9627. this._cache.pivotMatrixUpdated = true;
  9628. };
  9629. AbstractMesh.prototype.getPivotMatrix = function () {
  9630. return this._pivotMatrix;
  9631. };
  9632. AbstractMesh.prototype._isSynchronized = function () {
  9633. if (this._isDirty) {
  9634. return false;
  9635. }
  9636. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9637. return false;
  9638. if (this._cache.pivotMatrixUpdated) {
  9639. return false;
  9640. }
  9641. if (this.infiniteDistance) {
  9642. return false;
  9643. }
  9644. if (!this._cache.position.equals(this.position))
  9645. return false;
  9646. if (this.rotationQuaternion) {
  9647. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9648. return false;
  9649. }
  9650. else {
  9651. if (!this._cache.rotation.equals(this.rotation))
  9652. return false;
  9653. }
  9654. if (!this._cache.scaling.equals(this.scaling))
  9655. return false;
  9656. return true;
  9657. };
  9658. AbstractMesh.prototype._initCache = function () {
  9659. _super.prototype._initCache.call(this);
  9660. this._cache.localMatrixUpdated = false;
  9661. this._cache.position = BABYLON.Vector3.Zero();
  9662. this._cache.scaling = BABYLON.Vector3.Zero();
  9663. this._cache.rotation = BABYLON.Vector3.Zero();
  9664. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9665. this._cache.billboardMode = -1;
  9666. };
  9667. AbstractMesh.prototype.markAsDirty = function (property) {
  9668. if (property === "rotation") {
  9669. this.rotationQuaternion = null;
  9670. }
  9671. this._currentRenderId = Number.MAX_VALUE;
  9672. this._isDirty = true;
  9673. };
  9674. AbstractMesh.prototype._updateBoundingInfo = function () {
  9675. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9676. this._boundingInfo.update(this.worldMatrixFromCache);
  9677. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9678. };
  9679. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9680. if (!this.subMeshes) {
  9681. return;
  9682. }
  9683. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9684. var subMesh = this.subMeshes[subIndex];
  9685. if (!subMesh.IsGlobal) {
  9686. subMesh.updateBoundingInfo(matrix);
  9687. }
  9688. }
  9689. };
  9690. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9691. if (this._isWorldMatrixFrozen) {
  9692. return this._worldMatrix;
  9693. }
  9694. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9695. this._currentRenderId = this.getScene().getRenderId();
  9696. return this._worldMatrix;
  9697. }
  9698. this._cache.position.copyFrom(this.position);
  9699. this._cache.scaling.copyFrom(this.scaling);
  9700. this._cache.pivotMatrixUpdated = false;
  9701. this._cache.billboardMode = this.billboardMode;
  9702. this._currentRenderId = this.getScene().getRenderId();
  9703. this._isDirty = false;
  9704. // Scaling
  9705. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9706. // Rotation
  9707. //rotate, if quaternion is set and rotation was used
  9708. if (this.rotationQuaternion) {
  9709. var len = this.rotation.length();
  9710. if (len) {
  9711. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9712. this.rotation.copyFromFloats(0, 0, 0);
  9713. }
  9714. }
  9715. if (this.rotationQuaternion) {
  9716. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9717. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9718. }
  9719. else {
  9720. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9721. this._cache.rotation.copyFrom(this.rotation);
  9722. }
  9723. // Translation
  9724. if (this.infiniteDistance && !this.parent) {
  9725. var camera = this.getScene().activeCamera;
  9726. if (camera) {
  9727. var cameraWorldMatrix = camera.getWorldMatrix();
  9728. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9729. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9730. }
  9731. }
  9732. else {
  9733. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9734. }
  9735. // Composing transformations
  9736. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9737. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9738. // Billboarding
  9739. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9740. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9741. var localPosition = BABYLON.Tmp.Vector3[0];
  9742. if (this.parent && this.parent.getWorldMatrix) {
  9743. this._markSyncedWithParent();
  9744. var parentMatrix;
  9745. if (this._meshToBoneReferal) {
  9746. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9747. parentMatrix = BABYLON.Tmp.Matrix[6];
  9748. }
  9749. else {
  9750. parentMatrix = this.parent.getWorldMatrix();
  9751. }
  9752. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9753. localPosition = BABYLON.Tmp.Vector3[1];
  9754. }
  9755. var zero = this.getScene().activeCamera.globalPosition.clone();
  9756. if (this.parent && this.parent.position) {
  9757. localPosition.addInPlace(this.parent.position);
  9758. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9759. }
  9760. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9761. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9762. zero.x = localPosition.x + BABYLON.Epsilon;
  9763. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9764. zero.y = localPosition.y + BABYLON.Epsilon;
  9765. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9766. zero.z = localPosition.z + BABYLON.Epsilon;
  9767. }
  9768. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9769. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9770. BABYLON.Tmp.Matrix[3].invert();
  9771. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9772. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9773. }
  9774. // Local world
  9775. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9776. // Parent
  9777. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9778. this._markSyncedWithParent();
  9779. if (this._meshToBoneReferal) {
  9780. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9781. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9782. }
  9783. else {
  9784. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9785. }
  9786. }
  9787. else {
  9788. this._worldMatrix.copyFrom(this._localWorld);
  9789. }
  9790. // Bounding info
  9791. this._updateBoundingInfo();
  9792. // Absolute position
  9793. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9794. // Callbacks
  9795. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9796. if (!this._poseMatrix) {
  9797. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9798. }
  9799. return this._worldMatrix;
  9800. };
  9801. /**
  9802. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9803. * @param func: callback function to add
  9804. */
  9805. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9806. this.onAfterWorldMatrixUpdateObservable.add(func);
  9807. };
  9808. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9809. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9810. };
  9811. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9812. this.computeWorldMatrix();
  9813. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9814. };
  9815. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9816. this.computeWorldMatrix();
  9817. var invLocalWorldMatrix = this._localWorld.clone();
  9818. invLocalWorldMatrix.invert();
  9819. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9820. };
  9821. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9822. this.computeWorldMatrix(true);
  9823. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9824. };
  9825. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9826. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9827. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9828. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9829. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9830. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9831. /// <returns>Mesh oriented towards targetMesh</returns>
  9832. if (yawCor === void 0) { yawCor = 0; }
  9833. if (pitchCor === void 0) { pitchCor = 0; }
  9834. if (rollCor === void 0) { rollCor = 0; }
  9835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  9836. var dv = AbstractMesh._lookAtVectorCache;
  9837. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  9838. targetPoint.subtractToRef(pos, dv);
  9839. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9840. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9841. var pitch = Math.atan2(dv.y, len);
  9842. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  9843. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  9844. };
  9845. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9846. this._meshToBoneReferal = affectedMesh;
  9847. this.parent = bone;
  9848. if (bone.getWorldMatrix().determinant() < 0) {
  9849. this.scalingDeterminant *= -1;
  9850. }
  9851. };
  9852. AbstractMesh.prototype.detachFromBone = function () {
  9853. if (this.parent.getWorldMatrix().determinant() < 0) {
  9854. this.scalingDeterminant *= -1;
  9855. }
  9856. this._meshToBoneReferal = null;
  9857. this.parent = null;
  9858. };
  9859. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9860. return this._boundingInfo.isInFrustum(frustumPlanes);
  9861. };
  9862. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9863. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  9864. ;
  9865. };
  9866. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9867. if (!this._boundingInfo || !mesh._boundingInfo) {
  9868. return false;
  9869. }
  9870. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9871. };
  9872. AbstractMesh.prototype.intersectsPoint = function (point) {
  9873. if (!this._boundingInfo) {
  9874. return false;
  9875. }
  9876. return this._boundingInfo.intersectsPoint(point);
  9877. };
  9878. // Physics
  9879. /**
  9880. * @Deprecated. Use new PhysicsImpostor instead.
  9881. * */
  9882. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9883. //legacy support
  9884. if (impostor.impostor) {
  9885. options = impostor;
  9886. impostor = impostor.impostor;
  9887. }
  9888. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9889. return this.physicsImpostor.physicsBody;
  9890. };
  9891. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9892. return this.physicsImpostor;
  9893. };
  9894. /**
  9895. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9896. */
  9897. AbstractMesh.prototype.getPhysicsMass = function () {
  9898. return this.physicsImpostor.getParam("mass");
  9899. };
  9900. /**
  9901. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9902. */
  9903. AbstractMesh.prototype.getPhysicsFriction = function () {
  9904. return this.physicsImpostor.getParam("friction");
  9905. };
  9906. /**
  9907. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9908. */
  9909. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9910. return this.physicsImpostor.getParam("restitution");
  9911. };
  9912. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9913. if (!camera) {
  9914. camera = this.getScene().activeCamera;
  9915. }
  9916. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9917. };
  9918. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9919. if (!camera) {
  9920. camera = this.getScene().activeCamera;
  9921. }
  9922. return this.absolutePosition.subtract(camera.position).length();
  9923. };
  9924. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9925. if (!this.physicsImpostor) {
  9926. return;
  9927. }
  9928. this.physicsImpostor.applyImpulse(force, contactPoint);
  9929. };
  9930. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9931. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9932. return;
  9933. }
  9934. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9935. mainPivot: pivot1,
  9936. connectedPivot: pivot2,
  9937. nativeParams: options
  9938. });
  9939. };
  9940. /**
  9941. * @Deprecated
  9942. */
  9943. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9944. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9945. this.updatePhysicsBody();
  9946. };
  9947. /**
  9948. * @Deprecated
  9949. * Calling this function is not needed anymore.
  9950. * The physics engine takes care of transofmration automatically.
  9951. */
  9952. AbstractMesh.prototype.updatePhysicsBody = function () {
  9953. //Unneeded
  9954. };
  9955. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9956. // Collisions
  9957. get: function () {
  9958. return this._checkCollisions;
  9959. },
  9960. set: function (collisionEnabled) {
  9961. this._checkCollisions = collisionEnabled;
  9962. if (this.getScene().workerCollisions) {
  9963. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9964. }
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9970. var globalPosition = this.getAbsolutePosition();
  9971. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9972. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9973. this._collider.radius = this.ellipsoid;
  9974. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9975. };
  9976. // Submeshes octree
  9977. /**
  9978. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9979. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9980. */
  9981. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9982. if (maxCapacity === void 0) { maxCapacity = 64; }
  9983. if (maxDepth === void 0) { maxDepth = 2; }
  9984. if (!this._submeshesOctree) {
  9985. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9986. }
  9987. this.computeWorldMatrix(true);
  9988. // Update octree
  9989. var bbox = this.getBoundingInfo().boundingBox;
  9990. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9991. return this._submeshesOctree;
  9992. };
  9993. // Collisions
  9994. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9995. this._generatePointsArray();
  9996. // Transformation
  9997. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9998. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9999. subMesh._lastColliderWorldVertices = [];
  10000. subMesh._trianglePlanes = [];
  10001. var start = subMesh.verticesStart;
  10002. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10003. for (var i = start; i < end; i++) {
  10004. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10005. }
  10006. }
  10007. // Collide
  10008. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10009. if (collider.collisionFound) {
  10010. collider.collidedMesh = this;
  10011. }
  10012. };
  10013. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10014. var subMeshes;
  10015. var len;
  10016. // Octrees
  10017. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10018. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10019. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10020. len = intersections.length;
  10021. subMeshes = intersections.data;
  10022. }
  10023. else {
  10024. subMeshes = this.subMeshes;
  10025. len = subMeshes.length;
  10026. }
  10027. for (var index = 0; index < len; index++) {
  10028. var subMesh = subMeshes[index];
  10029. // Bounding test
  10030. if (len > 1 && !subMesh._checkCollision(collider))
  10031. continue;
  10032. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10033. }
  10034. };
  10035. AbstractMesh.prototype._checkCollision = function (collider) {
  10036. // Bounding box test
  10037. if (!this._boundingInfo._checkCollision(collider))
  10038. return;
  10039. // Transformation matrix
  10040. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10041. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10042. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10043. };
  10044. // Picking
  10045. AbstractMesh.prototype._generatePointsArray = function () {
  10046. return false;
  10047. };
  10048. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10049. var pickingInfo = new BABYLON.PickingInfo();
  10050. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10051. return pickingInfo;
  10052. }
  10053. if (!this._generatePointsArray()) {
  10054. return pickingInfo;
  10055. }
  10056. var intersectInfo = null;
  10057. // Octrees
  10058. var subMeshes;
  10059. var len;
  10060. if (this._submeshesOctree && this.useOctreeForPicking) {
  10061. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10062. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10063. len = intersections.length;
  10064. subMeshes = intersections.data;
  10065. }
  10066. else {
  10067. subMeshes = this.subMeshes;
  10068. len = subMeshes.length;
  10069. }
  10070. for (var index = 0; index < len; index++) {
  10071. var subMesh = subMeshes[index];
  10072. // Bounding test
  10073. if (len > 1 && !subMesh.canIntersects(ray))
  10074. continue;
  10075. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10076. if (currentIntersectInfo) {
  10077. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10078. intersectInfo = currentIntersectInfo;
  10079. intersectInfo.subMeshId = index;
  10080. if (fastCheck) {
  10081. break;
  10082. }
  10083. }
  10084. }
  10085. }
  10086. if (intersectInfo) {
  10087. // Get picked point
  10088. var world = this.getWorldMatrix();
  10089. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10090. var direction = ray.direction.clone();
  10091. direction = direction.scale(intersectInfo.distance);
  10092. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10093. var pickedPoint = worldOrigin.add(worldDirection);
  10094. // Return result
  10095. pickingInfo.hit = true;
  10096. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10097. pickingInfo.pickedPoint = pickedPoint;
  10098. pickingInfo.pickedMesh = this;
  10099. pickingInfo.bu = intersectInfo.bu;
  10100. pickingInfo.bv = intersectInfo.bv;
  10101. pickingInfo.faceId = intersectInfo.faceId;
  10102. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10103. return pickingInfo;
  10104. }
  10105. return pickingInfo;
  10106. };
  10107. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10108. return null;
  10109. };
  10110. AbstractMesh.prototype.releaseSubMeshes = function () {
  10111. if (this.subMeshes) {
  10112. while (this.subMeshes.length) {
  10113. this.subMeshes[0].dispose();
  10114. }
  10115. }
  10116. else {
  10117. this.subMeshes = new Array();
  10118. }
  10119. };
  10120. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10121. var _this = this;
  10122. var index;
  10123. // Action manager
  10124. if (this.actionManager) {
  10125. this.actionManager.dispose();
  10126. this.actionManager = null;
  10127. }
  10128. // Skeleton
  10129. this.skeleton = null;
  10130. // Animations
  10131. this.getScene().stopAnimation(this);
  10132. // Physics
  10133. if (this.physicsImpostor) {
  10134. this.physicsImpostor.dispose();
  10135. }
  10136. // Intersections in progress
  10137. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10138. var other = this._intersectionsInProgress[index];
  10139. var pos = other._intersectionsInProgress.indexOf(this);
  10140. other._intersectionsInProgress.splice(pos, 1);
  10141. }
  10142. this._intersectionsInProgress = [];
  10143. // Lights
  10144. var lights = this.getScene().lights;
  10145. lights.forEach(function (light) {
  10146. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10147. if (meshIndex !== -1) {
  10148. light.includedOnlyMeshes.splice(meshIndex, 1);
  10149. }
  10150. meshIndex = light.excludedMeshes.indexOf(_this);
  10151. if (meshIndex !== -1) {
  10152. light.excludedMeshes.splice(meshIndex, 1);
  10153. }
  10154. });
  10155. // Edges
  10156. if (this._edgesRenderer) {
  10157. this._edgesRenderer.dispose();
  10158. this._edgesRenderer = null;
  10159. }
  10160. // SubMeshes
  10161. this.releaseSubMeshes();
  10162. // Remove from scene
  10163. this.getScene().removeMesh(this);
  10164. if (!doNotRecurse) {
  10165. // Particles
  10166. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10167. if (this.getScene().particleSystems[index].emitter === this) {
  10168. this.getScene().particleSystems[index].dispose();
  10169. index--;
  10170. }
  10171. }
  10172. // Children
  10173. var objects = this.getDescendants(true);
  10174. for (index = 0; index < objects.length; index++) {
  10175. objects[index].dispose();
  10176. }
  10177. }
  10178. else {
  10179. var childMeshes = this.getChildMeshes(true);
  10180. for (index = 0; index < childMeshes.length; index++) {
  10181. var child = childMeshes[index];
  10182. child.parent = null;
  10183. child.computeWorldMatrix(true);
  10184. }
  10185. }
  10186. _super.prototype.dispose.call(this);
  10187. this.onAfterWorldMatrixUpdateObservable.clear();
  10188. this.onCollideObservable.clear();
  10189. this.onCollisionPositionChangeObservable.clear();
  10190. this._isDisposed = true;
  10191. // Callback
  10192. this.onDisposeObservable.notifyObservers(this);
  10193. this.onDisposeObservable.clear();
  10194. };
  10195. // Statics
  10196. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10197. AbstractMesh._BILLBOARDMODE_X = 1;
  10198. AbstractMesh._BILLBOARDMODE_Y = 2;
  10199. AbstractMesh._BILLBOARDMODE_Z = 4;
  10200. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10201. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10202. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10203. return AbstractMesh;
  10204. })(BABYLON.Node);
  10205. BABYLON.AbstractMesh = AbstractMesh;
  10206. })(BABYLON || (BABYLON = {}));
  10207. var BABYLON;
  10208. (function (BABYLON) {
  10209. var Light = (function (_super) {
  10210. __extends(Light, _super);
  10211. function Light(name, scene) {
  10212. _super.call(this, name, scene);
  10213. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10214. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10215. this.intensity = 1.0;
  10216. this.range = Number.MAX_VALUE;
  10217. this.includeOnlyWithLayerMask = 0;
  10218. this.includedOnlyMeshes = new Array();
  10219. this.excludedMeshes = new Array();
  10220. this.excludeWithLayerMask = 0;
  10221. // PBR Properties.
  10222. this.radius = 0.00001;
  10223. this._excludedMeshesIds = new Array();
  10224. this._includedOnlyMeshesIds = new Array();
  10225. scene.addLight(this);
  10226. }
  10227. /**
  10228. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10229. */
  10230. Light.prototype.toString = function (fullDetails) {
  10231. var ret = "Name: " + this.name;
  10232. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10233. if (this.animations) {
  10234. for (var i = 0; i < this.animations.length; i++) {
  10235. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10236. }
  10237. }
  10238. if (fullDetails) {
  10239. }
  10240. return ret;
  10241. };
  10242. Light.prototype.getShadowGenerator = function () {
  10243. return this._shadowGenerator;
  10244. };
  10245. Light.prototype.getAbsolutePosition = function () {
  10246. return BABYLON.Vector3.Zero();
  10247. };
  10248. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10249. };
  10250. Light.prototype._getWorldMatrix = function () {
  10251. return BABYLON.Matrix.Identity();
  10252. };
  10253. Light.prototype.canAffectMesh = function (mesh) {
  10254. if (!mesh) {
  10255. return true;
  10256. }
  10257. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10258. return false;
  10259. }
  10260. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10261. return false;
  10262. }
  10263. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10264. return false;
  10265. }
  10266. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10267. return false;
  10268. }
  10269. return true;
  10270. };
  10271. Light.prototype.getWorldMatrix = function () {
  10272. this._currentRenderId = this.getScene().getRenderId();
  10273. var worldMatrix = this._getWorldMatrix();
  10274. if (this.parent && this.parent.getWorldMatrix) {
  10275. if (!this._parentedWorldMatrix) {
  10276. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10277. }
  10278. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10279. this._markSyncedWithParent();
  10280. return this._parentedWorldMatrix;
  10281. }
  10282. return worldMatrix;
  10283. };
  10284. Light.prototype.dispose = function () {
  10285. if (this._shadowGenerator) {
  10286. this._shadowGenerator.dispose();
  10287. this._shadowGenerator = null;
  10288. }
  10289. // Animations
  10290. this.getScene().stopAnimation(this);
  10291. // Remove from scene
  10292. this.getScene().removeLight(this);
  10293. _super.prototype.dispose.call(this);
  10294. };
  10295. Light.prototype.getTypeID = function () {
  10296. return 0;
  10297. };
  10298. Light.prototype.clone = function (name) {
  10299. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10300. };
  10301. Light.prototype.serialize = function () {
  10302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10303. // Type
  10304. serializationObject.type = this.getTypeID();
  10305. // Parent
  10306. if (this.parent) {
  10307. serializationObject.parentId = this.parent.id;
  10308. }
  10309. // Inclusion / exclusions
  10310. if (this.excludedMeshes.length > 0) {
  10311. serializationObject.excludedMeshesIds = [];
  10312. this.excludedMeshes.forEach(function (mesh) {
  10313. serializationObject.excludedMeshesIds.push(mesh.id);
  10314. });
  10315. }
  10316. if (this.includedOnlyMeshes.length > 0) {
  10317. serializationObject.includedOnlyMeshesIds = [];
  10318. this.includedOnlyMeshes.forEach(function (mesh) {
  10319. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10320. });
  10321. }
  10322. // Animations
  10323. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10324. serializationObject.ranges = this.serializeAnimationRanges();
  10325. return serializationObject;
  10326. };
  10327. Light.GetConstructorFromName = function (type, name, scene) {
  10328. switch (type) {
  10329. case 0:
  10330. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10331. case 1:
  10332. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10333. case 2:
  10334. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10335. case 3:
  10336. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10337. }
  10338. };
  10339. Light.Parse = function (parsedLight, scene) {
  10340. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10341. // Inclusion / exclusions
  10342. if (parsedLight.excludedMeshesIds) {
  10343. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10344. }
  10345. if (parsedLight.includedOnlyMeshesIds) {
  10346. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10347. }
  10348. // Parent
  10349. if (parsedLight.parentId) {
  10350. light._waitingParentId = parsedLight.parentId;
  10351. }
  10352. // Animations
  10353. if (parsedLight.animations) {
  10354. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10355. var parsedAnimation = parsedLight.animations[animationIndex];
  10356. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10357. }
  10358. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10359. }
  10360. if (parsedLight.autoAnimate) {
  10361. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10362. }
  10363. return light;
  10364. };
  10365. __decorate([
  10366. BABYLON.serializeAsColor3()
  10367. ], Light.prototype, "diffuse", void 0);
  10368. __decorate([
  10369. BABYLON.serializeAsColor3()
  10370. ], Light.prototype, "specular", void 0);
  10371. __decorate([
  10372. BABYLON.serialize()
  10373. ], Light.prototype, "intensity", void 0);
  10374. __decorate([
  10375. BABYLON.serialize()
  10376. ], Light.prototype, "range", void 0);
  10377. __decorate([
  10378. BABYLON.serialize()
  10379. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10380. __decorate([
  10381. BABYLON.serialize()
  10382. ], Light.prototype, "excludeWithLayerMask", void 0);
  10383. __decorate([
  10384. BABYLON.serialize()
  10385. ], Light.prototype, "radius", void 0);
  10386. return Light;
  10387. })(BABYLON.Node);
  10388. BABYLON.Light = Light;
  10389. })(BABYLON || (BABYLON = {}));
  10390. var BABYLON;
  10391. (function (BABYLON) {
  10392. var PointLight = (function (_super) {
  10393. __extends(PointLight, _super);
  10394. function PointLight(name, position, scene) {
  10395. _super.call(this, name, scene);
  10396. this.position = position;
  10397. }
  10398. PointLight.prototype.getAbsolutePosition = function () {
  10399. return this.transformedPosition ? this.transformedPosition : this.position;
  10400. };
  10401. PointLight.prototype.computeTransformedPosition = function () {
  10402. if (this.parent && this.parent.getWorldMatrix) {
  10403. if (!this.transformedPosition) {
  10404. this.transformedPosition = BABYLON.Vector3.Zero();
  10405. }
  10406. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10407. return true;
  10408. }
  10409. return false;
  10410. };
  10411. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10412. if (this.parent && this.parent.getWorldMatrix) {
  10413. this.computeTransformedPosition();
  10414. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10415. return;
  10416. }
  10417. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10418. };
  10419. PointLight.prototype.needCube = function () {
  10420. return true;
  10421. };
  10422. PointLight.prototype.supportsVSM = function () {
  10423. return false;
  10424. };
  10425. PointLight.prototype.needRefreshPerFrame = function () {
  10426. return false;
  10427. };
  10428. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10429. switch (faceIndex) {
  10430. case 0:
  10431. return new BABYLON.Vector3(1, 0, 0);
  10432. case 1:
  10433. return new BABYLON.Vector3(-1, 0, 0);
  10434. case 2:
  10435. return new BABYLON.Vector3(0, -1, 0);
  10436. case 3:
  10437. return new BABYLON.Vector3(0, 1, 0);
  10438. case 4:
  10439. return new BABYLON.Vector3(0, 0, 1);
  10440. case 5:
  10441. return new BABYLON.Vector3(0, 0, -1);
  10442. }
  10443. return BABYLON.Vector3.Zero();
  10444. };
  10445. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10446. var activeCamera = this.getScene().activeCamera;
  10447. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10448. };
  10449. PointLight.prototype._getWorldMatrix = function () {
  10450. if (!this._worldMatrix) {
  10451. this._worldMatrix = BABYLON.Matrix.Identity();
  10452. }
  10453. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10454. return this._worldMatrix;
  10455. };
  10456. PointLight.prototype.getTypeID = function () {
  10457. return 0;
  10458. };
  10459. __decorate([
  10460. BABYLON.serializeAsVector3()
  10461. ], PointLight.prototype, "position", void 0);
  10462. return PointLight;
  10463. })(BABYLON.Light);
  10464. BABYLON.PointLight = PointLight;
  10465. })(BABYLON || (BABYLON = {}));
  10466. var BABYLON;
  10467. (function (BABYLON) {
  10468. var SpotLight = (function (_super) {
  10469. __extends(SpotLight, _super);
  10470. function SpotLight(name, position, direction, angle, exponent, scene) {
  10471. _super.call(this, name, scene);
  10472. this.position = position;
  10473. this.direction = direction;
  10474. this.angle = angle;
  10475. this.exponent = exponent;
  10476. }
  10477. SpotLight.prototype.getAbsolutePosition = function () {
  10478. return this.transformedPosition ? this.transformedPosition : this.position;
  10479. };
  10480. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10481. var activeCamera = this.getScene().activeCamera;
  10482. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10483. };
  10484. SpotLight.prototype.needCube = function () {
  10485. return false;
  10486. };
  10487. SpotLight.prototype.supportsVSM = function () {
  10488. return true;
  10489. };
  10490. SpotLight.prototype.needRefreshPerFrame = function () {
  10491. return false;
  10492. };
  10493. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10494. return this.direction;
  10495. };
  10496. SpotLight.prototype.setDirectionToTarget = function (target) {
  10497. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10498. return this.direction;
  10499. };
  10500. SpotLight.prototype.computeTransformedPosition = function () {
  10501. if (this.parent && this.parent.getWorldMatrix) {
  10502. if (!this.transformedPosition) {
  10503. this.transformedPosition = BABYLON.Vector3.Zero();
  10504. }
  10505. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10506. return true;
  10507. }
  10508. return false;
  10509. };
  10510. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10511. var normalizeDirection;
  10512. if (this.parent && this.parent.getWorldMatrix) {
  10513. if (!this._transformedDirection) {
  10514. this._transformedDirection = BABYLON.Vector3.Zero();
  10515. }
  10516. this.computeTransformedPosition();
  10517. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10518. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10519. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10520. }
  10521. else {
  10522. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10523. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10524. }
  10525. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10526. };
  10527. SpotLight.prototype._getWorldMatrix = function () {
  10528. if (!this._worldMatrix) {
  10529. this._worldMatrix = BABYLON.Matrix.Identity();
  10530. }
  10531. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10532. return this._worldMatrix;
  10533. };
  10534. SpotLight.prototype.getTypeID = function () {
  10535. return 2;
  10536. };
  10537. __decorate([
  10538. BABYLON.serializeAsVector3()
  10539. ], SpotLight.prototype, "position", void 0);
  10540. __decorate([
  10541. BABYLON.serializeAsVector3()
  10542. ], SpotLight.prototype, "direction", void 0);
  10543. __decorate([
  10544. BABYLON.serialize()
  10545. ], SpotLight.prototype, "angle", void 0);
  10546. __decorate([
  10547. BABYLON.serialize()
  10548. ], SpotLight.prototype, "exponent", void 0);
  10549. return SpotLight;
  10550. })(BABYLON.Light);
  10551. BABYLON.SpotLight = SpotLight;
  10552. })(BABYLON || (BABYLON = {}));
  10553. var BABYLON;
  10554. (function (BABYLON) {
  10555. var HemisphericLight = (function (_super) {
  10556. __extends(HemisphericLight, _super);
  10557. function HemisphericLight(name, direction, scene) {
  10558. _super.call(this, name, scene);
  10559. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10560. this.direction = direction;
  10561. }
  10562. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10563. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10564. return this.direction;
  10565. };
  10566. HemisphericLight.prototype.getShadowGenerator = function () {
  10567. return null;
  10568. };
  10569. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10570. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10571. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10572. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10573. };
  10574. HemisphericLight.prototype._getWorldMatrix = function () {
  10575. if (!this._worldMatrix) {
  10576. this._worldMatrix = BABYLON.Matrix.Identity();
  10577. }
  10578. return this._worldMatrix;
  10579. };
  10580. HemisphericLight.prototype.getTypeID = function () {
  10581. return 3;
  10582. };
  10583. __decorate([
  10584. BABYLON.serializeAsColor3()
  10585. ], HemisphericLight.prototype, "groundColor", void 0);
  10586. __decorate([
  10587. BABYLON.serializeAsVector3()
  10588. ], HemisphericLight.prototype, "direction", void 0);
  10589. return HemisphericLight;
  10590. })(BABYLON.Light);
  10591. BABYLON.HemisphericLight = HemisphericLight;
  10592. })(BABYLON || (BABYLON = {}));
  10593. var BABYLON;
  10594. (function (BABYLON) {
  10595. var DirectionalLight = (function (_super) {
  10596. __extends(DirectionalLight, _super);
  10597. function DirectionalLight(name, direction, scene) {
  10598. _super.call(this, name, scene);
  10599. this.shadowOrthoScale = 0.5;
  10600. this.autoUpdateExtends = true;
  10601. // Cache
  10602. this._orthoLeft = Number.MAX_VALUE;
  10603. this._orthoRight = Number.MIN_VALUE;
  10604. this._orthoTop = Number.MIN_VALUE;
  10605. this._orthoBottom = Number.MAX_VALUE;
  10606. this.position = direction.scale(-1);
  10607. this.direction = direction;
  10608. }
  10609. DirectionalLight.prototype.getAbsolutePosition = function () {
  10610. return this.transformedPosition ? this.transformedPosition : this.position;
  10611. };
  10612. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10613. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10614. return this.direction;
  10615. };
  10616. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10617. var activeCamera = this.getScene().activeCamera;
  10618. // Check extends
  10619. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10620. var tempVector3 = BABYLON.Vector3.Zero();
  10621. this._orthoLeft = Number.MAX_VALUE;
  10622. this._orthoRight = Number.MIN_VALUE;
  10623. this._orthoTop = Number.MIN_VALUE;
  10624. this._orthoBottom = Number.MAX_VALUE;
  10625. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10626. var mesh = renderList[meshIndex];
  10627. if (!mesh) {
  10628. continue;
  10629. }
  10630. var boundingInfo = mesh.getBoundingInfo();
  10631. if (!boundingInfo) {
  10632. continue;
  10633. }
  10634. var boundingBox = boundingInfo.boundingBox;
  10635. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10636. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10637. if (tempVector3.x < this._orthoLeft)
  10638. this._orthoLeft = tempVector3.x;
  10639. if (tempVector3.y < this._orthoBottom)
  10640. this._orthoBottom = tempVector3.y;
  10641. if (tempVector3.x > this._orthoRight)
  10642. this._orthoRight = tempVector3.x;
  10643. if (tempVector3.y > this._orthoTop)
  10644. this._orthoTop = tempVector3.y;
  10645. }
  10646. }
  10647. }
  10648. var xOffset = this._orthoRight - this._orthoLeft;
  10649. var yOffset = this._orthoTop - this._orthoBottom;
  10650. 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);
  10651. };
  10652. DirectionalLight.prototype.supportsVSM = function () {
  10653. return true;
  10654. };
  10655. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10656. return true;
  10657. };
  10658. DirectionalLight.prototype.needCube = function () {
  10659. return false;
  10660. };
  10661. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10662. return this.direction;
  10663. };
  10664. DirectionalLight.prototype.computeTransformedPosition = function () {
  10665. if (this.parent && this.parent.getWorldMatrix) {
  10666. if (!this.transformedPosition) {
  10667. this.transformedPosition = BABYLON.Vector3.Zero();
  10668. }
  10669. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10670. return true;
  10671. }
  10672. return false;
  10673. };
  10674. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10675. if (this.parent && this.parent.getWorldMatrix) {
  10676. if (!this._transformedDirection) {
  10677. this._transformedDirection = BABYLON.Vector3.Zero();
  10678. }
  10679. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10680. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10681. return;
  10682. }
  10683. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10684. };
  10685. DirectionalLight.prototype._getWorldMatrix = function () {
  10686. if (!this._worldMatrix) {
  10687. this._worldMatrix = BABYLON.Matrix.Identity();
  10688. }
  10689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10690. return this._worldMatrix;
  10691. };
  10692. DirectionalLight.prototype.getTypeID = function () {
  10693. return 1;
  10694. };
  10695. __decorate([
  10696. BABYLON.serializeAsVector3()
  10697. ], DirectionalLight.prototype, "position", void 0);
  10698. __decorate([
  10699. BABYLON.serializeAsVector3()
  10700. ], DirectionalLight.prototype, "direction", void 0);
  10701. __decorate([
  10702. BABYLON.serialize()
  10703. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10704. __decorate([
  10705. BABYLON.serialize()
  10706. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10707. return DirectionalLight;
  10708. })(BABYLON.Light);
  10709. BABYLON.DirectionalLight = DirectionalLight;
  10710. })(BABYLON || (BABYLON = {}));
  10711. var BABYLON;
  10712. (function (BABYLON) {
  10713. var ShadowGenerator = (function () {
  10714. function ShadowGenerator(mapSize, light) {
  10715. var _this = this;
  10716. // Members
  10717. this._filter = ShadowGenerator.FILTER_NONE;
  10718. this.blurScale = 2;
  10719. this._blurBoxOffset = 0;
  10720. this._bias = 0.00005;
  10721. this._lightDirection = BABYLON.Vector3.Zero();
  10722. this.forceBackFacesOnly = false;
  10723. this._darkness = 0;
  10724. this._transparencyShadow = false;
  10725. this._viewMatrix = BABYLON.Matrix.Zero();
  10726. this._projectionMatrix = BABYLON.Matrix.Zero();
  10727. this._transformMatrix = BABYLON.Matrix.Zero();
  10728. this._worldViewProjection = BABYLON.Matrix.Zero();
  10729. this._currentFaceIndex = 0;
  10730. this._currentFaceIndexCache = 0;
  10731. this._useFullFloat = true;
  10732. this._light = light;
  10733. this._scene = light.getScene();
  10734. this._mapSize = mapSize;
  10735. light._shadowGenerator = this;
  10736. // Texture type fallback from float to int if not supported.
  10737. var textureType;
  10738. if (this._scene.getEngine().getCaps().textureFloat) {
  10739. this._useFullFloat = true;
  10740. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  10741. }
  10742. else {
  10743. this._useFullFloat = false;
  10744. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  10745. }
  10746. // Render target
  10747. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  10748. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10749. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10750. this._shadowMap.anisotropicFilteringLevel = 1;
  10751. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10752. this._shadowMap.renderParticles = false;
  10753. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10754. _this._currentFaceIndex = faceIndex;
  10755. });
  10756. this._shadowMap.onAfterUnbindObservable.add(function () {
  10757. if (!_this.useBlurVarianceShadowMap) {
  10758. return;
  10759. }
  10760. if (!_this._shadowMap2) {
  10761. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  10762. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10763. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10764. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10765. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10766. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10767. effect.setTexture("textureSampler", _this._shadowMap);
  10768. });
  10769. _this.blurBoxOffset = 1;
  10770. }
  10771. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10772. });
  10773. // Custom render function
  10774. var renderSubMesh = function (subMesh) {
  10775. var mesh = subMesh.getRenderingMesh();
  10776. var scene = _this._scene;
  10777. var engine = scene.getEngine();
  10778. // Culling
  10779. engine.setState(subMesh.getMaterial().backFaceCulling);
  10780. // Managing instances
  10781. var batch = mesh._getInstancesRenderList(subMesh._id);
  10782. if (batch.mustReturn) {
  10783. return;
  10784. }
  10785. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10786. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10787. engine.enableEffect(_this._effect);
  10788. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10789. var material = subMesh.getMaterial();
  10790. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10791. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10792. if (_this.getLight().needCube()) {
  10793. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10794. }
  10795. // Alpha test
  10796. if (material && material.needAlphaTesting()) {
  10797. var alphaTexture = material.getAlphaTestTexture();
  10798. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10799. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10800. }
  10801. // Bones
  10802. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10803. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10804. }
  10805. if (_this.forceBackFacesOnly) {
  10806. engine.setState(true, 0, false, true);
  10807. }
  10808. // Draw
  10809. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10810. if (_this.forceBackFacesOnly) {
  10811. engine.setState(true, 0, false, false);
  10812. }
  10813. }
  10814. else {
  10815. // Need to reset refresh rate of the shadowMap
  10816. _this._shadowMap.resetRefreshCounter();
  10817. }
  10818. };
  10819. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10820. var index;
  10821. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10822. renderSubMesh(opaqueSubMeshes.data[index]);
  10823. }
  10824. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10825. renderSubMesh(alphaTestSubMeshes.data[index]);
  10826. }
  10827. if (_this._transparencyShadow) {
  10828. for (index = 0; index < transparentSubMeshes.length; index++) {
  10829. renderSubMesh(transparentSubMeshes.data[index]);
  10830. }
  10831. }
  10832. };
  10833. this._shadowMap.onClearObservable.add(function (engine) {
  10834. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10835. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10836. }
  10837. else {
  10838. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10839. }
  10840. });
  10841. }
  10842. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10843. // Static
  10844. get: function () {
  10845. return ShadowGenerator._FILTER_NONE;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10851. get: function () {
  10852. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10858. get: function () {
  10859. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10865. get: function () {
  10866. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10872. get: function () {
  10873. return this._bias;
  10874. },
  10875. set: function (bias) {
  10876. this._bias = bias;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10882. get: function () {
  10883. return this._blurBoxOffset;
  10884. },
  10885. set: function (value) {
  10886. var _this = this;
  10887. if (this._blurBoxOffset === value) {
  10888. return;
  10889. }
  10890. this._blurBoxOffset = value;
  10891. if (this._boxBlurPostprocess) {
  10892. this._boxBlurPostprocess.dispose();
  10893. }
  10894. 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);
  10895. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10896. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10897. });
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10903. get: function () {
  10904. return this._filter;
  10905. },
  10906. set: function (value) {
  10907. if (this._filter === value) {
  10908. return;
  10909. }
  10910. this._filter = value;
  10911. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10912. this._shadowMap.anisotropicFilteringLevel = 16;
  10913. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10914. }
  10915. else {
  10916. this._shadowMap.anisotropicFilteringLevel = 1;
  10917. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10918. }
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10924. get: function () {
  10925. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10926. },
  10927. set: function (value) {
  10928. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10934. get: function () {
  10935. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10936. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10937. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10938. },
  10939. set: function (value) {
  10940. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10946. get: function () {
  10947. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10948. },
  10949. set: function (value) {
  10950. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10956. var defines = [];
  10957. if (this._useFullFloat) {
  10958. defines.push("#define FULLFLOAT");
  10959. }
  10960. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10961. defines.push("#define VSM");
  10962. }
  10963. if (this.getLight().needCube()) {
  10964. defines.push("#define CUBEMAP");
  10965. }
  10966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10967. var mesh = subMesh.getMesh();
  10968. var material = subMesh.getMaterial();
  10969. // Alpha test
  10970. if (material && material.needAlphaTesting()) {
  10971. defines.push("#define ALPHATEST");
  10972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10973. attribs.push(BABYLON.VertexBuffer.UVKind);
  10974. defines.push("#define UV1");
  10975. }
  10976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10977. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10978. defines.push("#define UV2");
  10979. }
  10980. }
  10981. // Bones
  10982. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10985. if (mesh.numBoneInfluencers > 4) {
  10986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10988. }
  10989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10990. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10991. }
  10992. else {
  10993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10994. }
  10995. // Instances
  10996. if (useInstances) {
  10997. defines.push("#define INSTANCES");
  10998. attribs.push("world0");
  10999. attribs.push("world1");
  11000. attribs.push("world2");
  11001. attribs.push("world3");
  11002. }
  11003. // Get correct effect
  11004. var join = defines.join("\n");
  11005. if (this._cachedDefines !== join) {
  11006. this._cachedDefines = join;
  11007. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11008. }
  11009. return this._effect.isReady();
  11010. };
  11011. ShadowGenerator.prototype.getShadowMap = function () {
  11012. return this._shadowMap;
  11013. };
  11014. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11015. if (this._shadowMap2) {
  11016. return this._shadowMap2;
  11017. }
  11018. return this._shadowMap;
  11019. };
  11020. ShadowGenerator.prototype.getLight = function () {
  11021. return this._light;
  11022. };
  11023. // Methods
  11024. ShadowGenerator.prototype.getTransformMatrix = function () {
  11025. var scene = this._scene;
  11026. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11027. return this._transformMatrix;
  11028. }
  11029. this._currentRenderID = scene.getRenderId();
  11030. this._currentFaceIndexCache = this._currentFaceIndex;
  11031. var lightPosition = this._light.position;
  11032. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11033. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11034. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11035. }
  11036. if (this._light.computeTransformedPosition()) {
  11037. lightPosition = this._light.transformedPosition;
  11038. }
  11039. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11040. this._cachedPosition = lightPosition.clone();
  11041. this._cachedDirection = this._lightDirection.clone();
  11042. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11043. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11044. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11045. }
  11046. return this._transformMatrix;
  11047. };
  11048. ShadowGenerator.prototype.getDarkness = function () {
  11049. return this._darkness;
  11050. };
  11051. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11052. if (darkness >= 1.0)
  11053. this._darkness = 1.0;
  11054. else if (darkness <= 0.0)
  11055. this._darkness = 0.0;
  11056. else
  11057. this._darkness = darkness;
  11058. };
  11059. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11060. this._transparencyShadow = hasShadow;
  11061. };
  11062. ShadowGenerator.prototype._packHalf = function (depth) {
  11063. var scale = depth * 255.0;
  11064. var fract = scale - Math.floor(scale);
  11065. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11066. };
  11067. ShadowGenerator.prototype.dispose = function () {
  11068. this._shadowMap.dispose();
  11069. if (this._shadowMap2) {
  11070. this._shadowMap2.dispose();
  11071. }
  11072. if (this._downSamplePostprocess) {
  11073. this._downSamplePostprocess.dispose();
  11074. }
  11075. if (this._boxBlurPostprocess) {
  11076. this._boxBlurPostprocess.dispose();
  11077. }
  11078. };
  11079. ShadowGenerator.prototype.serialize = function () {
  11080. var serializationObject = {};
  11081. serializationObject.lightId = this._light.id;
  11082. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11083. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11084. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11085. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11086. serializationObject.renderList = [];
  11087. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11088. var mesh = this.getShadowMap().renderList[meshIndex];
  11089. serializationObject.renderList.push(mesh.id);
  11090. }
  11091. return serializationObject;
  11092. };
  11093. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11094. //casting to point light, as light is missing the position attr and typescript complains.
  11095. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11096. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11097. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11098. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11099. meshes.forEach(function (mesh) {
  11100. shadowGenerator.getShadowMap().renderList.push(mesh);
  11101. });
  11102. }
  11103. if (parsedShadowGenerator.usePoissonSampling) {
  11104. shadowGenerator.usePoissonSampling = true;
  11105. }
  11106. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11107. shadowGenerator.useVarianceShadowMap = true;
  11108. }
  11109. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11110. shadowGenerator.useBlurVarianceShadowMap = true;
  11111. if (parsedShadowGenerator.blurScale) {
  11112. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11113. }
  11114. if (parsedShadowGenerator.blurBoxOffset) {
  11115. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11116. }
  11117. }
  11118. if (parsedShadowGenerator.bias !== undefined) {
  11119. shadowGenerator.bias = parsedShadowGenerator.bias;
  11120. }
  11121. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11122. return shadowGenerator;
  11123. };
  11124. ShadowGenerator._FILTER_NONE = 0;
  11125. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11126. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11127. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11128. return ShadowGenerator;
  11129. })();
  11130. BABYLON.ShadowGenerator = ShadowGenerator;
  11131. })(BABYLON || (BABYLON = {}));
  11132. var BABYLON;
  11133. (function (BABYLON) {
  11134. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11135. if (boxMin.x > sphereCenter.x + sphereRadius)
  11136. return false;
  11137. if (sphereCenter.x - sphereRadius > boxMax.x)
  11138. return false;
  11139. if (boxMin.y > sphereCenter.y + sphereRadius)
  11140. return false;
  11141. if (sphereCenter.y - sphereRadius > boxMax.y)
  11142. return false;
  11143. if (boxMin.z > sphereCenter.z + sphereRadius)
  11144. return false;
  11145. if (sphereCenter.z - sphereRadius > boxMax.z)
  11146. return false;
  11147. return true;
  11148. };
  11149. var getLowestRoot = (function () {
  11150. var result = { root: 0, found: false };
  11151. return function (a, b, c, maxR) {
  11152. result.root = 0;
  11153. result.found = false;
  11154. var determinant = b * b - 4.0 * a * c;
  11155. if (determinant < 0)
  11156. return result;
  11157. var sqrtD = Math.sqrt(determinant);
  11158. var r1 = (-b - sqrtD) / (2.0 * a);
  11159. var r2 = (-b + sqrtD) / (2.0 * a);
  11160. if (r1 > r2) {
  11161. var temp = r2;
  11162. r2 = r1;
  11163. r1 = temp;
  11164. }
  11165. if (r1 > 0 && r1 < maxR) {
  11166. result.root = r1;
  11167. result.found = true;
  11168. return result;
  11169. }
  11170. if (r2 > 0 && r2 < maxR) {
  11171. result.root = r2;
  11172. result.found = true;
  11173. return result;
  11174. }
  11175. return result;
  11176. };
  11177. })();
  11178. var Collider = (function () {
  11179. function Collider() {
  11180. this.radius = new BABYLON.Vector3(1, 1, 1);
  11181. this.retry = 0;
  11182. this.basePointWorld = BABYLON.Vector3.Zero();
  11183. this.velocityWorld = BABYLON.Vector3.Zero();
  11184. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11185. this._collisionPoint = BABYLON.Vector3.Zero();
  11186. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11187. this._tempVector = BABYLON.Vector3.Zero();
  11188. this._tempVector2 = BABYLON.Vector3.Zero();
  11189. this._tempVector3 = BABYLON.Vector3.Zero();
  11190. this._tempVector4 = BABYLON.Vector3.Zero();
  11191. this._edge = BABYLON.Vector3.Zero();
  11192. this._baseToVertex = BABYLON.Vector3.Zero();
  11193. this._destinationPoint = BABYLON.Vector3.Zero();
  11194. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11195. this._displacementVector = BABYLON.Vector3.Zero();
  11196. }
  11197. // Methods
  11198. Collider.prototype._initialize = function (source, dir, e) {
  11199. this.velocity = dir;
  11200. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11201. this.basePoint = source;
  11202. source.multiplyToRef(this.radius, this.basePointWorld);
  11203. dir.multiplyToRef(this.radius, this.velocityWorld);
  11204. this.velocityWorldLength = this.velocityWorld.length();
  11205. this.epsilon = e;
  11206. this.collisionFound = false;
  11207. };
  11208. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11209. pa.subtractToRef(point, this._tempVector);
  11210. pb.subtractToRef(point, this._tempVector2);
  11211. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11212. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11213. if (d < 0)
  11214. return false;
  11215. pc.subtractToRef(point, this._tempVector3);
  11216. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11217. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11218. if (d < 0)
  11219. return false;
  11220. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11221. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11222. return d >= 0;
  11223. };
  11224. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11225. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11226. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11227. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11228. return false;
  11229. }
  11230. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11231. return false;
  11232. return true;
  11233. };
  11234. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11235. var t0;
  11236. var embeddedInPlane = false;
  11237. //defensive programming, actually not needed.
  11238. if (!trianglePlaneArray) {
  11239. trianglePlaneArray = [];
  11240. }
  11241. if (!trianglePlaneArray[faceIndex]) {
  11242. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11243. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11244. }
  11245. var trianglePlane = trianglePlaneArray[faceIndex];
  11246. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11247. return;
  11248. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11249. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11250. if (normalDotVelocity == 0) {
  11251. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11252. return;
  11253. embeddedInPlane = true;
  11254. t0 = 0;
  11255. }
  11256. else {
  11257. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11258. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11259. if (t0 > t1) {
  11260. var temp = t1;
  11261. t1 = t0;
  11262. t0 = temp;
  11263. }
  11264. if (t0 > 1.0 || t1 < 0.0)
  11265. return;
  11266. if (t0 < 0)
  11267. t0 = 0;
  11268. if (t0 > 1.0)
  11269. t0 = 1.0;
  11270. }
  11271. this._collisionPoint.copyFromFloats(0, 0, 0);
  11272. var found = false;
  11273. var t = 1.0;
  11274. if (!embeddedInPlane) {
  11275. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11276. this.velocity.scaleToRef(t0, this._tempVector);
  11277. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11278. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11279. found = true;
  11280. t = t0;
  11281. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11282. }
  11283. }
  11284. if (!found) {
  11285. var velocitySquaredLength = this.velocity.lengthSquared();
  11286. var a = velocitySquaredLength;
  11287. this.basePoint.subtractToRef(p1, this._tempVector);
  11288. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11289. var c = this._tempVector.lengthSquared() - 1.0;
  11290. var lowestRoot = getLowestRoot(a, b, c, t);
  11291. if (lowestRoot.found) {
  11292. t = lowestRoot.root;
  11293. found = true;
  11294. this._collisionPoint.copyFrom(p1);
  11295. }
  11296. this.basePoint.subtractToRef(p2, this._tempVector);
  11297. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11298. c = this._tempVector.lengthSquared() - 1.0;
  11299. lowestRoot = getLowestRoot(a, b, c, t);
  11300. if (lowestRoot.found) {
  11301. t = lowestRoot.root;
  11302. found = true;
  11303. this._collisionPoint.copyFrom(p2);
  11304. }
  11305. this.basePoint.subtractToRef(p3, this._tempVector);
  11306. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11307. c = this._tempVector.lengthSquared() - 1.0;
  11308. lowestRoot = getLowestRoot(a, b, c, t);
  11309. if (lowestRoot.found) {
  11310. t = lowestRoot.root;
  11311. found = true;
  11312. this._collisionPoint.copyFrom(p3);
  11313. }
  11314. p2.subtractToRef(p1, this._edge);
  11315. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11316. var edgeSquaredLength = this._edge.lengthSquared();
  11317. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11318. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11319. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11320. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11321. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11322. lowestRoot = getLowestRoot(a, b, c, t);
  11323. if (lowestRoot.found) {
  11324. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11325. if (f >= 0.0 && f <= 1.0) {
  11326. t = lowestRoot.root;
  11327. found = true;
  11328. this._edge.scaleInPlace(f);
  11329. p1.addToRef(this._edge, this._collisionPoint);
  11330. }
  11331. }
  11332. p3.subtractToRef(p2, this._edge);
  11333. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11334. edgeSquaredLength = this._edge.lengthSquared();
  11335. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11336. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11337. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11338. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11339. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11340. lowestRoot = getLowestRoot(a, b, c, t);
  11341. if (lowestRoot.found) {
  11342. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11343. if (f >= 0.0 && f <= 1.0) {
  11344. t = lowestRoot.root;
  11345. found = true;
  11346. this._edge.scaleInPlace(f);
  11347. p2.addToRef(this._edge, this._collisionPoint);
  11348. }
  11349. }
  11350. p1.subtractToRef(p3, this._edge);
  11351. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11352. edgeSquaredLength = this._edge.lengthSquared();
  11353. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11354. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11355. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11356. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11357. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11358. lowestRoot = getLowestRoot(a, b, c, t);
  11359. if (lowestRoot.found) {
  11360. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11361. if (f >= 0.0 && f <= 1.0) {
  11362. t = lowestRoot.root;
  11363. found = true;
  11364. this._edge.scaleInPlace(f);
  11365. p3.addToRef(this._edge, this._collisionPoint);
  11366. }
  11367. }
  11368. }
  11369. if (found) {
  11370. var distToCollision = t * this.velocity.length();
  11371. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11372. if (!this.intersectionPoint) {
  11373. this.intersectionPoint = this._collisionPoint.clone();
  11374. }
  11375. else {
  11376. this.intersectionPoint.copyFrom(this._collisionPoint);
  11377. }
  11378. this.nearestDistance = distToCollision;
  11379. this.collisionFound = true;
  11380. }
  11381. }
  11382. };
  11383. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11384. for (var i = indexStart; i < indexEnd; i += 3) {
  11385. var p1 = pts[indices[i] - decal];
  11386. var p2 = pts[indices[i + 1] - decal];
  11387. var p3 = pts[indices[i + 2] - decal];
  11388. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11389. }
  11390. };
  11391. Collider.prototype._getResponse = function (pos, vel) {
  11392. pos.addToRef(vel, this._destinationPoint);
  11393. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11394. this.basePoint.addToRef(vel, pos);
  11395. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11396. this._slidePlaneNormal.normalize();
  11397. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11398. pos.addInPlace(this._displacementVector);
  11399. this.intersectionPoint.addInPlace(this._displacementVector);
  11400. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11401. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11402. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11403. };
  11404. return Collider;
  11405. })();
  11406. BABYLON.Collider = Collider;
  11407. })(BABYLON || (BABYLON = {}));
  11408. var BABYLON;
  11409. (function (BABYLON) {
  11410. //WebWorker code will be inserted to this variable.
  11411. BABYLON.CollisionWorker = "";
  11412. (function (WorkerTaskType) {
  11413. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11414. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11415. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11416. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11417. var WorkerTaskType = BABYLON.WorkerTaskType;
  11418. (function (WorkerReplyType) {
  11419. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11420. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11421. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11422. var WorkerReplyType = BABYLON.WorkerReplyType;
  11423. var CollisionCoordinatorWorker = (function () {
  11424. function CollisionCoordinatorWorker() {
  11425. var _this = this;
  11426. this._scaledPosition = BABYLON.Vector3.Zero();
  11427. this._scaledVelocity = BABYLON.Vector3.Zero();
  11428. this.onMeshUpdated = function (mesh) {
  11429. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11430. };
  11431. this.onGeometryUpdated = function (geometry) {
  11432. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11433. };
  11434. this._afterRender = function () {
  11435. if (!_this._init)
  11436. return;
  11437. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11438. return;
  11439. }
  11440. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11441. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11442. if (_this._runningUpdated > 4) {
  11443. return;
  11444. }
  11445. ++_this._runningUpdated;
  11446. var payload = {
  11447. updatedMeshes: _this._addUpdateMeshesList,
  11448. updatedGeometries: _this._addUpdateGeometriesList,
  11449. removedGeometries: _this._toRemoveGeometryArray,
  11450. removedMeshes: _this._toRemoveMeshesArray
  11451. };
  11452. var message = {
  11453. payload: payload,
  11454. taskType: WorkerTaskType.UPDATE
  11455. };
  11456. var serializable = [];
  11457. for (var id in payload.updatedGeometries) {
  11458. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11459. //prepare transferables
  11460. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11461. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11462. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11463. }
  11464. }
  11465. _this._worker.postMessage(message, serializable);
  11466. _this._addUpdateMeshesList = {};
  11467. _this._addUpdateGeometriesList = {};
  11468. _this._toRemoveGeometryArray = [];
  11469. _this._toRemoveMeshesArray = [];
  11470. };
  11471. this._onMessageFromWorker = function (e) {
  11472. var returnData = e.data;
  11473. if (returnData.error != WorkerReplyType.SUCCESS) {
  11474. //TODO what errors can be returned from the worker?
  11475. BABYLON.Tools.Warn("error returned from worker!");
  11476. return;
  11477. }
  11478. switch (returnData.taskType) {
  11479. case WorkerTaskType.INIT:
  11480. _this._init = true;
  11481. //Update the worked with ALL of the scene's current state
  11482. _this._scene.meshes.forEach(function (mesh) {
  11483. _this.onMeshAdded(mesh);
  11484. });
  11485. _this._scene.getGeometries().forEach(function (geometry) {
  11486. _this.onGeometryAdded(geometry);
  11487. });
  11488. break;
  11489. case WorkerTaskType.UPDATE:
  11490. _this._runningUpdated--;
  11491. break;
  11492. case WorkerTaskType.COLLIDE:
  11493. _this._runningCollisionTask = false;
  11494. var returnPayload = returnData.payload;
  11495. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11496. return;
  11497. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11498. //cleanup
  11499. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11500. break;
  11501. }
  11502. };
  11503. this._collisionsCallbackArray = [];
  11504. this._init = false;
  11505. this._runningUpdated = 0;
  11506. this._runningCollisionTask = false;
  11507. this._addUpdateMeshesList = {};
  11508. this._addUpdateGeometriesList = {};
  11509. this._toRemoveGeometryArray = [];
  11510. this._toRemoveMeshesArray = [];
  11511. }
  11512. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11513. if (!this._init)
  11514. return;
  11515. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11516. return;
  11517. position.divideToRef(collider.radius, this._scaledPosition);
  11518. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11519. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11520. var payload = {
  11521. collider: {
  11522. position: this._scaledPosition.asArray(),
  11523. velocity: this._scaledVelocity.asArray(),
  11524. radius: collider.radius.asArray()
  11525. },
  11526. collisionId: collisionIndex,
  11527. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11528. maximumRetry: maximumRetry
  11529. };
  11530. var message = {
  11531. payload: payload,
  11532. taskType: WorkerTaskType.COLLIDE
  11533. };
  11534. this._worker.postMessage(message);
  11535. };
  11536. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11537. this._scene = scene;
  11538. this._scene.registerAfterRender(this._afterRender);
  11539. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11540. this._worker = new Worker(workerUrl);
  11541. this._worker.onmessage = this._onMessageFromWorker;
  11542. var message = {
  11543. payload: {},
  11544. taskType: WorkerTaskType.INIT
  11545. };
  11546. this._worker.postMessage(message);
  11547. };
  11548. CollisionCoordinatorWorker.prototype.destroy = function () {
  11549. this._scene.unregisterAfterRender(this._afterRender);
  11550. this._worker.terminate();
  11551. };
  11552. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11553. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11554. this.onMeshUpdated(mesh);
  11555. };
  11556. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11557. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11558. };
  11559. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11560. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11561. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11562. this.onGeometryUpdated(geometry);
  11563. };
  11564. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11565. this._toRemoveGeometryArray.push(geometry.id);
  11566. };
  11567. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11568. var submeshes = [];
  11569. if (mesh.subMeshes) {
  11570. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11571. return {
  11572. position: idx,
  11573. verticesStart: sm.verticesStart,
  11574. verticesCount: sm.verticesCount,
  11575. indexStart: sm.indexStart,
  11576. indexCount: sm.indexCount,
  11577. hasMaterial: !!sm.getMaterial(),
  11578. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11579. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11580. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11581. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11582. };
  11583. });
  11584. }
  11585. var geometryId = null;
  11586. if (mesh instanceof BABYLON.Mesh) {
  11587. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11588. }
  11589. else if (mesh instanceof BABYLON.InstancedMesh) {
  11590. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11591. }
  11592. return {
  11593. uniqueId: mesh.uniqueId,
  11594. id: mesh.id,
  11595. name: mesh.name,
  11596. geometryId: geometryId,
  11597. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11598. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11599. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11600. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11601. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11602. subMeshes: submeshes,
  11603. checkCollisions: mesh.checkCollisions
  11604. };
  11605. };
  11606. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11607. return {
  11608. id: geometry.id,
  11609. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11610. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11611. indices: new Int32Array(geometry.getIndices() || []),
  11612. };
  11613. };
  11614. return CollisionCoordinatorWorker;
  11615. })();
  11616. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11617. var CollisionCoordinatorLegacy = (function () {
  11618. function CollisionCoordinatorLegacy() {
  11619. this._scaledPosition = BABYLON.Vector3.Zero();
  11620. this._scaledVelocity = BABYLON.Vector3.Zero();
  11621. this._finalPosition = BABYLON.Vector3.Zero();
  11622. }
  11623. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11624. position.divideToRef(collider.radius, this._scaledPosition);
  11625. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11626. collider.collidedMesh = null;
  11627. collider.retry = 0;
  11628. collider.initialVelocity = this._scaledVelocity;
  11629. collider.initialPosition = this._scaledPosition;
  11630. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11631. this._finalPosition.multiplyInPlace(collider.radius);
  11632. //run the callback
  11633. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11634. };
  11635. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11636. this._scene = scene;
  11637. };
  11638. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11639. //Legacy need no destruction method.
  11640. };
  11641. //No update in legacy mode
  11642. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11643. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11644. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11645. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11646. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11647. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11648. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11649. if (excludedMesh === void 0) { excludedMesh = null; }
  11650. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11651. if (collider.retry >= maximumRetry) {
  11652. finalPosition.copyFrom(position);
  11653. return;
  11654. }
  11655. collider._initialize(position, velocity, closeDistance);
  11656. // Check all meshes
  11657. for (var index = 0; index < this._scene.meshes.length; index++) {
  11658. var mesh = this._scene.meshes[index];
  11659. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11660. mesh._checkCollision(collider);
  11661. }
  11662. }
  11663. if (!collider.collisionFound) {
  11664. position.addToRef(velocity, finalPosition);
  11665. return;
  11666. }
  11667. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11668. collider._getResponse(position, velocity);
  11669. }
  11670. if (velocity.length() <= closeDistance) {
  11671. finalPosition.copyFrom(position);
  11672. return;
  11673. }
  11674. collider.retry++;
  11675. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11676. };
  11677. return CollisionCoordinatorLegacy;
  11678. })();
  11679. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11680. })(BABYLON || (BABYLON = {}));
  11681. var BABYLON;
  11682. (function (BABYLON) {
  11683. var Camera = (function (_super) {
  11684. __extends(Camera, _super);
  11685. function Camera(name, position, scene) {
  11686. _super.call(this, name, scene);
  11687. this.upVector = BABYLON.Vector3.Up();
  11688. this.orthoLeft = null;
  11689. this.orthoRight = null;
  11690. this.orthoBottom = null;
  11691. this.orthoTop = null;
  11692. this.fov = 0.8;
  11693. this.minZ = 1.0;
  11694. this.maxZ = 10000.0;
  11695. this.inertia = 0.9;
  11696. this.mode = Camera.PERSPECTIVE_CAMERA;
  11697. this.isIntermediate = false;
  11698. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11699. this.layerMask = 0x0FFFFFFF;
  11700. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11701. // Camera rig members
  11702. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11703. this._rigCameras = new Array();
  11704. // Cache
  11705. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11706. this._projectionMatrix = new BABYLON.Matrix();
  11707. this._postProcesses = new Array();
  11708. this._transformMatrix = BABYLON.Matrix.Zero();
  11709. this._activeMeshes = new BABYLON.SmartArray(256);
  11710. this._globalPosition = BABYLON.Vector3.Zero();
  11711. this._refreshFrustumPlanes = true;
  11712. scene.addCamera(this);
  11713. if (!scene.activeCamera) {
  11714. scene.activeCamera = this;
  11715. }
  11716. this.position = position;
  11717. }
  11718. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11719. get: function () {
  11720. return Camera._PERSPECTIVE_CAMERA;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11726. get: function () {
  11727. return Camera._ORTHOGRAPHIC_CAMERA;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11733. get: function () {
  11734. return Camera._FOVMODE_VERTICAL_FIXED;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11740. get: function () {
  11741. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11747. get: function () {
  11748. return Camera._RIG_MODE_NONE;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11754. get: function () {
  11755. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11761. get: function () {
  11762. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11768. get: function () {
  11769. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11775. get: function () {
  11776. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11782. get: function () {
  11783. return Camera._RIG_MODE_VR;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. /**
  11789. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11790. */
  11791. Camera.prototype.toString = function (fullDetails) {
  11792. var ret = "Name: " + this.name;
  11793. ret += ", type: " + this.getTypeName();
  11794. if (this.animations) {
  11795. for (var i = 0; i < this.animations.length; i++) {
  11796. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11797. }
  11798. }
  11799. if (fullDetails) {
  11800. }
  11801. return ret;
  11802. };
  11803. Object.defineProperty(Camera.prototype, "globalPosition", {
  11804. get: function () {
  11805. return this._globalPosition;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Camera.prototype.getActiveMeshes = function () {
  11811. return this._activeMeshes;
  11812. };
  11813. Camera.prototype.isActiveMesh = function (mesh) {
  11814. return (this._activeMeshes.indexOf(mesh) !== -1);
  11815. };
  11816. //Cache
  11817. Camera.prototype._initCache = function () {
  11818. _super.prototype._initCache.call(this);
  11819. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11820. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11821. this._cache.mode = undefined;
  11822. this._cache.minZ = undefined;
  11823. this._cache.maxZ = undefined;
  11824. this._cache.fov = undefined;
  11825. this._cache.aspectRatio = undefined;
  11826. this._cache.orthoLeft = undefined;
  11827. this._cache.orthoRight = undefined;
  11828. this._cache.orthoBottom = undefined;
  11829. this._cache.orthoTop = undefined;
  11830. this._cache.renderWidth = undefined;
  11831. this._cache.renderHeight = undefined;
  11832. };
  11833. Camera.prototype._updateCache = function (ignoreParentClass) {
  11834. if (!ignoreParentClass) {
  11835. _super.prototype._updateCache.call(this);
  11836. }
  11837. var engine = this.getEngine();
  11838. this._cache.position.copyFrom(this.position);
  11839. this._cache.upVector.copyFrom(this.upVector);
  11840. this._cache.mode = this.mode;
  11841. this._cache.minZ = this.minZ;
  11842. this._cache.maxZ = this.maxZ;
  11843. this._cache.fov = this.fov;
  11844. this._cache.aspectRatio = engine.getAspectRatio(this);
  11845. this._cache.orthoLeft = this.orthoLeft;
  11846. this._cache.orthoRight = this.orthoRight;
  11847. this._cache.orthoBottom = this.orthoBottom;
  11848. this._cache.orthoTop = this.orthoTop;
  11849. this._cache.renderWidth = engine.getRenderWidth();
  11850. this._cache.renderHeight = engine.getRenderHeight();
  11851. };
  11852. Camera.prototype._updateFromScene = function () {
  11853. this.updateCache();
  11854. this._update();
  11855. };
  11856. // Synchronized
  11857. Camera.prototype._isSynchronized = function () {
  11858. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11859. };
  11860. Camera.prototype._isSynchronizedViewMatrix = function () {
  11861. if (!_super.prototype._isSynchronized.call(this))
  11862. return false;
  11863. return this._cache.position.equals(this.position)
  11864. && this._cache.upVector.equals(this.upVector)
  11865. && this.isSynchronizedWithParent();
  11866. };
  11867. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11868. var check = this._cache.mode === this.mode
  11869. && this._cache.minZ === this.minZ
  11870. && this._cache.maxZ === this.maxZ;
  11871. if (!check) {
  11872. return false;
  11873. }
  11874. var engine = this.getEngine();
  11875. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11876. check = this._cache.fov === this.fov
  11877. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11878. }
  11879. else {
  11880. check = this._cache.orthoLeft === this.orthoLeft
  11881. && this._cache.orthoRight === this.orthoRight
  11882. && this._cache.orthoBottom === this.orthoBottom
  11883. && this._cache.orthoTop === this.orthoTop
  11884. && this._cache.renderWidth === engine.getRenderWidth()
  11885. && this._cache.renderHeight === engine.getRenderHeight();
  11886. }
  11887. return check;
  11888. };
  11889. // Controls
  11890. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11891. };
  11892. Camera.prototype.detachControl = function (element) {
  11893. };
  11894. Camera.prototype._update = function () {
  11895. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11896. this._updateRigCameras();
  11897. }
  11898. this._checkInputs();
  11899. };
  11900. Camera.prototype._checkInputs = function () {
  11901. };
  11902. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11903. // invalidate framebuffer
  11904. if (this._postProcesses.length > 0) {
  11905. this._postProcesses[0].markTextureDirty();
  11906. }
  11907. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11908. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11909. var cam = this._rigCameras[i];
  11910. var rigPostProcess = cam._rigPostProcess;
  11911. // for VR rig, there does not have to be a post process
  11912. if (rigPostProcess) {
  11913. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11914. if (isPass) {
  11915. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11916. cam.isIntermediate = this._postProcesses.length === 0;
  11917. }
  11918. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11919. rigPostProcess.markTextureDirty();
  11920. }
  11921. else {
  11922. cam._postProcesses = this._postProcesses.slice(0);
  11923. }
  11924. }
  11925. };
  11926. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11927. if (insertAt === void 0) { insertAt = null; }
  11928. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11929. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11930. return 0;
  11931. }
  11932. if (insertAt == null || insertAt < 0) {
  11933. this._postProcesses.push(postProcess);
  11934. }
  11935. else {
  11936. this._postProcesses.splice(insertAt, 0, postProcess);
  11937. }
  11938. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11939. return this._postProcesses.indexOf(postProcess);
  11940. };
  11941. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11942. if (atIndices === void 0) { atIndices = null; }
  11943. var result = [];
  11944. var i;
  11945. var index;
  11946. if (!atIndices) {
  11947. var idx = this._postProcesses.indexOf(postProcess);
  11948. if (idx !== -1) {
  11949. this._postProcesses.splice(idx, 1);
  11950. }
  11951. }
  11952. else {
  11953. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11954. // iterate descending, so can just splice as we go
  11955. for (i = atIndices.length - 1; i >= 0; i--) {
  11956. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11957. result.push(i);
  11958. continue;
  11959. }
  11960. this._postProcesses.splice(index, 1);
  11961. }
  11962. }
  11963. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11964. return result;
  11965. };
  11966. Camera.prototype.getWorldMatrix = function () {
  11967. if (!this._worldMatrix) {
  11968. this._worldMatrix = BABYLON.Matrix.Identity();
  11969. }
  11970. var viewMatrix = this.getViewMatrix();
  11971. viewMatrix.invertToRef(this._worldMatrix);
  11972. return this._worldMatrix;
  11973. };
  11974. Camera.prototype._getViewMatrix = function () {
  11975. return BABYLON.Matrix.Identity();
  11976. };
  11977. Camera.prototype.getViewMatrix = function (force) {
  11978. this._computedViewMatrix = this._computeViewMatrix(force);
  11979. if (!force && this._isSynchronizedViewMatrix()) {
  11980. return this._computedViewMatrix;
  11981. }
  11982. this._refreshFrustumPlanes = true;
  11983. if (!this.parent || !this.parent.getWorldMatrix) {
  11984. this._globalPosition.copyFrom(this.position);
  11985. }
  11986. else {
  11987. if (!this._worldMatrix) {
  11988. this._worldMatrix = BABYLON.Matrix.Identity();
  11989. }
  11990. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11991. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11992. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11993. this._computedViewMatrix.invert();
  11994. this._markSyncedWithParent();
  11995. }
  11996. this._currentRenderId = this.getScene().getRenderId();
  11997. return this._computedViewMatrix;
  11998. };
  11999. Camera.prototype._computeViewMatrix = function (force) {
  12000. if (!force && this._isSynchronizedViewMatrix()) {
  12001. return this._computedViewMatrix;
  12002. }
  12003. this._computedViewMatrix = this._getViewMatrix();
  12004. this._currentRenderId = this.getScene().getRenderId();
  12005. return this._computedViewMatrix;
  12006. };
  12007. Camera.prototype.getProjectionMatrix = function (force) {
  12008. if (!force && this._isSynchronizedProjectionMatrix()) {
  12009. return this._projectionMatrix;
  12010. }
  12011. this._refreshFrustumPlanes = true;
  12012. var engine = this.getEngine();
  12013. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12014. if (this.minZ <= 0) {
  12015. this.minZ = 0.1;
  12016. }
  12017. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12018. return this._projectionMatrix;
  12019. }
  12020. var halfWidth = engine.getRenderWidth() / 2.0;
  12021. var halfHeight = engine.getRenderHeight() / 2.0;
  12022. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12023. return this._projectionMatrix;
  12024. };
  12025. Camera.prototype.getTranformationMatrix = function () {
  12026. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12027. return this._transformMatrix;
  12028. };
  12029. Camera.prototype.updateFrustumPlanes = function () {
  12030. if (!this._refreshFrustumPlanes) {
  12031. return;
  12032. }
  12033. this.getTranformationMatrix();
  12034. if (!this._frustumPlanes) {
  12035. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12036. }
  12037. else {
  12038. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12039. }
  12040. this._refreshFrustumPlanes = false;
  12041. };
  12042. Camera.prototype.isInFrustum = function (target) {
  12043. this.updateFrustumPlanes();
  12044. return target.isInFrustum(this._frustumPlanes);
  12045. };
  12046. Camera.prototype.isCompletelyInFrustum = function (target) {
  12047. this.updateFrustumPlanes();
  12048. return target.isCompletelyInFrustum(this._frustumPlanes);
  12049. };
  12050. Camera.prototype.dispose = function () {
  12051. // Animations
  12052. this.getScene().stopAnimation(this);
  12053. // Remove from scene
  12054. this.getScene().removeCamera(this);
  12055. while (this._rigCameras.length > 0) {
  12056. this._rigCameras.pop().dispose();
  12057. }
  12058. // Postprocesses
  12059. for (var i = 0; i < this._postProcesses.length; ++i) {
  12060. this._postProcesses[i].dispose(this);
  12061. }
  12062. _super.prototype.dispose.call(this);
  12063. };
  12064. // ---- Camera rigs section ----
  12065. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12066. while (this._rigCameras.length > 0) {
  12067. this._rigCameras.pop().dispose();
  12068. }
  12069. this.cameraRigMode = mode;
  12070. this._cameraRigParams = {};
  12071. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12072. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12073. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12074. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12075. // create the rig cameras, unless none
  12076. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12077. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12078. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12079. }
  12080. switch (this.cameraRigMode) {
  12081. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12082. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12083. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12084. break;
  12085. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12086. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12087. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12088. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12089. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12090. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12091. break;
  12092. case Camera.RIG_MODE_VR:
  12093. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12094. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12095. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12096. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12097. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12098. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12099. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12100. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12101. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12102. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12103. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12104. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12105. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12106. if (metrics.compensateDistortion) {
  12107. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12108. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12109. }
  12110. break;
  12111. }
  12112. this._cascadePostProcessesToRigCams();
  12113. this._update();
  12114. };
  12115. Camera.prototype._getVRProjectionMatrix = function () {
  12116. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12117. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12118. return this._projectionMatrix;
  12119. };
  12120. Camera.prototype.setCameraRigParameter = function (name, value) {
  12121. if (!this._cameraRigParams) {
  12122. this._cameraRigParams = {};
  12123. }
  12124. this._cameraRigParams[name] = value;
  12125. //provisionnally:
  12126. if (name === "interaxialDistance") {
  12127. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12128. }
  12129. };
  12130. /**
  12131. * needs to be overridden by children so sub has required properties to be copied
  12132. */
  12133. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12134. return null;
  12135. };
  12136. /**
  12137. * May need to be overridden by children
  12138. */
  12139. Camera.prototype._updateRigCameras = function () {
  12140. for (var i = 0; i < this._rigCameras.length; i++) {
  12141. this._rigCameras[i].minZ = this.minZ;
  12142. this._rigCameras[i].maxZ = this.maxZ;
  12143. this._rigCameras[i].fov = this.fov;
  12144. }
  12145. // only update viewport when ANAGLYPH
  12146. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12147. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12148. }
  12149. };
  12150. Camera.prototype._setupInputs = function () {
  12151. };
  12152. Camera.prototype.serialize = function () {
  12153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12154. // Type
  12155. serializationObject.type = this.getTypeName();
  12156. // Parent
  12157. if (this.parent) {
  12158. serializationObject.parentId = this.parent.id;
  12159. }
  12160. if (this.inputs) {
  12161. this.inputs.serialize(serializationObject);
  12162. }
  12163. // Animations
  12164. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12165. serializationObject.ranges = this.serializeAnimationRanges();
  12166. return serializationObject;
  12167. };
  12168. Camera.prototype.getTypeName = function () {
  12169. return "Camera";
  12170. };
  12171. Camera.prototype.clone = function (name) {
  12172. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12173. };
  12174. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12175. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12176. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12177. switch (type) {
  12178. case "ArcRotateCamera":
  12179. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12180. case "DeviceOrientationCamera":
  12181. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12182. case "FollowCamera":
  12183. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12184. case "ArcFollowCamera":
  12185. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12186. case "GamepadCamera":
  12187. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12188. case "TouchCamera":
  12189. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12190. case "VirtualJoysticksCamera":
  12191. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12192. case "WebVRFreeCamera":
  12193. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12194. case "VRDeviceOrientationFreeCamera":
  12195. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12196. case "AnaglyphArcRotateCamera":
  12197. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12198. case "AnaglyphFreeCamera":
  12199. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12200. case "AnaglyphGamepadCamera":
  12201. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12202. case "AnaglyphUniversalCamera":
  12203. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12204. case "StereoscopicArcRotateCamera":
  12205. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12206. case "StereoscopicFreeCamera":
  12207. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12208. case "StereoscopicGamepadCamera":
  12209. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12210. case "StereoscopicUniversalCamera":
  12211. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12212. case "FreeCamera":
  12213. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12214. default:
  12215. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12216. }
  12217. };
  12218. Camera.Parse = function (parsedCamera, scene) {
  12219. var type = parsedCamera.type;
  12220. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12221. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12222. // Parent
  12223. if (parsedCamera.parentId) {
  12224. camera._waitingParentId = parsedCamera.parentId;
  12225. }
  12226. //If camera has an input manager, let it parse inputs settings
  12227. if (camera.inputs) {
  12228. camera.inputs.parse(parsedCamera);
  12229. camera._setupInputs();
  12230. }
  12231. // Target
  12232. if (parsedCamera.target) {
  12233. if (camera.setTarget) {
  12234. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12235. }
  12236. }
  12237. // Apply 3d rig, when found
  12238. if (parsedCamera.cameraRigMode) {
  12239. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12240. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12241. }
  12242. // Animations
  12243. if (parsedCamera.animations) {
  12244. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12245. var parsedAnimation = parsedCamera.animations[animationIndex];
  12246. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12247. }
  12248. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12249. }
  12250. if (parsedCamera.autoAnimate) {
  12251. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12252. }
  12253. return camera;
  12254. };
  12255. // Statics
  12256. Camera._PERSPECTIVE_CAMERA = 0;
  12257. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12258. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12259. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12260. Camera._RIG_MODE_NONE = 0;
  12261. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12262. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12263. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12264. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12265. Camera._RIG_MODE_VR = 20;
  12266. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12267. __decorate([
  12268. BABYLON.serializeAsVector3()
  12269. ], Camera.prototype, "position", void 0);
  12270. __decorate([
  12271. BABYLON.serializeAsVector3()
  12272. ], Camera.prototype, "upVector", void 0);
  12273. __decorate([
  12274. BABYLON.serialize()
  12275. ], Camera.prototype, "orthoLeft", void 0);
  12276. __decorate([
  12277. BABYLON.serialize()
  12278. ], Camera.prototype, "orthoRight", void 0);
  12279. __decorate([
  12280. BABYLON.serialize()
  12281. ], Camera.prototype, "orthoBottom", void 0);
  12282. __decorate([
  12283. BABYLON.serialize()
  12284. ], Camera.prototype, "orthoTop", void 0);
  12285. __decorate([
  12286. BABYLON.serialize()
  12287. ], Camera.prototype, "fov", void 0);
  12288. __decorate([
  12289. BABYLON.serialize()
  12290. ], Camera.prototype, "minZ", void 0);
  12291. __decorate([
  12292. BABYLON.serialize()
  12293. ], Camera.prototype, "maxZ", void 0);
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], Camera.prototype, "inertia", void 0);
  12297. __decorate([
  12298. BABYLON.serialize()
  12299. ], Camera.prototype, "mode", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], Camera.prototype, "layerMask", void 0);
  12303. __decorate([
  12304. BABYLON.serialize()
  12305. ], Camera.prototype, "fovMode", void 0);
  12306. __decorate([
  12307. BABYLON.serialize()
  12308. ], Camera.prototype, "cameraRigMode", void 0);
  12309. __decorate([
  12310. BABYLON.serialize()
  12311. ], Camera.prototype, "interaxialDistance", void 0);
  12312. __decorate([
  12313. BABYLON.serialize()
  12314. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12315. return Camera;
  12316. })(BABYLON.Node);
  12317. BABYLON.Camera = Camera;
  12318. })(BABYLON || (BABYLON = {}));
  12319. var BABYLON;
  12320. (function (BABYLON) {
  12321. BABYLON.CameraInputTypes = {};
  12322. var CameraInputsManager = (function () {
  12323. function CameraInputsManager(camera) {
  12324. this.attached = {};
  12325. this.camera = camera;
  12326. this.checkInputs = function () { };
  12327. }
  12328. CameraInputsManager.prototype.add = function (input) {
  12329. var type = input.getSimpleName();
  12330. if (this.attached[type]) {
  12331. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12332. return;
  12333. }
  12334. this.attached[type] = input;
  12335. input.camera = this.camera;
  12336. //for checkInputs, we are dynamically creating a function
  12337. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12338. if (input.checkInputs) {
  12339. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12340. }
  12341. if (this.attachedElement) {
  12342. input.attachControl(this.attachedElement);
  12343. }
  12344. };
  12345. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12346. for (var cam in this.attached) {
  12347. var input = this.attached[cam];
  12348. if (input === inputToRemove) {
  12349. input.detachControl(this.attachedElement);
  12350. delete this.attached[cam];
  12351. this.rebuildInputCheck();
  12352. }
  12353. }
  12354. };
  12355. CameraInputsManager.prototype.removeByType = function (inputType) {
  12356. for (var cam in this.attached) {
  12357. var input = this.attached[cam];
  12358. if (input.getTypeName() === inputType) {
  12359. input.detachControl(this.attachedElement);
  12360. delete this.attached[cam];
  12361. this.rebuildInputCheck();
  12362. }
  12363. }
  12364. };
  12365. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12366. var current = this.checkInputs;
  12367. return function () {
  12368. current();
  12369. fn();
  12370. };
  12371. };
  12372. CameraInputsManager.prototype.attachInput = function (input) {
  12373. input.attachControl(this.attachedElement, this.noPreventDefault);
  12374. };
  12375. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12376. if (this.attachedElement) {
  12377. return;
  12378. }
  12379. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12380. this.attachedElement = element;
  12381. this.noPreventDefault = noPreventDefault;
  12382. for (var cam in this.attached) {
  12383. var input = this.attached[cam];
  12384. this.attached[cam].attachControl(element, noPreventDefault);
  12385. }
  12386. };
  12387. CameraInputsManager.prototype.detachElement = function (element) {
  12388. if (this.attachedElement !== element) {
  12389. return;
  12390. }
  12391. for (var cam in this.attached) {
  12392. var input = this.attached[cam];
  12393. this.attached[cam].detachControl(element);
  12394. }
  12395. this.attachedElement = null;
  12396. };
  12397. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12398. this.checkInputs = function () { };
  12399. for (var cam in this.attached) {
  12400. var input = this.attached[cam];
  12401. if (input.checkInputs) {
  12402. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12403. }
  12404. }
  12405. };
  12406. CameraInputsManager.prototype.clear = function () {
  12407. if (this.attachedElement) {
  12408. this.detachElement(this.attachedElement);
  12409. }
  12410. this.attached = {};
  12411. this.attachedElement = null;
  12412. this.checkInputs = function () { };
  12413. };
  12414. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12415. var inputs = {};
  12416. for (var cam in this.attached) {
  12417. var input = this.attached[cam];
  12418. var res = BABYLON.SerializationHelper.Serialize(input);
  12419. inputs[input.getTypeName()] = res;
  12420. }
  12421. serializedCamera.inputsmgr = inputs;
  12422. };
  12423. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12424. var parsedInputs = parsedCamera.inputsmgr;
  12425. if (parsedInputs) {
  12426. this.clear();
  12427. for (var n in parsedInputs) {
  12428. var construct = BABYLON.CameraInputTypes[n];
  12429. if (construct) {
  12430. var parsedinput = parsedInputs[n];
  12431. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12432. this.add(input);
  12433. }
  12434. }
  12435. }
  12436. else {
  12437. //2016-03-08 this part is for managing backward compatibility
  12438. for (var n in this.attached) {
  12439. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12440. if (construct) {
  12441. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12442. this.remove(this.attached[n]);
  12443. this.add(input);
  12444. }
  12445. }
  12446. }
  12447. };
  12448. return CameraInputsManager;
  12449. })();
  12450. BABYLON.CameraInputsManager = CameraInputsManager;
  12451. })(BABYLON || (BABYLON = {}));
  12452. var BABYLON;
  12453. (function (BABYLON) {
  12454. var FreeCameraMouseInput = (function () {
  12455. function FreeCameraMouseInput(touchEnabled) {
  12456. if (touchEnabled === void 0) { touchEnabled = true; }
  12457. this.touchEnabled = touchEnabled;
  12458. this.angularSensibility = 2000.0;
  12459. }
  12460. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12461. var _this = this;
  12462. if (!this._pointerInput) {
  12463. var camera = this.camera;
  12464. var engine = this.camera.getEngine();
  12465. this._pointerInput = function (p, s) {
  12466. var evt = p.event;
  12467. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12468. return;
  12469. }
  12470. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12471. try {
  12472. evt.srcElement.setPointerCapture(evt.pointerId);
  12473. }
  12474. catch (e) {
  12475. }
  12476. _this.previousPosition = {
  12477. x: evt.clientX,
  12478. y: evt.clientY
  12479. };
  12480. if (!noPreventDefault) {
  12481. evt.preventDefault();
  12482. element.focus();
  12483. }
  12484. }
  12485. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12486. try {
  12487. evt.srcElement.releasePointerCapture(evt.pointerId);
  12488. }
  12489. catch (e) {
  12490. }
  12491. _this.previousPosition = null;
  12492. if (!noPreventDefault) {
  12493. evt.preventDefault();
  12494. }
  12495. }
  12496. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12497. if (!_this.previousPosition && !engine.isPointerLock) {
  12498. return;
  12499. }
  12500. var offsetX;
  12501. var offsetY;
  12502. if (!engine.isPointerLock) {
  12503. offsetX = evt.clientX - _this.previousPosition.x;
  12504. offsetY = evt.clientY - _this.previousPosition.y;
  12505. }
  12506. else {
  12507. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12508. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12509. }
  12510. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12511. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12512. _this.previousPosition = {
  12513. x: evt.clientX,
  12514. y: evt.clientY
  12515. };
  12516. if (!noPreventDefault) {
  12517. evt.preventDefault();
  12518. }
  12519. }
  12520. };
  12521. }
  12522. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12523. };
  12524. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12525. if (this._observer && element) {
  12526. this.camera.getScene().onPointerObservable.remove(this._observer);
  12527. this._observer = null;
  12528. this.previousPosition = null;
  12529. }
  12530. };
  12531. FreeCameraMouseInput.prototype.getTypeName = function () {
  12532. return "FreeCameraMouseInput";
  12533. };
  12534. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12535. return "mouse";
  12536. };
  12537. __decorate([
  12538. BABYLON.serialize()
  12539. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12540. return FreeCameraMouseInput;
  12541. })();
  12542. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12543. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12544. })(BABYLON || (BABYLON = {}));
  12545. var BABYLON;
  12546. (function (BABYLON) {
  12547. var FreeCameraKeyboardMoveInput = (function () {
  12548. function FreeCameraKeyboardMoveInput() {
  12549. this._keys = [];
  12550. this.keysUp = [38];
  12551. this.keysDown = [40];
  12552. this.keysLeft = [37];
  12553. this.keysRight = [39];
  12554. }
  12555. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12556. var _this = this;
  12557. if (!this._onKeyDown) {
  12558. element.tabIndex = 1;
  12559. this._onKeyDown = function (evt) {
  12560. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12561. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12562. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12563. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12564. var index = _this._keys.indexOf(evt.keyCode);
  12565. if (index === -1) {
  12566. _this._keys.push(evt.keyCode);
  12567. }
  12568. if (!noPreventDefault) {
  12569. evt.preventDefault();
  12570. }
  12571. }
  12572. };
  12573. this._onKeyUp = function (evt) {
  12574. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12575. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12576. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12577. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12578. var index = _this._keys.indexOf(evt.keyCode);
  12579. if (index >= 0) {
  12580. _this._keys.splice(index, 1);
  12581. }
  12582. if (!noPreventDefault) {
  12583. evt.preventDefault();
  12584. }
  12585. }
  12586. };
  12587. element.addEventListener("keydown", this._onKeyDown, false);
  12588. element.addEventListener("keyup", this._onKeyUp, false);
  12589. BABYLON.Tools.RegisterTopRootEvents([
  12590. { name: "blur", handler: this._onLostFocus }
  12591. ]);
  12592. }
  12593. };
  12594. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12595. if (this._onKeyDown) {
  12596. element.removeEventListener("keydown", this._onKeyDown);
  12597. element.removeEventListener("keyup", this._onKeyUp);
  12598. BABYLON.Tools.UnregisterTopRootEvents([
  12599. { name: "blur", handler: this._onLostFocus }
  12600. ]);
  12601. this._keys = [];
  12602. this._onKeyDown = null;
  12603. this._onKeyUp = null;
  12604. }
  12605. };
  12606. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12607. if (this._onKeyDown) {
  12608. var camera = this.camera;
  12609. // Keyboard
  12610. for (var index = 0; index < this._keys.length; index++) {
  12611. var keyCode = this._keys[index];
  12612. var speed = camera._computeLocalCameraSpeed();
  12613. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12614. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12615. }
  12616. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12617. camera._localDirection.copyFromFloats(0, 0, speed);
  12618. }
  12619. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12620. camera._localDirection.copyFromFloats(speed, 0, 0);
  12621. }
  12622. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12623. camera._localDirection.copyFromFloats(0, 0, -speed);
  12624. }
  12625. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12626. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12627. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12628. }
  12629. }
  12630. };
  12631. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12632. return "FreeCameraKeyboardMoveInput";
  12633. };
  12634. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12635. this._keys = [];
  12636. };
  12637. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12638. return "keyboard";
  12639. };
  12640. __decorate([
  12641. BABYLON.serialize()
  12642. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12643. __decorate([
  12644. BABYLON.serialize()
  12645. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12646. __decorate([
  12647. BABYLON.serialize()
  12648. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12649. __decorate([
  12650. BABYLON.serialize()
  12651. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12652. return FreeCameraKeyboardMoveInput;
  12653. })();
  12654. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12655. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12656. })(BABYLON || (BABYLON = {}));
  12657. var BABYLON;
  12658. (function (BABYLON) {
  12659. var FreeCameraTouchInput = (function () {
  12660. function FreeCameraTouchInput() {
  12661. this._offsetX = null;
  12662. this._offsetY = null;
  12663. this._pointerCount = 0;
  12664. this._pointerPressed = [];
  12665. this.touchAngularSensibility = 200000.0;
  12666. this.touchMoveSensibility = 250.0;
  12667. }
  12668. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12669. var _this = this;
  12670. var previousPosition;
  12671. if (this._pointerInput === undefined) {
  12672. this._onLostFocus = function (evt) {
  12673. _this._offsetX = null;
  12674. _this._offsetY = null;
  12675. };
  12676. this._pointerInput = function (p, s) {
  12677. var evt = p.event;
  12678. if (evt.pointerType === "mouse") {
  12679. return;
  12680. }
  12681. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12682. if (!noPreventDefault) {
  12683. evt.preventDefault();
  12684. }
  12685. _this._pointerPressed.push(evt.pointerId);
  12686. if (_this._pointerPressed.length !== 1) {
  12687. return;
  12688. }
  12689. previousPosition = {
  12690. x: evt.clientX,
  12691. y: evt.clientY
  12692. };
  12693. }
  12694. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12695. if (!noPreventDefault) {
  12696. evt.preventDefault();
  12697. }
  12698. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12699. if (index === -1) {
  12700. return;
  12701. }
  12702. _this._pointerPressed.splice(index, 1);
  12703. if (index != 0) {
  12704. return;
  12705. }
  12706. previousPosition = null;
  12707. _this._offsetX = null;
  12708. _this._offsetY = null;
  12709. }
  12710. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12711. if (!noPreventDefault) {
  12712. evt.preventDefault();
  12713. }
  12714. if (!previousPosition) {
  12715. return;
  12716. }
  12717. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12718. if (index != 0) {
  12719. return;
  12720. }
  12721. _this._offsetX = evt.clientX - previousPosition.x;
  12722. _this._offsetY = -(evt.clientY - previousPosition.y);
  12723. }
  12724. };
  12725. }
  12726. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12727. element.addEventListener("blur", this._onLostFocus);
  12728. };
  12729. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12730. if (this._pointerInput && element) {
  12731. this.camera.getScene().onPointerObservable.remove(this._observer);
  12732. this._observer = null;
  12733. element.removeEventListener("blur", this._onLostFocus);
  12734. this._onLostFocus = null;
  12735. this._pointerPressed = [];
  12736. this._offsetX = null;
  12737. this._offsetY = null;
  12738. this._pointerCount = 0;
  12739. }
  12740. };
  12741. FreeCameraTouchInput.prototype.checkInputs = function () {
  12742. if (this._offsetX) {
  12743. var camera = this.camera;
  12744. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12745. if (this._pointerPressed.length > 1) {
  12746. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12747. }
  12748. else {
  12749. var speed = camera._computeLocalCameraSpeed();
  12750. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12751. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12752. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12753. }
  12754. }
  12755. };
  12756. FreeCameraTouchInput.prototype.getTypeName = function () {
  12757. return "FreeCameraTouchInput";
  12758. };
  12759. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12760. return "touch";
  12761. };
  12762. __decorate([
  12763. BABYLON.serialize()
  12764. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12765. __decorate([
  12766. BABYLON.serialize()
  12767. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12768. return FreeCameraTouchInput;
  12769. })();
  12770. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12771. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12772. })(BABYLON || (BABYLON = {}));
  12773. var BABYLON;
  12774. (function (BABYLON) {
  12775. var FreeCameraDeviceOrientationInput = (function () {
  12776. function FreeCameraDeviceOrientationInput() {
  12777. var _this = this;
  12778. this._screenOrientationAngle = 0;
  12779. this._screenQuaternion = new BABYLON.Quaternion();
  12780. this._alpha = 0;
  12781. this._beta = 0;
  12782. this._gamma = 0;
  12783. this._orientationChanged = function () {
  12784. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12785. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12786. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12787. };
  12788. this._deviceOrientation = function (evt) {
  12789. _this._alpha = evt.alpha;
  12790. _this._beta = evt.beta;
  12791. _this._gamma = evt.gamma;
  12792. };
  12793. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12794. this._orientationChanged();
  12795. }
  12796. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12797. get: function () {
  12798. return this._camera;
  12799. },
  12800. set: function (camera) {
  12801. this._camera = camera;
  12802. if (!this._camera.rotationQuaternion)
  12803. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12809. window.addEventListener("orientationchange", this._orientationChanged);
  12810. window.addEventListener("deviceorientation", this._deviceOrientation);
  12811. };
  12812. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12813. window.removeEventListener("orientationchange", this._orientationChanged);
  12814. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12815. };
  12816. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12817. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12818. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12819. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12820. //Mirror on XY Plane
  12821. this._camera.rotationQuaternion.z *= -1;
  12822. this._camera.rotationQuaternion.w *= -1;
  12823. };
  12824. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12825. return "FreeCameraDeviceOrientationInput";
  12826. };
  12827. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12828. return "deviceOrientation";
  12829. };
  12830. return FreeCameraDeviceOrientationInput;
  12831. })();
  12832. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12833. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12834. })(BABYLON || (BABYLON = {}));
  12835. var BABYLON;
  12836. (function (BABYLON) {
  12837. var FreeCameraVRDeviceOrientationInput = (function () {
  12838. function FreeCameraVRDeviceOrientationInput() {
  12839. this.alphaCorrection = 1;
  12840. this.betaCorrection = 1;
  12841. this.gammaCorrection = 1;
  12842. this._alpha = 0;
  12843. this._beta = 0;
  12844. this._gamma = 0;
  12845. this._dirty = false;
  12846. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12847. }
  12848. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12849. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12850. };
  12851. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12852. var camera = this.camera;
  12853. this._alpha = evt.alpha;
  12854. this._beta = evt.beta;
  12855. this._gamma = evt.gamma;
  12856. this._dirty = true;
  12857. };
  12858. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12859. if (this._dirty) {
  12860. this._dirty = false;
  12861. var rotationX = this._gamma;
  12862. if (rotationX < 0) {
  12863. rotationX = 90 + rotationX;
  12864. }
  12865. else {
  12866. // Incline it in the correct angle.
  12867. rotationX = 270 - rotationX;
  12868. }
  12869. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12870. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12871. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12872. }
  12873. };
  12874. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12875. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12876. };
  12877. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12878. return "FreeCameraVRDeviceOrientationInput";
  12879. };
  12880. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12881. return "VRDeviceOrientation";
  12882. };
  12883. return FreeCameraVRDeviceOrientationInput;
  12884. })();
  12885. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12886. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12887. })(BABYLON || (BABYLON = {}));
  12888. var BABYLON;
  12889. (function (BABYLON) {
  12890. var FreeCameraGamepadInput = (function () {
  12891. function FreeCameraGamepadInput() {
  12892. this.gamepadAngularSensibility = 200;
  12893. this.gamepadMoveSensibility = 40;
  12894. }
  12895. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12896. var _this = this;
  12897. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12898. };
  12899. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12900. if (this._gamepads) {
  12901. this._gamepads.dispose();
  12902. }
  12903. this.gamepad = null;
  12904. };
  12905. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12906. if (this.gamepad) {
  12907. var camera = this.camera;
  12908. var LSValues = this.gamepad.leftStick;
  12909. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12910. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12911. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12912. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12913. var RSValues = this.gamepad.rightStick;
  12914. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12915. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12916. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12917. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12918. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12919. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12920. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12921. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12922. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12923. }
  12924. };
  12925. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12926. // Only the first gamepad can control the camera
  12927. if (gamepad.index === 0) {
  12928. this.gamepad = gamepad;
  12929. }
  12930. };
  12931. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12932. return "FreeCameraGamepadInput";
  12933. };
  12934. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12935. return "gamepad";
  12936. };
  12937. __decorate([
  12938. BABYLON.serialize()
  12939. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12940. __decorate([
  12941. BABYLON.serialize()
  12942. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12943. return FreeCameraGamepadInput;
  12944. })();
  12945. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12946. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12947. })(BABYLON || (BABYLON = {}));
  12948. var BABYLON;
  12949. (function (BABYLON) {
  12950. var ArcRotateCameraKeyboardMoveInput = (function () {
  12951. function ArcRotateCameraKeyboardMoveInput() {
  12952. this._keys = [];
  12953. this.keysUp = [38];
  12954. this.keysDown = [40];
  12955. this.keysLeft = [37];
  12956. this.keysRight = [39];
  12957. }
  12958. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12959. var _this = this;
  12960. element.tabIndex = 1;
  12961. this._onKeyDown = function (evt) {
  12962. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12963. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12964. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12965. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12966. var index = _this._keys.indexOf(evt.keyCode);
  12967. if (index === -1) {
  12968. _this._keys.push(evt.keyCode);
  12969. }
  12970. if (evt.preventDefault) {
  12971. if (!noPreventDefault) {
  12972. evt.preventDefault();
  12973. }
  12974. }
  12975. }
  12976. };
  12977. this._onKeyUp = function (evt) {
  12978. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12979. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12980. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12981. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12982. var index = _this._keys.indexOf(evt.keyCode);
  12983. if (index >= 0) {
  12984. _this._keys.splice(index, 1);
  12985. }
  12986. if (evt.preventDefault) {
  12987. if (!noPreventDefault) {
  12988. evt.preventDefault();
  12989. }
  12990. }
  12991. }
  12992. };
  12993. this._onLostFocus = function () {
  12994. _this._keys = [];
  12995. };
  12996. element.addEventListener("keydown", this._onKeyDown, false);
  12997. element.addEventListener("keyup", this._onKeyUp, false);
  12998. BABYLON.Tools.RegisterTopRootEvents([
  12999. { name: "blur", handler: this._onLostFocus }
  13000. ]);
  13001. };
  13002. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13003. if (element) {
  13004. element.removeEventListener("keydown", this._onKeyDown);
  13005. element.removeEventListener("keyup", this._onKeyUp);
  13006. }
  13007. BABYLON.Tools.UnregisterTopRootEvents([
  13008. { name: "blur", handler: this._onLostFocus }
  13009. ]);
  13010. this._keys = [];
  13011. this._onKeyDown = null;
  13012. this._onKeyUp = null;
  13013. this._onLostFocus = null;
  13014. };
  13015. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13016. if (this._onKeyDown) {
  13017. var camera = this.camera;
  13018. for (var index = 0; index < this._keys.length; index++) {
  13019. var keyCode = this._keys[index];
  13020. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13021. camera.inertialAlphaOffset -= 0.01;
  13022. }
  13023. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13024. camera.inertialBetaOffset -= 0.01;
  13025. }
  13026. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13027. camera.inertialAlphaOffset += 0.01;
  13028. }
  13029. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13030. camera.inertialBetaOffset += 0.01;
  13031. }
  13032. }
  13033. }
  13034. };
  13035. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13036. return "ArcRotateCameraKeyboardMoveInput";
  13037. };
  13038. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13039. return "keyboard";
  13040. };
  13041. __decorate([
  13042. BABYLON.serialize()
  13043. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13044. __decorate([
  13045. BABYLON.serialize()
  13046. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13047. __decorate([
  13048. BABYLON.serialize()
  13049. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13050. __decorate([
  13051. BABYLON.serialize()
  13052. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13053. return ArcRotateCameraKeyboardMoveInput;
  13054. })();
  13055. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13056. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13057. })(BABYLON || (BABYLON = {}));
  13058. var BABYLON;
  13059. (function (BABYLON) {
  13060. var ArcRotateCameraMouseWheelInput = (function () {
  13061. function ArcRotateCameraMouseWheelInput() {
  13062. this.wheelPrecision = 3.0;
  13063. }
  13064. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13065. var _this = this;
  13066. this._wheel = function (p, s) {
  13067. //sanity check - this should be a PointerWheel event.
  13068. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13069. return;
  13070. var event = p.event;
  13071. var delta = 0;
  13072. if (event.wheelDelta) {
  13073. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13074. }
  13075. else if (event.detail) {
  13076. delta = -event.detail / _this.wheelPrecision;
  13077. }
  13078. if (delta)
  13079. _this.camera.inertialRadiusOffset += delta;
  13080. if (event.preventDefault) {
  13081. if (!noPreventDefault) {
  13082. event.preventDefault();
  13083. }
  13084. }
  13085. };
  13086. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13087. };
  13088. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13089. if (this._observer && element) {
  13090. this.camera.getScene().onPointerObservable.remove(this._observer);
  13091. this._observer = null;
  13092. this._wheel = null;
  13093. }
  13094. };
  13095. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13096. return "ArcRotateCameraMouseWheelInput";
  13097. };
  13098. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13099. return "mousewheel";
  13100. };
  13101. __decorate([
  13102. BABYLON.serialize()
  13103. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13104. return ArcRotateCameraMouseWheelInput;
  13105. })();
  13106. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13107. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13108. })(BABYLON || (BABYLON = {}));
  13109. var BABYLON;
  13110. (function (BABYLON) {
  13111. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13112. var ArcRotateCameraPointersInput = (function () {
  13113. function ArcRotateCameraPointersInput() {
  13114. this.angularSensibilityX = 1000.0;
  13115. this.angularSensibilityY = 1000.0;
  13116. this.pinchPrecision = 6.0;
  13117. this.panningSensibility = 50.0;
  13118. this._isPanClick = false;
  13119. this._isCtrlPushed = false;
  13120. this.pinchInwards = true;
  13121. }
  13122. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13123. var _this = this;
  13124. var engine = this.camera.getEngine();
  13125. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13126. var pointA, pointB;
  13127. var previousPinchDistance = 0;
  13128. this._pointerInput = function (p, s) {
  13129. var evt = p.event;
  13130. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13131. try {
  13132. evt.srcElement.setPointerCapture(evt.pointerId);
  13133. }
  13134. catch (e) {
  13135. }
  13136. // Manage panning with pan button click
  13137. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13138. // manage pointers
  13139. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13140. if (pointA === undefined) {
  13141. pointA = cacheSoloPointer;
  13142. }
  13143. else if (pointB === undefined) {
  13144. pointB = cacheSoloPointer;
  13145. }
  13146. if (!noPreventDefault) {
  13147. evt.preventDefault();
  13148. element.focus();
  13149. }
  13150. }
  13151. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13152. try {
  13153. evt.srcElement.releasePointerCapture(evt.pointerId);
  13154. }
  13155. catch (e) {
  13156. }
  13157. cacheSoloPointer = null;
  13158. previousPinchDistance = 0;
  13159. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13160. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13161. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13162. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13163. pointA = pointB = undefined;
  13164. if (!noPreventDefault) {
  13165. evt.preventDefault();
  13166. }
  13167. }
  13168. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13169. if (!noPreventDefault) {
  13170. evt.preventDefault();
  13171. }
  13172. // One button down
  13173. if (pointA && pointB === undefined) {
  13174. if (_this.panningSensibility !== 0 &&
  13175. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  13176. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13177. _this.camera
  13178. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13179. _this.camera
  13180. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13181. }
  13182. else {
  13183. var offsetX = evt.clientX - cacheSoloPointer.x;
  13184. var offsetY = evt.clientY - cacheSoloPointer.y;
  13185. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13186. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13187. }
  13188. cacheSoloPointer.x = evt.clientX;
  13189. cacheSoloPointer.y = evt.clientY;
  13190. }
  13191. else if (pointA && pointB) {
  13192. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13193. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13194. ed.x = evt.clientX;
  13195. ed.y = evt.clientY;
  13196. var direction = _this.pinchInwards ? 1 : -1;
  13197. var distX = pointA.x - pointB.x;
  13198. var distY = pointA.y - pointB.y;
  13199. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13200. if (previousPinchDistance === 0) {
  13201. previousPinchDistance = pinchSquaredDistance;
  13202. return;
  13203. }
  13204. if (pinchSquaredDistance !== previousPinchDistance) {
  13205. _this.camera
  13206. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13207. (_this.pinchPrecision *
  13208. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13209. direction);
  13210. previousPinchDistance = pinchSquaredDistance;
  13211. }
  13212. }
  13213. }
  13214. };
  13215. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13216. this._onContextMenu = function (evt) {
  13217. evt.preventDefault();
  13218. };
  13219. if (!this.camera._useCtrlForPanning) {
  13220. element.addEventListener("contextmenu", this._onContextMenu, false);
  13221. }
  13222. this._onLostFocus = function () {
  13223. //this._keys = [];
  13224. pointA = pointB = undefined;
  13225. previousPinchDistance = 0;
  13226. cacheSoloPointer = null;
  13227. };
  13228. this._onKeyDown = function (evt) {
  13229. _this._isCtrlPushed = evt.ctrlKey;
  13230. };
  13231. this._onKeyUp = function (evt) {
  13232. _this._isCtrlPushed = evt.ctrlKey;
  13233. };
  13234. this._onMouseMove = function (evt) {
  13235. if (!engine.isPointerLock) {
  13236. return;
  13237. }
  13238. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13239. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13240. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13241. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13242. if (!noPreventDefault) {
  13243. evt.preventDefault();
  13244. }
  13245. };
  13246. this._onGestureStart = function (e) {
  13247. if (window.MSGesture === undefined) {
  13248. return;
  13249. }
  13250. if (!_this._MSGestureHandler) {
  13251. _this._MSGestureHandler = new MSGesture();
  13252. _this._MSGestureHandler.target = element;
  13253. }
  13254. _this._MSGestureHandler.addPointer(e.pointerId);
  13255. };
  13256. this._onGesture = function (e) {
  13257. _this.camera.radius *= e.scale;
  13258. if (e.preventDefault) {
  13259. if (!noPreventDefault) {
  13260. e.stopPropagation();
  13261. e.preventDefault();
  13262. }
  13263. }
  13264. };
  13265. element.addEventListener("mousemove", this._onMouseMove, false);
  13266. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13267. element.addEventListener("MSGestureChange", this._onGesture, false);
  13268. element.addEventListener("keydown", this._onKeyDown, false);
  13269. element.addEventListener("keyup", this._onKeyUp, false);
  13270. BABYLON.Tools.RegisterTopRootEvents([
  13271. { name: "blur", handler: this._onLostFocus }
  13272. ]);
  13273. };
  13274. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13275. if (element && this._observer) {
  13276. this.camera.getScene().onPointerObservable.remove(this._observer);
  13277. this._observer = null;
  13278. element.removeEventListener("contextmenu", this._onContextMenu);
  13279. element.removeEventListener("mousemove", this._onMouseMove);
  13280. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13281. element.removeEventListener("MSGestureChange", this._onGesture);
  13282. element.removeEventListener("keydown", this._onKeyDown);
  13283. element.removeEventListener("keyup", this._onKeyUp);
  13284. this._isPanClick = false;
  13285. this._isCtrlPushed = false;
  13286. this.pinchInwards = true;
  13287. this._onKeyDown = null;
  13288. this._onKeyUp = null;
  13289. this._onMouseMove = null;
  13290. this._onGestureStart = null;
  13291. this._onGesture = null;
  13292. this._MSGestureHandler = null;
  13293. this._onLostFocus = null;
  13294. this._onContextMenu = null;
  13295. }
  13296. BABYLON.Tools.UnregisterTopRootEvents([
  13297. { name: "blur", handler: this._onLostFocus }
  13298. ]);
  13299. };
  13300. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13301. return "ArcRotateCameraPointersInput";
  13302. };
  13303. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13304. return "pointers";
  13305. };
  13306. __decorate([
  13307. BABYLON.serialize()
  13308. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13309. __decorate([
  13310. BABYLON.serialize()
  13311. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13312. __decorate([
  13313. BABYLON.serialize()
  13314. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13315. __decorate([
  13316. BABYLON.serialize()
  13317. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13318. return ArcRotateCameraPointersInput;
  13319. })();
  13320. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13321. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13322. })(BABYLON || (BABYLON = {}));
  13323. var BABYLON;
  13324. (function (BABYLON) {
  13325. var ArcRotateCameraGamepadInput = (function () {
  13326. function ArcRotateCameraGamepadInput() {
  13327. this.gamepadRotationSensibility = 80;
  13328. this.gamepadMoveSensibility = 40;
  13329. }
  13330. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13331. var _this = this;
  13332. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13333. };
  13334. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13335. if (this._gamepads) {
  13336. this._gamepads.dispose();
  13337. }
  13338. this.gamepad = null;
  13339. };
  13340. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13341. if (this.gamepad) {
  13342. var camera = this.camera;
  13343. var RSValues = this.gamepad.rightStick;
  13344. if (RSValues.x != 0) {
  13345. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13346. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13347. camera.inertialAlphaOffset += normalizedRX;
  13348. }
  13349. }
  13350. if (RSValues.y != 0) {
  13351. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13352. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13353. camera.inertialBetaOffset += normalizedRY;
  13354. }
  13355. }
  13356. var LSValues = this.gamepad.leftStick;
  13357. if (LSValues.y != 0) {
  13358. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13359. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13360. this.camera.inertialRadiusOffset -= normalizedLY;
  13361. }
  13362. }
  13363. }
  13364. };
  13365. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13366. // Only the first gamepad can control the camera
  13367. if (gamepad.index === 0) {
  13368. this.gamepad = gamepad;
  13369. }
  13370. };
  13371. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13372. return "ArcRotateCameraGamepadInput";
  13373. };
  13374. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13375. return "gamepad";
  13376. };
  13377. __decorate([
  13378. BABYLON.serialize()
  13379. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13380. __decorate([
  13381. BABYLON.serialize()
  13382. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13383. return ArcRotateCameraGamepadInput;
  13384. })();
  13385. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13386. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13387. })(BABYLON || (BABYLON = {}));
  13388. var BABYLON;
  13389. (function (BABYLON) {
  13390. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13391. function ArcRotateCameraVRDeviceOrientationInput() {
  13392. this.alphaCorrection = 1;
  13393. this.betaCorrection = 1;
  13394. this.gammaCorrection = 1;
  13395. this._alpha = 0;
  13396. this._beta = 0;
  13397. this._gamma = 0;
  13398. this._dirty = false;
  13399. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13400. }
  13401. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13402. this.camera.attachControl(element, noPreventDefault);
  13403. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13404. };
  13405. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13406. var camera = this.camera;
  13407. this._alpha = +evt.alpha | 0;
  13408. this._beta = +evt.beta | 0;
  13409. this._gamma = +evt.gamma | 0;
  13410. this._dirty = true;
  13411. };
  13412. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13413. if (this._dirty) {
  13414. this._dirty = false;
  13415. if (this._gamma < 0) {
  13416. this._gamma = 180 + this._gamma;
  13417. }
  13418. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13419. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13420. }
  13421. };
  13422. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13423. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13424. };
  13425. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13426. return "ArcRotateCameraVRDeviceOrientationInput";
  13427. };
  13428. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13429. return "VRDeviceOrientation";
  13430. };
  13431. return ArcRotateCameraVRDeviceOrientationInput;
  13432. })();
  13433. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13434. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13435. })(BABYLON || (BABYLON = {}));
  13436. var BABYLON;
  13437. (function (BABYLON) {
  13438. var TargetCamera = (function (_super) {
  13439. __extends(TargetCamera, _super);
  13440. function TargetCamera(name, position, scene) {
  13441. _super.call(this, name, position, scene);
  13442. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13443. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13444. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13445. this.speed = 2.0;
  13446. this.noRotationConstraint = false;
  13447. this.lockedTarget = null;
  13448. this._currentTarget = BABYLON.Vector3.Zero();
  13449. this._viewMatrix = BABYLON.Matrix.Zero();
  13450. this._camMatrix = BABYLON.Matrix.Zero();
  13451. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13452. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13453. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13454. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13455. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13456. this._lookAtTemp = BABYLON.Matrix.Zero();
  13457. this._tempMatrix = BABYLON.Matrix.Zero();
  13458. }
  13459. TargetCamera.prototype.getFrontPosition = function (distance) {
  13460. var direction = this.getTarget().subtract(this.position);
  13461. direction.normalize();
  13462. direction.scaleInPlace(distance);
  13463. return this.globalPosition.add(direction);
  13464. };
  13465. TargetCamera.prototype._getLockedTargetPosition = function () {
  13466. if (!this.lockedTarget) {
  13467. return null;
  13468. }
  13469. return this.lockedTarget.position || this.lockedTarget;
  13470. };
  13471. // Cache
  13472. TargetCamera.prototype._initCache = function () {
  13473. _super.prototype._initCache.call(this);
  13474. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13475. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13476. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13477. };
  13478. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13479. if (!ignoreParentClass) {
  13480. _super.prototype._updateCache.call(this);
  13481. }
  13482. var lockedTargetPosition = this._getLockedTargetPosition();
  13483. if (!lockedTargetPosition) {
  13484. this._cache.lockedTarget = null;
  13485. }
  13486. else {
  13487. if (!this._cache.lockedTarget) {
  13488. this._cache.lockedTarget = lockedTargetPosition.clone();
  13489. }
  13490. else {
  13491. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13492. }
  13493. }
  13494. this._cache.rotation.copyFrom(this.rotation);
  13495. if (this.rotationQuaternion)
  13496. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13497. };
  13498. // Synchronized
  13499. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13500. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13501. return false;
  13502. }
  13503. var lockedTargetPosition = this._getLockedTargetPosition();
  13504. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13505. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13506. };
  13507. // Methods
  13508. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13509. var engine = this.getEngine();
  13510. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13511. };
  13512. // Target
  13513. TargetCamera.prototype.setTarget = function (target) {
  13514. this.upVector.normalize();
  13515. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13516. this._camMatrix.invert();
  13517. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13518. var vDir = target.subtract(this.position);
  13519. if (vDir.x >= 0.0) {
  13520. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13521. }
  13522. else {
  13523. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13524. }
  13525. this.rotation.z = 0;
  13526. if (isNaN(this.rotation.x)) {
  13527. this.rotation.x = 0;
  13528. }
  13529. if (isNaN(this.rotation.y)) {
  13530. this.rotation.y = 0;
  13531. }
  13532. if (isNaN(this.rotation.z)) {
  13533. this.rotation.z = 0;
  13534. }
  13535. if (this.rotationQuaternion) {
  13536. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13537. }
  13538. };
  13539. TargetCamera.prototype.getTarget = function () {
  13540. return this._currentTarget;
  13541. };
  13542. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13543. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13544. };
  13545. TargetCamera.prototype._updatePosition = function () {
  13546. this.position.addInPlace(this.cameraDirection);
  13547. };
  13548. TargetCamera.prototype._checkInputs = function () {
  13549. var needToMove = this._decideIfNeedsToMove();
  13550. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13551. // Move
  13552. if (needToMove) {
  13553. this._updatePosition();
  13554. }
  13555. // Rotate
  13556. if (needToRotate) {
  13557. this.rotation.x += this.cameraRotation.x;
  13558. this.rotation.y += this.cameraRotation.y;
  13559. if (!this.noRotationConstraint) {
  13560. var limit = (Math.PI / 2) * 0.95;
  13561. if (this.rotation.x > limit)
  13562. this.rotation.x = limit;
  13563. if (this.rotation.x < -limit)
  13564. this.rotation.x = -limit;
  13565. }
  13566. }
  13567. // Inertia
  13568. if (needToMove) {
  13569. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13570. this.cameraDirection.x = 0;
  13571. }
  13572. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13573. this.cameraDirection.y = 0;
  13574. }
  13575. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13576. this.cameraDirection.z = 0;
  13577. }
  13578. this.cameraDirection.scaleInPlace(this.inertia);
  13579. }
  13580. if (needToRotate) {
  13581. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13582. this.cameraRotation.x = 0;
  13583. }
  13584. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13585. this.cameraRotation.y = 0;
  13586. }
  13587. this.cameraRotation.scaleInPlace(this.inertia);
  13588. }
  13589. _super.prototype._checkInputs.call(this);
  13590. };
  13591. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13592. if (this.rotationQuaternion) {
  13593. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13594. //update the up vector!
  13595. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13596. }
  13597. else {
  13598. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13599. }
  13600. };
  13601. TargetCamera.prototype._getViewMatrix = function () {
  13602. if (!this.lockedTarget) {
  13603. // Compute
  13604. this._updateCameraRotationMatrix();
  13605. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13606. // Computing target and final matrix
  13607. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13608. }
  13609. else {
  13610. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13611. }
  13612. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13613. return this._viewMatrix;
  13614. };
  13615. /**
  13616. * @override
  13617. * Override Camera.createRigCamera
  13618. */
  13619. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13620. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13621. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13622. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13623. if (!this.rotationQuaternion) {
  13624. this.rotationQuaternion = new BABYLON.Quaternion();
  13625. }
  13626. rigCamera._cameraRigParams = {};
  13627. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13628. }
  13629. return rigCamera;
  13630. }
  13631. return null;
  13632. };
  13633. /**
  13634. * @override
  13635. * Override Camera._updateRigCameras
  13636. */
  13637. TargetCamera.prototype._updateRigCameras = function () {
  13638. var camLeft = this._rigCameras[0];
  13639. var camRight = this._rigCameras[1];
  13640. switch (this.cameraRigMode) {
  13641. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13645. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13646. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13647. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13648. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13649. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13650. camLeft.setTarget(this.getTarget());
  13651. camRight.setTarget(this.getTarget());
  13652. break;
  13653. case BABYLON.Camera.RIG_MODE_VR:
  13654. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13655. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13656. camLeft.position.copyFrom(this.position);
  13657. camRight.position.copyFrom(this.position);
  13658. break;
  13659. }
  13660. _super.prototype._updateRigCameras.call(this);
  13661. };
  13662. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13663. if (!this._rigCamTransformMatrix) {
  13664. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13665. }
  13666. var target = this.getTarget();
  13667. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13668. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13669. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13670. };
  13671. TargetCamera.prototype.getTypeName = function () {
  13672. return "TargetCamera";
  13673. };
  13674. __decorate([
  13675. BABYLON.serializeAsVector3()
  13676. ], TargetCamera.prototype, "rotation", void 0);
  13677. __decorate([
  13678. BABYLON.serialize()
  13679. ], TargetCamera.prototype, "speed", void 0);
  13680. __decorate([
  13681. BABYLON.serializeAsMeshReference("lockedTargetId")
  13682. ], TargetCamera.prototype, "lockedTarget", void 0);
  13683. return TargetCamera;
  13684. })(BABYLON.Camera);
  13685. BABYLON.TargetCamera = TargetCamera;
  13686. })(BABYLON || (BABYLON = {}));
  13687. var BABYLON;
  13688. (function (BABYLON) {
  13689. var FreeCamera = (function (_super) {
  13690. __extends(FreeCamera, _super);
  13691. function FreeCamera(name, position, scene) {
  13692. var _this = this;
  13693. _super.call(this, name, position, scene);
  13694. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13695. this.checkCollisions = false;
  13696. this.applyGravity = false;
  13697. this._collider = new BABYLON.Collider();
  13698. this._needMoveForGravity = false;
  13699. this._oldPosition = BABYLON.Vector3.Zero();
  13700. this._diffPosition = BABYLON.Vector3.Zero();
  13701. this._newPosition = BABYLON.Vector3.Zero();
  13702. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13703. if (collidedMesh === void 0) { collidedMesh = null; }
  13704. //TODO move this to the collision coordinator!
  13705. if (_this.getScene().workerCollisions)
  13706. newPosition.multiplyInPlace(_this._collider.radius);
  13707. var updatePosition = function (newPos) {
  13708. _this._newPosition.copyFrom(newPos);
  13709. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13710. var oldPosition = _this.position.clone();
  13711. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13712. _this.position.addInPlace(_this._diffPosition);
  13713. if (_this.onCollide && collidedMesh) {
  13714. _this.onCollide(collidedMesh);
  13715. }
  13716. }
  13717. };
  13718. updatePosition(newPosition);
  13719. };
  13720. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13721. this.inputs.addKeyboard().addMouse();
  13722. }
  13723. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13724. //-- begin properties for backward compatibility for inputs
  13725. get: function () {
  13726. var mouse = this.inputs.attached["mouse"];
  13727. if (mouse)
  13728. return mouse.angularSensibility;
  13729. },
  13730. set: function (value) {
  13731. var mouse = this.inputs.attached["mouse"];
  13732. if (mouse)
  13733. mouse.angularSensibility = value;
  13734. },
  13735. enumerable: true,
  13736. configurable: true
  13737. });
  13738. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13739. get: function () {
  13740. var keyboard = this.inputs.attached["keyboard"];
  13741. if (keyboard)
  13742. return keyboard.keysUp;
  13743. },
  13744. set: function (value) {
  13745. var keyboard = this.inputs.attached["keyboard"];
  13746. if (keyboard)
  13747. keyboard.keysUp = value;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13753. get: function () {
  13754. var keyboard = this.inputs.attached["keyboard"];
  13755. if (keyboard)
  13756. return keyboard.keysDown;
  13757. },
  13758. set: function (value) {
  13759. var keyboard = this.inputs.attached["keyboard"];
  13760. if (keyboard)
  13761. keyboard.keysDown = value;
  13762. },
  13763. enumerable: true,
  13764. configurable: true
  13765. });
  13766. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13767. get: function () {
  13768. var keyboard = this.inputs.attached["keyboard"];
  13769. if (keyboard)
  13770. return keyboard.keysLeft;
  13771. },
  13772. set: function (value) {
  13773. var keyboard = this.inputs.attached["keyboard"];
  13774. if (keyboard)
  13775. keyboard.keysLeft = value;
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13781. get: function () {
  13782. var keyboard = this.inputs.attached["keyboard"];
  13783. if (keyboard)
  13784. return keyboard.keysRight;
  13785. },
  13786. set: function (value) {
  13787. var keyboard = this.inputs.attached["keyboard"];
  13788. if (keyboard)
  13789. keyboard.keysRight = value;
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. // Controls
  13795. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13796. this.inputs.attachElement(element, noPreventDefault);
  13797. };
  13798. FreeCamera.prototype.detachControl = function (element) {
  13799. this.inputs.detachElement(element);
  13800. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13801. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13802. };
  13803. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13804. var globalPosition;
  13805. if (this.parent) {
  13806. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13807. }
  13808. else {
  13809. globalPosition = this.position;
  13810. }
  13811. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13812. this._collider.radius = this.ellipsoid;
  13813. //no need for clone, as long as gravity is not on.
  13814. var actualVelocity = velocity;
  13815. //add gravity to the velocity to prevent the dual-collision checking
  13816. if (this.applyGravity) {
  13817. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13818. actualVelocity = velocity.add(this.getScene().gravity);
  13819. }
  13820. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13821. };
  13822. FreeCamera.prototype._checkInputs = function () {
  13823. if (!this._localDirection) {
  13824. this._localDirection = BABYLON.Vector3.Zero();
  13825. this._transformedDirection = BABYLON.Vector3.Zero();
  13826. }
  13827. this.inputs.checkInputs();
  13828. _super.prototype._checkInputs.call(this);
  13829. };
  13830. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13831. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13832. };
  13833. FreeCamera.prototype._updatePosition = function () {
  13834. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13835. this._collideWithWorld(this.cameraDirection);
  13836. }
  13837. else {
  13838. this.position.addInPlace(this.cameraDirection);
  13839. }
  13840. };
  13841. FreeCamera.prototype.dispose = function () {
  13842. this.inputs.clear();
  13843. _super.prototype.dispose.call(this);
  13844. };
  13845. FreeCamera.prototype.getTypeName = function () {
  13846. return "FreeCamera";
  13847. };
  13848. __decorate([
  13849. BABYLON.serializeAsVector3()
  13850. ], FreeCamera.prototype, "ellipsoid", void 0);
  13851. __decorate([
  13852. BABYLON.serialize()
  13853. ], FreeCamera.prototype, "checkCollisions", void 0);
  13854. __decorate([
  13855. BABYLON.serialize()
  13856. ], FreeCamera.prototype, "applyGravity", void 0);
  13857. return FreeCamera;
  13858. })(BABYLON.TargetCamera);
  13859. BABYLON.FreeCamera = FreeCamera;
  13860. })(BABYLON || (BABYLON = {}));
  13861. var BABYLON;
  13862. (function (BABYLON) {
  13863. var FreeCameraInputsManager = (function (_super) {
  13864. __extends(FreeCameraInputsManager, _super);
  13865. function FreeCameraInputsManager(camera) {
  13866. _super.call(this, camera);
  13867. }
  13868. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13869. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13870. return this;
  13871. };
  13872. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13873. if (touchEnabled === void 0) { touchEnabled = true; }
  13874. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13875. return this;
  13876. };
  13877. FreeCameraInputsManager.prototype.addGamepad = function () {
  13878. this.add(new BABYLON.FreeCameraGamepadInput());
  13879. return this;
  13880. };
  13881. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13882. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13883. return this;
  13884. };
  13885. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13886. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13887. return this;
  13888. };
  13889. FreeCameraInputsManager.prototype.addTouch = function () {
  13890. this.add(new BABYLON.FreeCameraTouchInput());
  13891. return this;
  13892. };
  13893. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13894. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13895. return this;
  13896. };
  13897. return FreeCameraInputsManager;
  13898. })(BABYLON.CameraInputsManager);
  13899. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13900. })(BABYLON || (BABYLON = {}));
  13901. var BABYLON;
  13902. (function (BABYLON) {
  13903. var FollowCamera = (function (_super) {
  13904. __extends(FollowCamera, _super);
  13905. function FollowCamera(name, position, scene, target) {
  13906. _super.call(this, name, position, scene);
  13907. this.radius = 12;
  13908. this.rotationOffset = 0;
  13909. this.heightOffset = 4;
  13910. this.cameraAcceleration = 0.05;
  13911. this.maxCameraSpeed = 20;
  13912. this.target = target;
  13913. }
  13914. FollowCamera.prototype.getRadians = function (degrees) {
  13915. return degrees * Math.PI / 180;
  13916. };
  13917. FollowCamera.prototype.follow = function (cameraTarget) {
  13918. if (!cameraTarget)
  13919. return;
  13920. var yRotation;
  13921. if (cameraTarget.rotationQuaternion) {
  13922. var rotMatrix = new BABYLON.Matrix();
  13923. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13924. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13925. }
  13926. else {
  13927. yRotation = cameraTarget.rotation.y;
  13928. }
  13929. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13930. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13931. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13932. var dx = targetX - this.position.x;
  13933. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13934. var dz = (targetZ) - this.position.z;
  13935. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13936. var vy = dy * this.cameraAcceleration;
  13937. var vz = dz * this.cameraAcceleration * 2;
  13938. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13939. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13940. }
  13941. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13942. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13943. }
  13944. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13945. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13946. }
  13947. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13948. this.setTarget(cameraTarget.position);
  13949. };
  13950. FollowCamera.prototype._checkInputs = function () {
  13951. _super.prototype._checkInputs.call(this);
  13952. this.follow(this.target);
  13953. };
  13954. FollowCamera.prototype.getTypeName = function () {
  13955. return "FollowCamera";
  13956. };
  13957. __decorate([
  13958. BABYLON.serialize()
  13959. ], FollowCamera.prototype, "radius", void 0);
  13960. __decorate([
  13961. BABYLON.serialize()
  13962. ], FollowCamera.prototype, "rotationOffset", void 0);
  13963. __decorate([
  13964. BABYLON.serialize()
  13965. ], FollowCamera.prototype, "heightOffset", void 0);
  13966. __decorate([
  13967. BABYLON.serialize()
  13968. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13969. __decorate([
  13970. BABYLON.serialize()
  13971. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13972. __decorate([
  13973. BABYLON.serializeAsMeshReference("lockedTargetId")
  13974. ], FollowCamera.prototype, "target", void 0);
  13975. return FollowCamera;
  13976. })(BABYLON.TargetCamera);
  13977. BABYLON.FollowCamera = FollowCamera;
  13978. var ArcFollowCamera = (function (_super) {
  13979. __extends(ArcFollowCamera, _super);
  13980. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13981. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13982. this.alpha = alpha;
  13983. this.beta = beta;
  13984. this.radius = radius;
  13985. this.target = target;
  13986. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13987. this.follow();
  13988. }
  13989. ArcFollowCamera.prototype.follow = function () {
  13990. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13991. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13992. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13993. this.position = this.target.position.add(this._cartesianCoordinates);
  13994. this.setTarget(this.target.position);
  13995. };
  13996. ArcFollowCamera.prototype._checkInputs = function () {
  13997. _super.prototype._checkInputs.call(this);
  13998. this.follow();
  13999. };
  14000. ArcFollowCamera.prototype.getTypeName = function () {
  14001. return "ArcFollowCamera";
  14002. };
  14003. return ArcFollowCamera;
  14004. })(BABYLON.TargetCamera);
  14005. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14006. })(BABYLON || (BABYLON = {}));
  14007. var BABYLON;
  14008. (function (BABYLON) {
  14009. // We're mainly based on the logic defined into the FreeCamera code
  14010. var TouchCamera = (function (_super) {
  14011. __extends(TouchCamera, _super);
  14012. //-- end properties for backward compatibility for inputs
  14013. function TouchCamera(name, position, scene) {
  14014. _super.call(this, name, position, scene);
  14015. this.inputs.addTouch();
  14016. this._setupInputs();
  14017. }
  14018. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14019. //-- Begin properties for backward compatibility for inputs
  14020. get: function () {
  14021. var touch = this.inputs.attached["touch"];
  14022. if (touch)
  14023. return touch.touchAngularSensibility;
  14024. },
  14025. set: function (value) {
  14026. var touch = this.inputs.attached["touch"];
  14027. if (touch)
  14028. touch.touchAngularSensibility = value;
  14029. },
  14030. enumerable: true,
  14031. configurable: true
  14032. });
  14033. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14034. get: function () {
  14035. var touch = this.inputs.attached["touch"];
  14036. if (touch)
  14037. return touch.touchMoveSensibility;
  14038. },
  14039. set: function (value) {
  14040. var touch = this.inputs.attached["touch"];
  14041. if (touch)
  14042. touch.touchMoveSensibility = value;
  14043. },
  14044. enumerable: true,
  14045. configurable: true
  14046. });
  14047. TouchCamera.prototype.getTypeName = function () {
  14048. return "TouchCamera";
  14049. };
  14050. TouchCamera.prototype._setupInputs = function () {
  14051. var mouse = this.inputs.attached["mouse"];
  14052. if (mouse) {
  14053. mouse.touchEnabled = false;
  14054. }
  14055. };
  14056. return TouchCamera;
  14057. })(BABYLON.FreeCamera);
  14058. BABYLON.TouchCamera = TouchCamera;
  14059. })(BABYLON || (BABYLON = {}));
  14060. var BABYLON;
  14061. (function (BABYLON) {
  14062. var ArcRotateCamera = (function (_super) {
  14063. __extends(ArcRotateCamera, _super);
  14064. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14065. var _this = this;
  14066. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14067. this.inertialAlphaOffset = 0;
  14068. this.inertialBetaOffset = 0;
  14069. this.inertialRadiusOffset = 0;
  14070. this.lowerAlphaLimit = null;
  14071. this.upperAlphaLimit = null;
  14072. this.lowerBetaLimit = 0.01;
  14073. this.upperBetaLimit = Math.PI;
  14074. this.lowerRadiusLimit = null;
  14075. this.upperRadiusLimit = null;
  14076. this.inertialPanningX = 0;
  14077. this.inertialPanningY = 0;
  14078. //-- end properties for backward compatibility for inputs
  14079. this.zoomOnFactor = 1;
  14080. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14081. this.allowUpsideDown = true;
  14082. this._viewMatrix = new BABYLON.Matrix();
  14083. // Panning
  14084. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14085. this.checkCollisions = false;
  14086. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14087. this._collider = new BABYLON.Collider();
  14088. this._previousPosition = BABYLON.Vector3.Zero();
  14089. this._collisionVelocity = BABYLON.Vector3.Zero();
  14090. this._newPosition = BABYLON.Vector3.Zero();
  14091. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14092. if (collidedMesh === void 0) { collidedMesh = null; }
  14093. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14094. newPosition.multiplyInPlace(_this._collider.radius);
  14095. }
  14096. if (!collidedMesh) {
  14097. _this._previousPosition.copyFrom(_this.position);
  14098. }
  14099. else {
  14100. _this.setPosition(newPosition);
  14101. if (_this.onCollide) {
  14102. _this.onCollide(collidedMesh);
  14103. }
  14104. }
  14105. // Recompute because of constraints
  14106. var cosa = Math.cos(_this.alpha);
  14107. var sina = Math.sin(_this.alpha);
  14108. var cosb = Math.cos(_this.beta);
  14109. var sinb = Math.sin(_this.beta);
  14110. if (sinb === 0) {
  14111. sinb = 0.0001;
  14112. }
  14113. var target = _this._getTargetPosition();
  14114. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14115. _this.position.copyFrom(_this._newPosition);
  14116. var up = _this.upVector;
  14117. if (_this.allowUpsideDown && _this.beta < 0) {
  14118. up = up.clone();
  14119. up = up.negate();
  14120. }
  14121. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14122. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14123. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14124. _this._collisionTriggered = false;
  14125. };
  14126. if (!target) {
  14127. this.target = BABYLON.Vector3.Zero();
  14128. }
  14129. else {
  14130. this.target = target;
  14131. }
  14132. this.alpha = alpha;
  14133. this.beta = beta;
  14134. this.radius = radius;
  14135. this.getViewMatrix();
  14136. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14137. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14138. }
  14139. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14140. //-- begin properties for backward compatibility for inputs
  14141. get: function () {
  14142. var pointers = this.inputs.attached["pointers"];
  14143. if (pointers)
  14144. return pointers.angularSensibilityX;
  14145. },
  14146. set: function (value) {
  14147. var pointers = this.inputs.attached["pointers"];
  14148. if (pointers) {
  14149. pointers.angularSensibilityX = value;
  14150. }
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14156. get: function () {
  14157. var pointers = this.inputs.attached["pointers"];
  14158. if (pointers)
  14159. return pointers.angularSensibilityY;
  14160. },
  14161. set: function (value) {
  14162. var pointers = this.inputs.attached["pointers"];
  14163. if (pointers) {
  14164. pointers.angularSensibilityY = value;
  14165. }
  14166. },
  14167. enumerable: true,
  14168. configurable: true
  14169. });
  14170. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14171. get: function () {
  14172. var pointers = this.inputs.attached["pointers"];
  14173. if (pointers)
  14174. return pointers.pinchPrecision;
  14175. },
  14176. set: function (value) {
  14177. var pointers = this.inputs.attached["pointers"];
  14178. if (pointers) {
  14179. pointers.pinchPrecision = value;
  14180. }
  14181. },
  14182. enumerable: true,
  14183. configurable: true
  14184. });
  14185. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14186. get: function () {
  14187. var pointers = this.inputs.attached["pointers"];
  14188. if (pointers)
  14189. return pointers.panningSensibility;
  14190. },
  14191. set: function (value) {
  14192. var pointers = this.inputs.attached["pointers"];
  14193. if (pointers) {
  14194. pointers.panningSensibility = value;
  14195. }
  14196. },
  14197. enumerable: true,
  14198. configurable: true
  14199. });
  14200. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14201. get: function () {
  14202. var keyboard = this.inputs.attached["keyboard"];
  14203. if (keyboard)
  14204. return keyboard.keysUp;
  14205. },
  14206. set: function (value) {
  14207. var keyboard = this.inputs.attached["keyboard"];
  14208. if (keyboard)
  14209. keyboard.keysUp = value;
  14210. },
  14211. enumerable: true,
  14212. configurable: true
  14213. });
  14214. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14215. get: function () {
  14216. var keyboard = this.inputs.attached["keyboard"];
  14217. if (keyboard)
  14218. return keyboard.keysDown;
  14219. },
  14220. set: function (value) {
  14221. var keyboard = this.inputs.attached["keyboard"];
  14222. if (keyboard)
  14223. keyboard.keysDown = value;
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14229. get: function () {
  14230. var keyboard = this.inputs.attached["keyboard"];
  14231. if (keyboard)
  14232. return keyboard.keysLeft;
  14233. },
  14234. set: function (value) {
  14235. var keyboard = this.inputs.attached["keyboard"];
  14236. if (keyboard)
  14237. keyboard.keysLeft = value;
  14238. },
  14239. enumerable: true,
  14240. configurable: true
  14241. });
  14242. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14243. get: function () {
  14244. var keyboard = this.inputs.attached["keyboard"];
  14245. if (keyboard)
  14246. return keyboard.keysRight;
  14247. },
  14248. set: function (value) {
  14249. var keyboard = this.inputs.attached["keyboard"];
  14250. if (keyboard)
  14251. keyboard.keysRight = value;
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14257. get: function () {
  14258. var mousewheel = this.inputs.attached["mousewheel"];
  14259. if (mousewheel)
  14260. return mousewheel.wheelPrecision;
  14261. },
  14262. set: function (value) {
  14263. var mousewheel = this.inputs.attached["mousewheel"];
  14264. if (mousewheel)
  14265. mousewheel.wheelPrecision = value;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. // Cache
  14271. ArcRotateCamera.prototype._initCache = function () {
  14272. _super.prototype._initCache.call(this);
  14273. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14274. this._cache.alpha = undefined;
  14275. this._cache.beta = undefined;
  14276. this._cache.radius = undefined;
  14277. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14278. };
  14279. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14280. if (!ignoreParentClass) {
  14281. _super.prototype._updateCache.call(this);
  14282. }
  14283. this._cache.target.copyFrom(this._getTargetPosition());
  14284. this._cache.alpha = this.alpha;
  14285. this._cache.beta = this.beta;
  14286. this._cache.radius = this.radius;
  14287. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14288. };
  14289. ArcRotateCamera.prototype._getTargetPosition = function () {
  14290. if (this.target.getAbsolutePosition) {
  14291. return this.target.getAbsolutePosition();
  14292. }
  14293. return this.target;
  14294. };
  14295. // Synchronized
  14296. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14297. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14298. return false;
  14299. return this._cache.target.equals(this.target)
  14300. && this._cache.alpha === this.alpha
  14301. && this._cache.beta === this.beta
  14302. && this._cache.radius === this.radius
  14303. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14304. };
  14305. // Methods
  14306. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14307. var _this = this;
  14308. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14309. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14310. this._useCtrlForPanning = useCtrlForPanning;
  14311. this._panningMouseButton = panningMouseButton;
  14312. this.inputs.attachElement(element, noPreventDefault);
  14313. this._reset = function () {
  14314. _this.inertialAlphaOffset = 0;
  14315. _this.inertialBetaOffset = 0;
  14316. _this.inertialRadiusOffset = 0;
  14317. };
  14318. };
  14319. ArcRotateCamera.prototype.detachControl = function (element) {
  14320. this.inputs.detachElement(element);
  14321. if (this._reset) {
  14322. this._reset();
  14323. }
  14324. };
  14325. ArcRotateCamera.prototype._checkInputs = function () {
  14326. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14327. if (this._collisionTriggered) {
  14328. return;
  14329. }
  14330. this.inputs.checkInputs();
  14331. // Inertia
  14332. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14333. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14334. this.beta += this.inertialBetaOffset;
  14335. this.radius -= this.inertialRadiusOffset;
  14336. this.inertialAlphaOffset *= this.inertia;
  14337. this.inertialBetaOffset *= this.inertia;
  14338. this.inertialRadiusOffset *= this.inertia;
  14339. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14340. this.inertialAlphaOffset = 0;
  14341. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14342. this.inertialBetaOffset = 0;
  14343. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14344. this.inertialRadiusOffset = 0;
  14345. }
  14346. // Panning inertia
  14347. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14348. if (!this._localDirection) {
  14349. this._localDirection = BABYLON.Vector3.Zero();
  14350. this._transformedDirection = BABYLON.Vector3.Zero();
  14351. }
  14352. this.inertialPanningX *= this.inertia;
  14353. this.inertialPanningY *= this.inertia;
  14354. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14355. this.inertialPanningX = 0;
  14356. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14357. this.inertialPanningY = 0;
  14358. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14359. this._localDirection.multiplyInPlace(this.panningAxis);
  14360. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14361. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14362. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14363. if (!this.panningAxis.y) {
  14364. this._transformedDirection.y = 0;
  14365. }
  14366. if (!this.target.getAbsolutePosition) {
  14367. this.target.addInPlace(this._transformedDirection);
  14368. }
  14369. }
  14370. // Limits
  14371. this._checkLimits();
  14372. _super.prototype._checkInputs.call(this);
  14373. };
  14374. ArcRotateCamera.prototype._checkLimits = function () {
  14375. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14376. if (this.allowUpsideDown && this.beta > Math.PI) {
  14377. this.beta = this.beta - (2 * Math.PI);
  14378. }
  14379. }
  14380. else {
  14381. if (this.beta < this.lowerBetaLimit) {
  14382. this.beta = this.lowerBetaLimit;
  14383. }
  14384. }
  14385. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14386. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14387. this.beta = this.beta + (2 * Math.PI);
  14388. }
  14389. }
  14390. else {
  14391. if (this.beta > this.upperBetaLimit) {
  14392. this.beta = this.upperBetaLimit;
  14393. }
  14394. }
  14395. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14396. this.alpha = this.lowerAlphaLimit;
  14397. }
  14398. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14399. this.alpha = this.upperAlphaLimit;
  14400. }
  14401. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14402. this.radius = this.lowerRadiusLimit;
  14403. }
  14404. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14405. this.radius = this.upperRadiusLimit;
  14406. }
  14407. };
  14408. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14409. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14410. this.radius = radiusv3.length();
  14411. // Alpha
  14412. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14413. if (radiusv3.z < 0) {
  14414. this.alpha = 2 * Math.PI - this.alpha;
  14415. }
  14416. // Beta
  14417. this.beta = Math.acos(radiusv3.y / this.radius);
  14418. this._checkLimits();
  14419. };
  14420. ArcRotateCamera.prototype.setPosition = function (position) {
  14421. if (this.position.equals(position)) {
  14422. return;
  14423. }
  14424. this.position.copyFrom(position);
  14425. this.rebuildAnglesAndRadius();
  14426. };
  14427. ArcRotateCamera.prototype.setTarget = function (target) {
  14428. if (this._getTargetPosition().equals(target)) {
  14429. return;
  14430. }
  14431. this.target = target;
  14432. this.rebuildAnglesAndRadius();
  14433. };
  14434. ArcRotateCamera.prototype._getViewMatrix = function () {
  14435. // Compute
  14436. var cosa = Math.cos(this.alpha);
  14437. var sina = Math.sin(this.alpha);
  14438. var cosb = Math.cos(this.beta);
  14439. var sinb = Math.sin(this.beta);
  14440. if (sinb === 0) {
  14441. sinb = 0.0001;
  14442. }
  14443. var target = this._getTargetPosition();
  14444. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14445. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14446. this._collider.radius = this.collisionRadius;
  14447. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14448. this._collisionTriggered = true;
  14449. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14450. }
  14451. else {
  14452. this.position.copyFrom(this._newPosition);
  14453. var up = this.upVector;
  14454. if (this.allowUpsideDown && this.beta < 0) {
  14455. up = up.clone();
  14456. up = up.negate();
  14457. }
  14458. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14459. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14460. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14461. }
  14462. return this._viewMatrix;
  14463. };
  14464. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14465. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14466. meshes = meshes || this.getScene().meshes;
  14467. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14468. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14469. this.radius = distance * this.zoomOnFactor;
  14470. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14471. };
  14472. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14473. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14474. var meshesOrMinMaxVector;
  14475. var distance;
  14476. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14477. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14478. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14479. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14480. }
  14481. else {
  14482. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14483. distance = meshesOrMinMaxVectorAndDistance.distance;
  14484. }
  14485. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14486. if (!doNotUpdateMaxZ) {
  14487. this.maxZ = distance * 2;
  14488. }
  14489. };
  14490. /**
  14491. * @override
  14492. * Override Camera.createRigCamera
  14493. */
  14494. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14495. var alphaShift;
  14496. switch (this.cameraRigMode) {
  14497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14500. case BABYLON.Camera.RIG_MODE_VR:
  14501. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14502. break;
  14503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14504. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14505. break;
  14506. }
  14507. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14508. rigCam._cameraRigParams = {};
  14509. return rigCam;
  14510. };
  14511. /**
  14512. * @override
  14513. * Override Camera._updateRigCameras
  14514. */
  14515. ArcRotateCamera.prototype._updateRigCameras = function () {
  14516. var camLeft = this._rigCameras[0];
  14517. var camRight = this._rigCameras[1];
  14518. camLeft.beta = camRight.beta = this.beta;
  14519. camLeft.radius = camRight.radius = this.radius;
  14520. switch (this.cameraRigMode) {
  14521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14524. case BABYLON.Camera.RIG_MODE_VR:
  14525. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14526. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14527. break;
  14528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14529. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14530. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14531. break;
  14532. }
  14533. _super.prototype._updateRigCameras.call(this);
  14534. };
  14535. ArcRotateCamera.prototype.dispose = function () {
  14536. this.inputs.clear();
  14537. _super.prototype.dispose.call(this);
  14538. };
  14539. ArcRotateCamera.prototype.getTypeName = function () {
  14540. return "ArcRotateCamera";
  14541. };
  14542. __decorate([
  14543. BABYLON.serialize()
  14544. ], ArcRotateCamera.prototype, "alpha", void 0);
  14545. __decorate([
  14546. BABYLON.serialize()
  14547. ], ArcRotateCamera.prototype, "beta", void 0);
  14548. __decorate([
  14549. BABYLON.serialize()
  14550. ], ArcRotateCamera.prototype, "radius", void 0);
  14551. __decorate([
  14552. BABYLON.serializeAsVector3()
  14553. ], ArcRotateCamera.prototype, "target", void 0);
  14554. __decorate([
  14555. BABYLON.serialize()
  14556. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14557. __decorate([
  14558. BABYLON.serialize()
  14559. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14560. __decorate([
  14561. BABYLON.serialize()
  14562. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14563. __decorate([
  14564. BABYLON.serialize()
  14565. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14566. __decorate([
  14567. BABYLON.serialize()
  14568. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14569. __decorate([
  14570. BABYLON.serialize()
  14571. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14572. __decorate([
  14573. BABYLON.serialize()
  14574. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14575. __decorate([
  14576. BABYLON.serialize()
  14577. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14578. __decorate([
  14579. BABYLON.serialize()
  14580. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14581. __decorate([
  14582. BABYLON.serialize()
  14583. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14584. __decorate([
  14585. BABYLON.serialize()
  14586. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14587. __decorate([
  14588. BABYLON.serialize()
  14589. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14590. __decorate([
  14591. BABYLON.serialize()
  14592. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14593. return ArcRotateCamera;
  14594. })(BABYLON.TargetCamera);
  14595. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14596. })(BABYLON || (BABYLON = {}));
  14597. var BABYLON;
  14598. (function (BABYLON) {
  14599. var ArcRotateCameraInputsManager = (function (_super) {
  14600. __extends(ArcRotateCameraInputsManager, _super);
  14601. function ArcRotateCameraInputsManager(camera) {
  14602. _super.call(this, camera);
  14603. }
  14604. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14605. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14606. return this;
  14607. };
  14608. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14609. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14610. return this;
  14611. };
  14612. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14613. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14614. return this;
  14615. };
  14616. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14617. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14618. return this;
  14619. };
  14620. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14621. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14622. return this;
  14623. };
  14624. return ArcRotateCameraInputsManager;
  14625. })(BABYLON.CameraInputsManager);
  14626. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14627. })(BABYLON || (BABYLON = {}));
  14628. var BABYLON;
  14629. (function (BABYLON) {
  14630. var RenderingManager = (function () {
  14631. function RenderingManager(scene) {
  14632. this._renderingGroups = new Array();
  14633. this._scene = scene;
  14634. }
  14635. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14636. if (this._scene._activeParticleSystems.length === 0) {
  14637. return;
  14638. }
  14639. // Particles
  14640. var activeCamera = this._scene.activeCamera;
  14641. this._scene._particlesDuration.beginMonitoring();
  14642. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14643. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14644. if (particleSystem.renderingGroupId !== index) {
  14645. continue;
  14646. }
  14647. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14648. continue;
  14649. }
  14650. this._clearDepthBuffer();
  14651. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14652. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14653. }
  14654. }
  14655. this._scene._particlesDuration.endMonitoring(false);
  14656. };
  14657. RenderingManager.prototype._renderSprites = function (index) {
  14658. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14659. return;
  14660. }
  14661. // Sprites
  14662. var activeCamera = this._scene.activeCamera;
  14663. this._scene._spritesDuration.beginMonitoring();
  14664. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14665. var spriteManager = this._scene.spriteManagers[id];
  14666. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14667. this._clearDepthBuffer();
  14668. spriteManager.render();
  14669. }
  14670. }
  14671. this._scene._spritesDuration.endMonitoring(false);
  14672. };
  14673. RenderingManager.prototype._clearDepthBuffer = function () {
  14674. if (this._depthBufferAlreadyCleaned) {
  14675. return;
  14676. }
  14677. this._scene.getEngine().clear(0, false, true);
  14678. this._depthBufferAlreadyCleaned = true;
  14679. };
  14680. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14681. if (this._currentRenderSprites) {
  14682. this._renderSprites(this._currentIndex);
  14683. }
  14684. if (this._currentRenderParticles) {
  14685. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14686. }
  14687. };
  14688. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14689. this._currentActiveMeshes = activeMeshes;
  14690. this._currentRenderParticles = renderParticles;
  14691. this._currentRenderSprites = renderSprites;
  14692. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14693. this._depthBufferAlreadyCleaned = index === 0;
  14694. var renderingGroup = this._renderingGroups[index];
  14695. var needToStepBack = false;
  14696. this._currentIndex = index;
  14697. if (renderingGroup) {
  14698. this._clearDepthBuffer();
  14699. if (!renderingGroup.onBeforeTransparentRendering) {
  14700. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14701. }
  14702. if (!renderingGroup.render(customRenderFunction)) {
  14703. this._renderingGroups.splice(index, 1);
  14704. needToStepBack = true;
  14705. this._renderSpritesAndParticles();
  14706. }
  14707. }
  14708. else {
  14709. this._renderSpritesAndParticles();
  14710. }
  14711. if (needToStepBack) {
  14712. index--;
  14713. }
  14714. }
  14715. };
  14716. RenderingManager.prototype.reset = function () {
  14717. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14718. if (renderingGroup) {
  14719. renderingGroup.prepare();
  14720. }
  14721. });
  14722. };
  14723. RenderingManager.prototype.dispatch = function (subMesh) {
  14724. var mesh = subMesh.getMesh();
  14725. var renderingGroupId = mesh.renderingGroupId || 0;
  14726. if (!this._renderingGroups[renderingGroupId]) {
  14727. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14728. }
  14729. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14730. };
  14731. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14732. return RenderingManager;
  14733. })();
  14734. BABYLON.RenderingManager = RenderingManager;
  14735. })(BABYLON || (BABYLON = {}));
  14736. var BABYLON;
  14737. (function (BABYLON) {
  14738. var RenderingGroup = (function () {
  14739. function RenderingGroup(index, scene) {
  14740. this.index = index;
  14741. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14742. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14743. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14744. this._scene = scene;
  14745. }
  14746. RenderingGroup.prototype.render = function (customRenderFunction) {
  14747. if (customRenderFunction) {
  14748. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14749. return true;
  14750. }
  14751. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14752. if (this.onBeforeTransparentRendering) {
  14753. this.onBeforeTransparentRendering();
  14754. }
  14755. return false;
  14756. }
  14757. var engine = this._scene.getEngine();
  14758. // Opaque
  14759. var subIndex;
  14760. var submesh;
  14761. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14762. submesh = this._opaqueSubMeshes.data[subIndex];
  14763. submesh.render(false);
  14764. }
  14765. // Alpha test
  14766. engine.setAlphaTesting(true);
  14767. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14768. submesh = this._alphaTestSubMeshes.data[subIndex];
  14769. submesh.render(false);
  14770. }
  14771. engine.setAlphaTesting(false);
  14772. if (this.onBeforeTransparentRendering) {
  14773. this.onBeforeTransparentRendering();
  14774. }
  14775. // Transparent
  14776. if (this._transparentSubMeshes.length) {
  14777. // Sorting
  14778. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14779. submesh = this._transparentSubMeshes.data[subIndex];
  14780. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14781. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14782. }
  14783. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14784. sortedArray.sort(function (a, b) {
  14785. // Alpha index first
  14786. if (a._alphaIndex > b._alphaIndex) {
  14787. return 1;
  14788. }
  14789. if (a._alphaIndex < b._alphaIndex) {
  14790. return -1;
  14791. }
  14792. // Then distance to camera
  14793. if (a._distanceToCamera < b._distanceToCamera) {
  14794. return 1;
  14795. }
  14796. if (a._distanceToCamera > b._distanceToCamera) {
  14797. return -1;
  14798. }
  14799. return 0;
  14800. });
  14801. // Rendering
  14802. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14803. submesh = sortedArray[subIndex];
  14804. submesh.render(true);
  14805. }
  14806. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14807. }
  14808. return true;
  14809. };
  14810. RenderingGroup.prototype.prepare = function () {
  14811. this._opaqueSubMeshes.reset();
  14812. this._transparentSubMeshes.reset();
  14813. this._alphaTestSubMeshes.reset();
  14814. };
  14815. RenderingGroup.prototype.dispatch = function (subMesh) {
  14816. var material = subMesh.getMaterial();
  14817. var mesh = subMesh.getMesh();
  14818. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14819. this._transparentSubMeshes.push(subMesh);
  14820. }
  14821. else if (material.needAlphaTesting()) {
  14822. this._alphaTestSubMeshes.push(subMesh);
  14823. }
  14824. else {
  14825. this._opaqueSubMeshes.push(subMesh); // Opaque
  14826. }
  14827. };
  14828. return RenderingGroup;
  14829. })();
  14830. BABYLON.RenderingGroup = RenderingGroup;
  14831. })(BABYLON || (BABYLON = {}));
  14832. var BABYLON;
  14833. (function (BABYLON) {
  14834. var PointerEventTypes = (function () {
  14835. function PointerEventTypes() {
  14836. }
  14837. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14838. get: function () {
  14839. return PointerEventTypes._POINTERDOWN;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14845. get: function () {
  14846. return PointerEventTypes._POINTERUP;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14852. get: function () {
  14853. return PointerEventTypes._POINTERMOVE;
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14859. get: function () {
  14860. return PointerEventTypes._POINTERWHEEL;
  14861. },
  14862. enumerable: true,
  14863. configurable: true
  14864. });
  14865. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14866. get: function () {
  14867. return PointerEventTypes._POINTERPICK;
  14868. },
  14869. enumerable: true,
  14870. configurable: true
  14871. });
  14872. PointerEventTypes._POINTERDOWN = 0x01;
  14873. PointerEventTypes._POINTERUP = 0x02;
  14874. PointerEventTypes._POINTERMOVE = 0x04;
  14875. PointerEventTypes._POINTERWHEEL = 0x08;
  14876. PointerEventTypes._POINTERPICK = 0x10;
  14877. return PointerEventTypes;
  14878. })();
  14879. BABYLON.PointerEventTypes = PointerEventTypes;
  14880. var PointerInfoBase = (function () {
  14881. function PointerInfoBase(type, event) {
  14882. this.type = type;
  14883. this.event = event;
  14884. }
  14885. return PointerInfoBase;
  14886. })();
  14887. BABYLON.PointerInfoBase = PointerInfoBase;
  14888. /**
  14889. * This class is used to store pointer related info for the onPrePointerObservable event.
  14890. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14891. */
  14892. var PointerInfoPre = (function (_super) {
  14893. __extends(PointerInfoPre, _super);
  14894. function PointerInfoPre(type, event, localX, localY) {
  14895. _super.call(this, type, event);
  14896. this.skipOnPointerObservable = false;
  14897. this.localPosition = new BABYLON.Vector2(localX, localY);
  14898. }
  14899. return PointerInfoPre;
  14900. })(PointerInfoBase);
  14901. BABYLON.PointerInfoPre = PointerInfoPre;
  14902. /**
  14903. * This type contains all the data related to a pointer event in Babylon.js.
  14904. * 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.
  14905. */
  14906. var PointerInfo = (function (_super) {
  14907. __extends(PointerInfo, _super);
  14908. function PointerInfo(type, event, pickInfo) {
  14909. _super.call(this, type, event);
  14910. this.pickInfo = pickInfo;
  14911. }
  14912. return PointerInfo;
  14913. })(PointerInfoBase);
  14914. BABYLON.PointerInfo = PointerInfo;
  14915. /**
  14916. * Represents a scene to be rendered by the engine.
  14917. * @see http://doc.babylonjs.com/page.php?p=21911
  14918. */
  14919. var Scene = (function () {
  14920. /**
  14921. * @constructor
  14922. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14923. */
  14924. function Scene(engine) {
  14925. // Members
  14926. this.autoClear = true;
  14927. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14928. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14929. this.forceWireframe = false;
  14930. this.forcePointsCloud = false;
  14931. this.forceShowBoundingBoxes = false;
  14932. this.animationsEnabled = true;
  14933. this.constantlyUpdateMeshUnderPointer = false;
  14934. this.hoverCursor = "pointer";
  14935. // Events
  14936. /**
  14937. * An event triggered when the scene is disposed.
  14938. * @type {BABYLON.Observable}
  14939. */
  14940. this.onDisposeObservable = new BABYLON.Observable();
  14941. /**
  14942. * An event triggered before rendering the scene
  14943. * @type {BABYLON.Observable}
  14944. */
  14945. this.onBeforeRenderObservable = new BABYLON.Observable();
  14946. /**
  14947. * An event triggered after rendering the scene
  14948. * @type {BABYLON.Observable}
  14949. */
  14950. this.onAfterRenderObservable = new BABYLON.Observable();
  14951. /**
  14952. * An event triggered when the scene is ready
  14953. * @type {BABYLON.Observable}
  14954. */
  14955. this.onReadyObservable = new BABYLON.Observable();
  14956. /**
  14957. * An event triggered before rendering a camera
  14958. * @type {BABYLON.Observable}
  14959. */
  14960. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14961. /**
  14962. * An event triggered after rendering a camera
  14963. * @type {BABYLON.Observable}
  14964. */
  14965. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14966. /**
  14967. * An event triggered when a camera is created
  14968. * @type {BABYLON.Observable}
  14969. */
  14970. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14971. /**
  14972. * An event triggered when a camera is removed
  14973. * @type {BABYLON.Observable}
  14974. */
  14975. this.onCameraRemovedObservable = new BABYLON.Observable();
  14976. /**
  14977. * An event triggered when a light is created
  14978. * @type {BABYLON.Observable}
  14979. */
  14980. this.onNewLightAddedObservable = new BABYLON.Observable();
  14981. /**
  14982. * An event triggered when a light is removed
  14983. * @type {BABYLON.Observable}
  14984. */
  14985. this.onLightRemovedObservable = new BABYLON.Observable();
  14986. /**
  14987. * An event triggered when a geometry is created
  14988. * @type {BABYLON.Observable}
  14989. */
  14990. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14991. /**
  14992. * An event triggered when a geometry is removed
  14993. * @type {BABYLON.Observable}
  14994. */
  14995. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14996. /**
  14997. * An event triggered when a mesh is created
  14998. * @type {BABYLON.Observable}
  14999. */
  15000. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15001. /**
  15002. * An event triggered when a mesh is removed
  15003. * @type {BABYLON.Observable}
  15004. */
  15005. this.onMeshRemovedObservable = new BABYLON.Observable();
  15006. // Animations
  15007. this.animations = [];
  15008. /**
  15009. * 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).
  15010. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15011. */
  15012. this.onPrePointerObservable = new BABYLON.Observable();
  15013. /**
  15014. * Observable event triggered each time an input event is received from the rendering canvas
  15015. */
  15016. this.onPointerObservable = new BABYLON.Observable();
  15017. 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
  15018. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15019. this._startingPointerTime = 0;
  15020. // Fog
  15021. /**
  15022. * is fog enabled on this scene.
  15023. * @type {boolean}
  15024. */
  15025. this.fogEnabled = true;
  15026. this.fogMode = Scene.FOGMODE_NONE;
  15027. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15028. this.fogDensity = 0.1;
  15029. this.fogStart = 0;
  15030. this.fogEnd = 1000.0;
  15031. // Lights
  15032. /**
  15033. * is shadow enabled on this scene.
  15034. * @type {boolean}
  15035. */
  15036. this.shadowsEnabled = true;
  15037. /**
  15038. * is light enabled on this scene.
  15039. * @type {boolean}
  15040. */
  15041. this.lightsEnabled = true;
  15042. /**
  15043. * All of the lights added to this scene.
  15044. * @see BABYLON.Light
  15045. * @type {BABYLON.Light[]}
  15046. */
  15047. this.lights = new Array();
  15048. // Cameras
  15049. /**
  15050. * All of the cameras added to this scene.
  15051. * @see BABYLON.Camera
  15052. * @type {BABYLON.Camera[]}
  15053. */
  15054. this.cameras = new Array();
  15055. this.activeCameras = new Array();
  15056. // Meshes
  15057. /**
  15058. * All of the (abstract) meshes added to this scene.
  15059. * @see BABYLON.AbstractMesh
  15060. * @type {BABYLON.AbstractMesh[]}
  15061. */
  15062. this.meshes = new Array();
  15063. // Geometries
  15064. this._geometries = new Array();
  15065. this.materials = new Array();
  15066. this.multiMaterials = new Array();
  15067. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15068. // Textures
  15069. this.texturesEnabled = true;
  15070. this.textures = new Array();
  15071. // Particles
  15072. this.particlesEnabled = true;
  15073. this.particleSystems = new Array();
  15074. // Sprites
  15075. this.spritesEnabled = true;
  15076. this.spriteManagers = new Array();
  15077. // Layers
  15078. this.layers = new Array();
  15079. // Skeletons
  15080. this.skeletonsEnabled = true;
  15081. this.skeletons = new Array();
  15082. // Lens flares
  15083. this.lensFlaresEnabled = true;
  15084. this.lensFlareSystems = new Array();
  15085. // Collisions
  15086. this.collisionsEnabled = true;
  15087. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15088. // Postprocesses
  15089. this.postProcessesEnabled = true;
  15090. // Customs render targets
  15091. this.renderTargetsEnabled = true;
  15092. this.dumpNextRenderTargets = false;
  15093. this.customRenderTargets = new Array();
  15094. // Imported meshes
  15095. this.importedMeshesFiles = new Array();
  15096. // Probes
  15097. this.probesEnabled = true;
  15098. this.reflectionProbes = new Array();
  15099. this._actionManagers = new Array();
  15100. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15101. // Procedural textures
  15102. this.proceduralTexturesEnabled = true;
  15103. this._proceduralTextures = new Array();
  15104. this.soundTracks = new Array();
  15105. this._audioEnabled = true;
  15106. this._headphone = false;
  15107. // Performance counters
  15108. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15109. this._totalLightsCounter = new BABYLON.PerfCounter();
  15110. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15111. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15112. this._totalVertices = new BABYLON.PerfCounter();
  15113. this._activeIndices = new BABYLON.PerfCounter();
  15114. this._activeParticles = new BABYLON.PerfCounter();
  15115. this._lastFrameDuration = new BABYLON.PerfCounter();
  15116. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15117. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15118. this._particlesDuration = new BABYLON.PerfCounter();
  15119. this._renderDuration = new BABYLON.PerfCounter();
  15120. this._spritesDuration = new BABYLON.PerfCounter();
  15121. this._activeBones = new BABYLON.PerfCounter();
  15122. this._renderId = 0;
  15123. this._executeWhenReadyTimeoutId = -1;
  15124. this._intermediateRendering = false;
  15125. this._toBeDisposed = new BABYLON.SmartArray(256);
  15126. this._pendingData = []; //ANY
  15127. this._activeMeshes = new BABYLON.SmartArray(256);
  15128. this._processedMaterials = new BABYLON.SmartArray(256);
  15129. this._renderTargets = new BABYLON.SmartArray(256);
  15130. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15131. this._activeSkeletons = new BABYLON.SmartArray(32);
  15132. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15133. this._activeAnimatables = new Array();
  15134. this._transformMatrix = BABYLON.Matrix.Zero();
  15135. this._edgesRenderers = new BABYLON.SmartArray(16);
  15136. this._uniqueIdCounter = 0;
  15137. this._engine = engine;
  15138. engine.scenes.push(this);
  15139. this._renderingManager = new BABYLON.RenderingManager(this);
  15140. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15141. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15142. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15143. if (BABYLON.OutlineRenderer) {
  15144. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15145. }
  15146. this.attachControl();
  15147. if (BABYLON.SoundTrack) {
  15148. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15149. }
  15150. //simplification queue
  15151. if (BABYLON.SimplificationQueue) {
  15152. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15153. }
  15154. //collision coordinator initialization. For now legacy per default.
  15155. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15156. }
  15157. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15158. get: function () {
  15159. return Scene._FOGMODE_NONE;
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15165. get: function () {
  15166. return Scene._FOGMODE_EXP;
  15167. },
  15168. enumerable: true,
  15169. configurable: true
  15170. });
  15171. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15172. get: function () {
  15173. return Scene._FOGMODE_EXP2;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15179. get: function () {
  15180. return Scene._FOGMODE_LINEAR;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Object.defineProperty(Scene.prototype, "onDispose", {
  15186. set: function (callback) {
  15187. if (this._onDisposeObserver) {
  15188. this.onDisposeObservable.remove(this._onDisposeObserver);
  15189. }
  15190. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15191. },
  15192. enumerable: true,
  15193. configurable: true
  15194. });
  15195. Object.defineProperty(Scene.prototype, "beforeRender", {
  15196. set: function (callback) {
  15197. if (this._onBeforeRenderObserver) {
  15198. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15199. }
  15200. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15201. },
  15202. enumerable: true,
  15203. configurable: true
  15204. });
  15205. Object.defineProperty(Scene.prototype, "afterRender", {
  15206. set: function (callback) {
  15207. if (this._onAfterRenderObserver) {
  15208. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15209. }
  15210. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15211. },
  15212. enumerable: true,
  15213. configurable: true
  15214. });
  15215. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15216. set: function (callback) {
  15217. if (this._onBeforeCameraRenderObserver) {
  15218. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15219. }
  15220. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15221. },
  15222. enumerable: true,
  15223. configurable: true
  15224. });
  15225. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15226. set: function (callback) {
  15227. if (this._onAfterCameraRenderObserver) {
  15228. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15229. }
  15230. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15231. },
  15232. enumerable: true,
  15233. configurable: true
  15234. });
  15235. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15236. get: function () {
  15237. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15238. },
  15239. enumerable: true,
  15240. configurable: true
  15241. });
  15242. Object.defineProperty(Scene.prototype, "debugLayer", {
  15243. // Properties
  15244. get: function () {
  15245. if (!this._debugLayer) {
  15246. this._debugLayer = new BABYLON.DebugLayer(this);
  15247. }
  15248. return this._debugLayer;
  15249. },
  15250. enumerable: true,
  15251. configurable: true
  15252. });
  15253. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15254. get: function () {
  15255. return this._workerCollisions;
  15256. },
  15257. set: function (enabled) {
  15258. enabled = (enabled && !!Worker);
  15259. this._workerCollisions = enabled;
  15260. if (this.collisionCoordinator) {
  15261. this.collisionCoordinator.destroy();
  15262. }
  15263. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15264. this.collisionCoordinator.init(this);
  15265. },
  15266. enumerable: true,
  15267. configurable: true
  15268. });
  15269. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15270. get: function () {
  15271. return this._selectionOctree;
  15272. },
  15273. enumerable: true,
  15274. configurable: true
  15275. });
  15276. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15277. /**
  15278. * The mesh that is currently under the pointer.
  15279. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15280. */
  15281. get: function () {
  15282. return this._pointerOverMesh;
  15283. },
  15284. enumerable: true,
  15285. configurable: true
  15286. });
  15287. Object.defineProperty(Scene.prototype, "pointerX", {
  15288. /**
  15289. * Current on-screen X position of the pointer
  15290. * @return {number} X position of the pointer
  15291. */
  15292. get: function () {
  15293. return this._pointerX;
  15294. },
  15295. enumerable: true,
  15296. configurable: true
  15297. });
  15298. Object.defineProperty(Scene.prototype, "pointerY", {
  15299. /**
  15300. * Current on-screen Y position of the pointer
  15301. * @return {number} Y position of the pointer
  15302. */
  15303. get: function () {
  15304. return this._pointerY;
  15305. },
  15306. enumerable: true,
  15307. configurable: true
  15308. });
  15309. Scene.prototype.getCachedMaterial = function () {
  15310. return this._cachedMaterial;
  15311. };
  15312. Scene.prototype.getBoundingBoxRenderer = function () {
  15313. return this._boundingBoxRenderer;
  15314. };
  15315. Scene.prototype.getOutlineRenderer = function () {
  15316. return this._outlineRenderer;
  15317. };
  15318. Scene.prototype.getEngine = function () {
  15319. return this._engine;
  15320. };
  15321. Scene.prototype.getTotalVertices = function () {
  15322. return this._totalVertices.current;
  15323. };
  15324. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15325. get: function () {
  15326. return this._totalVertices;
  15327. },
  15328. enumerable: true,
  15329. configurable: true
  15330. });
  15331. Scene.prototype.getActiveIndices = function () {
  15332. return this._activeIndices.current;
  15333. };
  15334. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15335. get: function () {
  15336. return this._activeIndices;
  15337. },
  15338. enumerable: true,
  15339. configurable: true
  15340. });
  15341. Scene.prototype.getActiveParticles = function () {
  15342. return this._activeParticles.current;
  15343. };
  15344. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15345. get: function () {
  15346. return this._activeParticles;
  15347. },
  15348. enumerable: true,
  15349. configurable: true
  15350. });
  15351. Scene.prototype.getActiveBones = function () {
  15352. return this._activeBones.current;
  15353. };
  15354. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15355. get: function () {
  15356. return this._activeBones;
  15357. },
  15358. enumerable: true,
  15359. configurable: true
  15360. });
  15361. // Stats
  15362. Scene.prototype.getLastFrameDuration = function () {
  15363. return this._lastFrameDuration.current;
  15364. };
  15365. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15366. get: function () {
  15367. return this._lastFrameDuration;
  15368. },
  15369. enumerable: true,
  15370. configurable: true
  15371. });
  15372. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15373. return this._evaluateActiveMeshesDuration.current;
  15374. };
  15375. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15376. get: function () {
  15377. return this._evaluateActiveMeshesDuration;
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. Scene.prototype.getActiveMeshes = function () {
  15383. return this._activeMeshes;
  15384. };
  15385. Scene.prototype.getRenderTargetsDuration = function () {
  15386. return this._renderTargetsDuration.current;
  15387. };
  15388. Scene.prototype.getRenderDuration = function () {
  15389. return this._renderDuration.current;
  15390. };
  15391. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15392. get: function () {
  15393. return this._renderDuration;
  15394. },
  15395. enumerable: true,
  15396. configurable: true
  15397. });
  15398. Scene.prototype.getParticlesDuration = function () {
  15399. return this._particlesDuration.current;
  15400. };
  15401. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15402. get: function () {
  15403. return this._particlesDuration;
  15404. },
  15405. enumerable: true,
  15406. configurable: true
  15407. });
  15408. Scene.prototype.getSpritesDuration = function () {
  15409. return this._spritesDuration.current;
  15410. };
  15411. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15412. get: function () {
  15413. return this._spritesDuration;
  15414. },
  15415. enumerable: true,
  15416. configurable: true
  15417. });
  15418. Scene.prototype.getAnimationRatio = function () {
  15419. return this._animationRatio;
  15420. };
  15421. Scene.prototype.getRenderId = function () {
  15422. return this._renderId;
  15423. };
  15424. Scene.prototype.incrementRenderId = function () {
  15425. this._renderId++;
  15426. };
  15427. Scene.prototype._updatePointerPosition = function (evt) {
  15428. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15429. this._pointerX = evt.clientX - canvasRect.left;
  15430. this._pointerY = evt.clientY - canvasRect.top;
  15431. this._unTranslatedPointerX = this._pointerX;
  15432. this._unTranslatedPointerY = this._pointerY;
  15433. if (this.cameraToUseForPointers) {
  15434. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15435. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15436. }
  15437. };
  15438. // Pointers handling
  15439. /**
  15440. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15441. * @param attachUp defines if you want to attach events to pointerup
  15442. * @param attachDown defines if you want to attach events to pointerdown
  15443. * @param attachMove defines if you want to attach events to pointermove
  15444. */
  15445. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15446. var _this = this;
  15447. if (attachUp === void 0) { attachUp = true; }
  15448. if (attachDown === void 0) { attachDown = true; }
  15449. if (attachMove === void 0) { attachMove = true; }
  15450. var spritePredicate = function (sprite) {
  15451. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15452. };
  15453. this._onPointerMove = function (evt) {
  15454. _this._updatePointerPosition(evt);
  15455. // PreObservable support
  15456. if (_this.onPrePointerObservable.hasObservers()) {
  15457. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15458. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15459. _this.onPrePointerObservable.notifyObservers(pi, type);
  15460. if (pi.skipOnPointerObservable) {
  15461. return;
  15462. }
  15463. }
  15464. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15465. return;
  15466. }
  15467. var canvas = _this._engine.getRenderingCanvas();
  15468. if (!_this.pointerMovePredicate) {
  15469. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15470. }
  15471. // Meshes
  15472. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15473. if (pickResult.hit && pickResult.pickedMesh) {
  15474. _this.setPointerOverSprite(null);
  15475. _this.setPointerOverMesh(pickResult.pickedMesh);
  15476. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15477. canvas.style.cursor = _this.hoverCursor;
  15478. }
  15479. else {
  15480. canvas.style.cursor = "";
  15481. }
  15482. }
  15483. else {
  15484. _this.setPointerOverMesh(null);
  15485. // Sprites
  15486. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15487. if (pickResult.hit && pickResult.pickedSprite) {
  15488. canvas.style.cursor = _this.hoverCursor;
  15489. _this.setPointerOverSprite(pickResult.pickedSprite);
  15490. }
  15491. else {
  15492. _this.setPointerOverSprite(null);
  15493. // Restore pointer
  15494. canvas.style.cursor = "";
  15495. }
  15496. }
  15497. if (_this.onPointerMove) {
  15498. _this.onPointerMove(evt, pickResult);
  15499. }
  15500. if (_this.onPointerObservable.hasObservers()) {
  15501. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15502. var pi = new PointerInfo(type, evt, pickResult);
  15503. _this.onPointerObservable.notifyObservers(pi, type);
  15504. }
  15505. };
  15506. this._onPointerDown = function (evt) {
  15507. _this._updatePointerPosition(evt);
  15508. // PreObservable support
  15509. if (_this.onPrePointerObservable.hasObservers()) {
  15510. var type = PointerEventTypes.POINTERDOWN;
  15511. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15512. _this.onPrePointerObservable.notifyObservers(pi, type);
  15513. if (pi.skipOnPointerObservable) {
  15514. return;
  15515. }
  15516. }
  15517. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15518. return;
  15519. }
  15520. _this._startingPointerPosition.x = _this._pointerX;
  15521. _this._startingPointerPosition.y = _this._pointerY;
  15522. _this._startingPointerTime = new Date().getTime();
  15523. if (!_this.pointerDownPredicate) {
  15524. _this.pointerDownPredicate = function (mesh) {
  15525. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15526. };
  15527. }
  15528. // Meshes
  15529. _this._pickedDownMesh = null;
  15530. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15531. if (pickResult.hit && pickResult.pickedMesh) {
  15532. if (pickResult.pickedMesh.actionManager) {
  15533. _this._pickedDownMesh = pickResult.pickedMesh;
  15534. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15535. switch (evt.button) {
  15536. case 0:
  15537. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15538. break;
  15539. case 1:
  15540. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15541. break;
  15542. case 2:
  15543. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15544. break;
  15545. }
  15546. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15547. }
  15548. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15549. var that = _this;
  15550. window.setTimeout(function () {
  15551. 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);
  15552. if (pickResult.hit && pickResult.pickedMesh) {
  15553. if (pickResult.pickedMesh.actionManager) {
  15554. 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)) {
  15555. that._startingPointerTime = 0;
  15556. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15557. }
  15558. }
  15559. }
  15560. }, BABYLON.ActionManager.LongPressDelay);
  15561. }
  15562. }
  15563. }
  15564. if (_this.onPointerDown) {
  15565. _this.onPointerDown(evt, pickResult);
  15566. }
  15567. if (_this.onPointerObservable.hasObservers()) {
  15568. var type = PointerEventTypes.POINTERDOWN;
  15569. var pi = new PointerInfo(type, evt, pickResult);
  15570. _this.onPointerObservable.notifyObservers(pi, type);
  15571. }
  15572. // Sprites
  15573. _this._pickedDownSprite = null;
  15574. if (_this.spriteManagers.length > 0) {
  15575. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15576. if (pickResult.hit && pickResult.pickedSprite) {
  15577. if (pickResult.pickedSprite.actionManager) {
  15578. _this._pickedDownSprite = pickResult.pickedSprite;
  15579. switch (evt.button) {
  15580. case 0:
  15581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15582. break;
  15583. case 1:
  15584. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15585. break;
  15586. case 2:
  15587. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15588. break;
  15589. }
  15590. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15591. }
  15592. }
  15593. }
  15594. };
  15595. this._onPointerUp = function (evt) {
  15596. _this._updatePointerPosition(evt);
  15597. // PreObservable support
  15598. if (_this.onPrePointerObservable.hasObservers()) {
  15599. var type = PointerEventTypes.POINTERUP;
  15600. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15601. _this.onPrePointerObservable.notifyObservers(pi, type);
  15602. if (pi.skipOnPointerObservable) {
  15603. return;
  15604. }
  15605. }
  15606. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15607. return;
  15608. }
  15609. if (!_this.pointerUpPredicate) {
  15610. _this.pointerUpPredicate = function (mesh) {
  15611. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15612. };
  15613. }
  15614. // Meshes
  15615. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15616. if (pickResult.hit && pickResult.pickedMesh) {
  15617. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15618. if (_this.onPointerPick) {
  15619. _this.onPointerPick(evt, pickResult);
  15620. }
  15621. if (_this.onPointerObservable.hasObservers()) {
  15622. var type = PointerEventTypes.POINTERPICK;
  15623. var pi = new PointerInfo(type, evt, pickResult);
  15624. _this.onPointerObservable.notifyObservers(pi, type);
  15625. }
  15626. }
  15627. if (pickResult.pickedMesh.actionManager) {
  15628. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15629. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15630. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15631. }
  15632. }
  15633. }
  15634. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15635. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15636. }
  15637. if (_this.onPointerUp) {
  15638. _this.onPointerUp(evt, pickResult);
  15639. }
  15640. if (_this.onPointerObservable.hasObservers()) {
  15641. var type = PointerEventTypes.POINTERUP;
  15642. var pi = new PointerInfo(type, evt, pickResult);
  15643. _this.onPointerObservable.notifyObservers(pi, type);
  15644. }
  15645. _this._startingPointerTime = 0;
  15646. // Sprites
  15647. if (_this.spriteManagers.length > 0) {
  15648. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15649. if (pickResult.hit && pickResult.pickedSprite) {
  15650. if (pickResult.pickedSprite.actionManager) {
  15651. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15652. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15654. }
  15655. }
  15656. }
  15657. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15658. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15659. }
  15660. }
  15661. };
  15662. this._onKeyDown = function (evt) {
  15663. if (_this.actionManager) {
  15664. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15665. }
  15666. };
  15667. this._onKeyUp = function (evt) {
  15668. if (_this.actionManager) {
  15669. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15670. }
  15671. };
  15672. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15673. var canvas = this._engine.getRenderingCanvas();
  15674. if (attachMove) {
  15675. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15676. // Wheel
  15677. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15678. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15679. }
  15680. if (attachDown) {
  15681. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15682. }
  15683. if (attachUp) {
  15684. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15685. }
  15686. canvas.tabIndex = 1;
  15687. canvas.addEventListener("keydown", this._onKeyDown, false);
  15688. canvas.addEventListener("keyup", this._onKeyUp, false);
  15689. };
  15690. Scene.prototype.detachControl = function () {
  15691. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15692. var canvas = this._engine.getRenderingCanvas();
  15693. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15694. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15695. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15696. // Wheel
  15697. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15698. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15699. canvas.removeEventListener("keydown", this._onKeyDown);
  15700. canvas.removeEventListener("keyup", this._onKeyUp);
  15701. };
  15702. // Ready
  15703. Scene.prototype.isReady = function () {
  15704. if (this._pendingData.length > 0) {
  15705. return false;
  15706. }
  15707. var index;
  15708. for (index = 0; index < this._geometries.length; index++) {
  15709. var geometry = this._geometries[index];
  15710. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15711. return false;
  15712. }
  15713. }
  15714. for (index = 0; index < this.meshes.length; index++) {
  15715. var mesh = this.meshes[index];
  15716. if (!mesh.isReady()) {
  15717. return false;
  15718. }
  15719. var mat = mesh.material;
  15720. if (mat) {
  15721. if (!mat.isReady(mesh)) {
  15722. return false;
  15723. }
  15724. }
  15725. }
  15726. return true;
  15727. };
  15728. Scene.prototype.resetCachedMaterial = function () {
  15729. this._cachedMaterial = null;
  15730. };
  15731. Scene.prototype.registerBeforeRender = function (func) {
  15732. this.onBeforeRenderObservable.add(func);
  15733. };
  15734. Scene.prototype.unregisterBeforeRender = function (func) {
  15735. this.onBeforeRenderObservable.removeCallback(func);
  15736. };
  15737. Scene.prototype.registerAfterRender = function (func) {
  15738. this.onAfterRenderObservable.add(func);
  15739. };
  15740. Scene.prototype.unregisterAfterRender = function (func) {
  15741. this.onAfterRenderObservable.removeCallback(func);
  15742. };
  15743. Scene.prototype._addPendingData = function (data) {
  15744. this._pendingData.push(data);
  15745. };
  15746. Scene.prototype._removePendingData = function (data) {
  15747. var index = this._pendingData.indexOf(data);
  15748. if (index !== -1) {
  15749. this._pendingData.splice(index, 1);
  15750. }
  15751. };
  15752. Scene.prototype.getWaitingItemsCount = function () {
  15753. return this._pendingData.length;
  15754. };
  15755. /**
  15756. * Registers a function to be executed when the scene is ready.
  15757. * @param {Function} func - the function to be executed.
  15758. */
  15759. Scene.prototype.executeWhenReady = function (func) {
  15760. var _this = this;
  15761. this.onReadyObservable.add(func);
  15762. if (this._executeWhenReadyTimeoutId !== -1) {
  15763. return;
  15764. }
  15765. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15766. _this._checkIsReady();
  15767. }, 150);
  15768. };
  15769. Scene.prototype._checkIsReady = function () {
  15770. var _this = this;
  15771. if (this.isReady()) {
  15772. this.onReadyObservable.notifyObservers(this);
  15773. this.onReadyObservable.clear();
  15774. this._executeWhenReadyTimeoutId = -1;
  15775. return;
  15776. }
  15777. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15778. _this._checkIsReady();
  15779. }, 150);
  15780. };
  15781. // Animations
  15782. /**
  15783. * Will start the animation sequence of a given target
  15784. * @param target - the target
  15785. * @param {number} from - from which frame should animation start
  15786. * @param {number} to - till which frame should animation run.
  15787. * @param {boolean} [loop] - should the animation loop
  15788. * @param {number} [speedRatio] - the speed in which to run the animation
  15789. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15790. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15791. * @return {BABYLON.Animatable} the animatable object created for this animation
  15792. * @see BABYLON.Animatable
  15793. * @see http://doc.babylonjs.com/page.php?p=22081
  15794. */
  15795. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15796. if (speedRatio === void 0) { speedRatio = 1.0; }
  15797. this.stopAnimation(target);
  15798. if (!animatable) {
  15799. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15800. }
  15801. // Local animations
  15802. if (target.animations) {
  15803. animatable.appendAnimations(target, target.animations);
  15804. }
  15805. // Children animations
  15806. if (target.getAnimatables) {
  15807. var animatables = target.getAnimatables();
  15808. for (var index = 0; index < animatables.length; index++) {
  15809. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15810. }
  15811. }
  15812. animatable.reset();
  15813. return animatable;
  15814. };
  15815. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15816. if (speedRatio === undefined) {
  15817. speedRatio = 1.0;
  15818. }
  15819. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15820. return animatable;
  15821. };
  15822. Scene.prototype.getAnimatableByTarget = function (target) {
  15823. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15824. if (this._activeAnimatables[index].target === target) {
  15825. return this._activeAnimatables[index];
  15826. }
  15827. }
  15828. return null;
  15829. };
  15830. Object.defineProperty(Scene.prototype, "Animatables", {
  15831. get: function () {
  15832. return this._activeAnimatables;
  15833. },
  15834. enumerable: true,
  15835. configurable: true
  15836. });
  15837. /**
  15838. * Will stop the animation of the given target
  15839. * @param target - the target
  15840. * @see beginAnimation
  15841. */
  15842. Scene.prototype.stopAnimation = function (target) {
  15843. var animatable = this.getAnimatableByTarget(target);
  15844. if (animatable) {
  15845. animatable.stop();
  15846. }
  15847. };
  15848. Scene.prototype._animate = function () {
  15849. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15850. return;
  15851. }
  15852. if (!this._animationStartDate) {
  15853. if (this._pendingData.length > 0) {
  15854. return;
  15855. }
  15856. this._animationStartDate = BABYLON.Tools.Now;
  15857. }
  15858. // Getting time
  15859. var now = BABYLON.Tools.Now;
  15860. var delay = now - this._animationStartDate;
  15861. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15862. this._activeAnimatables[index]._animate(delay);
  15863. }
  15864. };
  15865. // Matrix
  15866. Scene.prototype.getViewMatrix = function () {
  15867. return this._viewMatrix;
  15868. };
  15869. Scene.prototype.getProjectionMatrix = function () {
  15870. return this._projectionMatrix;
  15871. };
  15872. Scene.prototype.getTransformMatrix = function () {
  15873. return this._transformMatrix;
  15874. };
  15875. Scene.prototype.setTransformMatrix = function (view, projection) {
  15876. this._viewMatrix = view;
  15877. this._projectionMatrix = projection;
  15878. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15879. // Update frustum
  15880. if (!this._frustumPlanes) {
  15881. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15882. }
  15883. else {
  15884. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15885. }
  15886. };
  15887. // Methods
  15888. Scene.prototype.addMesh = function (newMesh) {
  15889. newMesh.uniqueId = this._uniqueIdCounter++;
  15890. var position = this.meshes.push(newMesh);
  15891. //notify the collision coordinator
  15892. this.collisionCoordinator.onMeshAdded(newMesh);
  15893. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15894. };
  15895. Scene.prototype.removeMesh = function (toRemove) {
  15896. var index = this.meshes.indexOf(toRemove);
  15897. if (index !== -1) {
  15898. // Remove from the scene if mesh found
  15899. this.meshes.splice(index, 1);
  15900. }
  15901. //notify the collision coordinator
  15902. this.collisionCoordinator.onMeshRemoved(toRemove);
  15903. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15904. return index;
  15905. };
  15906. Scene.prototype.removeSkeleton = function (toRemove) {
  15907. var index = this.skeletons.indexOf(toRemove);
  15908. if (index !== -1) {
  15909. // Remove from the scene if mesh found
  15910. this.skeletons.splice(index, 1);
  15911. }
  15912. return index;
  15913. };
  15914. Scene.prototype.removeLight = function (toRemove) {
  15915. var index = this.lights.indexOf(toRemove);
  15916. if (index !== -1) {
  15917. // Remove from the scene if mesh found
  15918. this.lights.splice(index, 1);
  15919. }
  15920. this.onLightRemovedObservable.notifyObservers(toRemove);
  15921. return index;
  15922. };
  15923. Scene.prototype.removeCamera = function (toRemove) {
  15924. var index = this.cameras.indexOf(toRemove);
  15925. if (index !== -1) {
  15926. // Remove from the scene if mesh found
  15927. this.cameras.splice(index, 1);
  15928. }
  15929. // Remove from activeCameras
  15930. var index2 = this.activeCameras.indexOf(toRemove);
  15931. if (index2 !== -1) {
  15932. // Remove from the scene if mesh found
  15933. this.activeCameras.splice(index2, 1);
  15934. }
  15935. // Reset the activeCamera
  15936. if (this.activeCamera === toRemove) {
  15937. if (this.cameras.length > 0) {
  15938. this.activeCamera = this.cameras[0];
  15939. }
  15940. else {
  15941. this.activeCamera = null;
  15942. }
  15943. }
  15944. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15945. return index;
  15946. };
  15947. Scene.prototype.addLight = function (newLight) {
  15948. newLight.uniqueId = this._uniqueIdCounter++;
  15949. var position = this.lights.push(newLight);
  15950. this.onNewLightAddedObservable.notifyObservers(newLight);
  15951. };
  15952. Scene.prototype.addCamera = function (newCamera) {
  15953. newCamera.uniqueId = this._uniqueIdCounter++;
  15954. var position = this.cameras.push(newCamera);
  15955. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15956. };
  15957. /**
  15958. * Switch active camera
  15959. * @param {Camera} newCamera - new active camera
  15960. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15961. */
  15962. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15963. if (attachControl === void 0) { attachControl = true; }
  15964. var canvas = this._engine.getRenderingCanvas();
  15965. this.activeCamera.detachControl(canvas);
  15966. this.activeCamera = newCamera;
  15967. if (attachControl) {
  15968. newCamera.attachControl(canvas);
  15969. }
  15970. };
  15971. /**
  15972. * sets the active camera of the scene using its ID
  15973. * @param {string} id - the camera's ID
  15974. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15975. * @see activeCamera
  15976. */
  15977. Scene.prototype.setActiveCameraByID = function (id) {
  15978. var camera = this.getCameraByID(id);
  15979. if (camera) {
  15980. this.activeCamera = camera;
  15981. return camera;
  15982. }
  15983. return null;
  15984. };
  15985. /**
  15986. * sets the active camera of the scene using its name
  15987. * @param {string} name - the camera's name
  15988. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15989. * @see activeCamera
  15990. */
  15991. Scene.prototype.setActiveCameraByName = function (name) {
  15992. var camera = this.getCameraByName(name);
  15993. if (camera) {
  15994. this.activeCamera = camera;
  15995. return camera;
  15996. }
  15997. return null;
  15998. };
  15999. /**
  16000. * get a material using its id
  16001. * @param {string} the material's ID
  16002. * @return {BABYLON.Material|null} the material or null if none found.
  16003. */
  16004. Scene.prototype.getMaterialByID = function (id) {
  16005. for (var index = 0; index < this.materials.length; index++) {
  16006. if (this.materials[index].id === id) {
  16007. return this.materials[index];
  16008. }
  16009. }
  16010. return null;
  16011. };
  16012. /**
  16013. * get a material using its name
  16014. * @param {string} the material's name
  16015. * @return {BABYLON.Material|null} the material or null if none found.
  16016. */
  16017. Scene.prototype.getMaterialByName = function (name) {
  16018. for (var index = 0; index < this.materials.length; index++) {
  16019. if (this.materials[index].name === name) {
  16020. return this.materials[index];
  16021. }
  16022. }
  16023. return null;
  16024. };
  16025. Scene.prototype.getLensFlareSystemByName = function (name) {
  16026. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16027. if (this.lensFlareSystems[index].name === name) {
  16028. return this.lensFlareSystems[index];
  16029. }
  16030. }
  16031. return null;
  16032. };
  16033. Scene.prototype.getLensFlareSystemByID = function (id) {
  16034. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16035. if (this.lensFlareSystems[index].id === id) {
  16036. return this.lensFlareSystems[index];
  16037. }
  16038. }
  16039. return null;
  16040. };
  16041. Scene.prototype.getCameraByID = function (id) {
  16042. for (var index = 0; index < this.cameras.length; index++) {
  16043. if (this.cameras[index].id === id) {
  16044. return this.cameras[index];
  16045. }
  16046. }
  16047. return null;
  16048. };
  16049. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16050. for (var index = 0; index < this.cameras.length; index++) {
  16051. if (this.cameras[index].uniqueId === uniqueId) {
  16052. return this.cameras[index];
  16053. }
  16054. }
  16055. return null;
  16056. };
  16057. /**
  16058. * get a camera using its name
  16059. * @param {string} the camera's name
  16060. * @return {BABYLON.Camera|null} the camera or null if none found.
  16061. */
  16062. Scene.prototype.getCameraByName = function (name) {
  16063. for (var index = 0; index < this.cameras.length; index++) {
  16064. if (this.cameras[index].name === name) {
  16065. return this.cameras[index];
  16066. }
  16067. }
  16068. return null;
  16069. };
  16070. /**
  16071. * get a bone using its id
  16072. * @param {string} the bone's id
  16073. * @return {BABYLON.Bone|null} the bone or null if not found
  16074. */
  16075. Scene.prototype.getBoneByID = function (id) {
  16076. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16077. var skeleton = this.skeletons[skeletonIndex];
  16078. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16079. if (skeleton.bones[boneIndex].id === id) {
  16080. return skeleton.bones[boneIndex];
  16081. }
  16082. }
  16083. }
  16084. return null;
  16085. };
  16086. /**
  16087. * get a bone using its id
  16088. * @param {string} the bone's name
  16089. * @return {BABYLON.Bone|null} the bone or null if not found
  16090. */
  16091. Scene.prototype.getBoneByName = function (name) {
  16092. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16093. var skeleton = this.skeletons[skeletonIndex];
  16094. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16095. if (skeleton.bones[boneIndex].name === name) {
  16096. return skeleton.bones[boneIndex];
  16097. }
  16098. }
  16099. }
  16100. return null;
  16101. };
  16102. /**
  16103. * get a light node using its name
  16104. * @param {string} the light's name
  16105. * @return {BABYLON.Light|null} the light or null if none found.
  16106. */
  16107. Scene.prototype.getLightByName = function (name) {
  16108. for (var index = 0; index < this.lights.length; index++) {
  16109. if (this.lights[index].name === name) {
  16110. return this.lights[index];
  16111. }
  16112. }
  16113. return null;
  16114. };
  16115. /**
  16116. * get a light node using its ID
  16117. * @param {string} the light's id
  16118. * @return {BABYLON.Light|null} the light or null if none found.
  16119. */
  16120. Scene.prototype.getLightByID = function (id) {
  16121. for (var index = 0; index < this.lights.length; index++) {
  16122. if (this.lights[index].id === id) {
  16123. return this.lights[index];
  16124. }
  16125. }
  16126. return null;
  16127. };
  16128. /**
  16129. * get a light node using its scene-generated unique ID
  16130. * @param {number} the light's unique id
  16131. * @return {BABYLON.Light|null} the light or null if none found.
  16132. */
  16133. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16134. for (var index = 0; index < this.lights.length; index++) {
  16135. if (this.lights[index].uniqueId === uniqueId) {
  16136. return this.lights[index];
  16137. }
  16138. }
  16139. return null;
  16140. };
  16141. /**
  16142. * get a particle system by id
  16143. * @param id {number} the particle system id
  16144. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16145. */
  16146. Scene.prototype.getParticleSystemByID = function (id) {
  16147. for (var index = 0; index < this.particleSystems.length; index++) {
  16148. if (this.particleSystems[index].id === id) {
  16149. return this.particleSystems[index];
  16150. }
  16151. }
  16152. return null;
  16153. };
  16154. /**
  16155. * get a geometry using its ID
  16156. * @param {string} the geometry's id
  16157. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16158. */
  16159. Scene.prototype.getGeometryByID = function (id) {
  16160. for (var index = 0; index < this._geometries.length; index++) {
  16161. if (this._geometries[index].id === id) {
  16162. return this._geometries[index];
  16163. }
  16164. }
  16165. return null;
  16166. };
  16167. /**
  16168. * add a new geometry to this scene.
  16169. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16170. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16171. * @return {boolean} was the geometry added or not
  16172. */
  16173. Scene.prototype.pushGeometry = function (geometry, force) {
  16174. if (!force && this.getGeometryByID(geometry.id)) {
  16175. return false;
  16176. }
  16177. this._geometries.push(geometry);
  16178. //notify the collision coordinator
  16179. this.collisionCoordinator.onGeometryAdded(geometry);
  16180. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16181. return true;
  16182. };
  16183. /**
  16184. * Removes an existing geometry
  16185. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16186. * @return {boolean} was the geometry removed or not
  16187. */
  16188. Scene.prototype.removeGeometry = function (geometry) {
  16189. var index = this._geometries.indexOf(geometry);
  16190. if (index > -1) {
  16191. this._geometries.splice(index, 1);
  16192. //notify the collision coordinator
  16193. this.collisionCoordinator.onGeometryDeleted(geometry);
  16194. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16195. return true;
  16196. }
  16197. return false;
  16198. };
  16199. Scene.prototype.getGeometries = function () {
  16200. return this._geometries;
  16201. };
  16202. /**
  16203. * Get the first added mesh found of a given ID
  16204. * @param {string} id - the id to search for
  16205. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16206. */
  16207. Scene.prototype.getMeshByID = function (id) {
  16208. for (var index = 0; index < this.meshes.length; index++) {
  16209. if (this.meshes[index].id === id) {
  16210. return this.meshes[index];
  16211. }
  16212. }
  16213. return null;
  16214. };
  16215. Scene.prototype.getMeshesByID = function (id) {
  16216. return this.meshes.filter(function (m) {
  16217. return m.id === id;
  16218. });
  16219. };
  16220. /**
  16221. * Get a mesh with its auto-generated unique id
  16222. * @param {number} uniqueId - the unique id to search for
  16223. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16224. */
  16225. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16226. for (var index = 0; index < this.meshes.length; index++) {
  16227. if (this.meshes[index].uniqueId === uniqueId) {
  16228. return this.meshes[index];
  16229. }
  16230. }
  16231. return null;
  16232. };
  16233. /**
  16234. * Get a the last added mesh found of a given ID
  16235. * @param {string} id - the id to search for
  16236. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16237. */
  16238. Scene.prototype.getLastMeshByID = function (id) {
  16239. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16240. if (this.meshes[index].id === id) {
  16241. return this.meshes[index];
  16242. }
  16243. }
  16244. return null;
  16245. };
  16246. /**
  16247. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16248. * @param {string} id - the id to search for
  16249. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16250. */
  16251. Scene.prototype.getLastEntryByID = function (id) {
  16252. var index;
  16253. for (index = this.meshes.length - 1; index >= 0; index--) {
  16254. if (this.meshes[index].id === id) {
  16255. return this.meshes[index];
  16256. }
  16257. }
  16258. for (index = this.cameras.length - 1; index >= 0; index--) {
  16259. if (this.cameras[index].id === id) {
  16260. return this.cameras[index];
  16261. }
  16262. }
  16263. for (index = this.lights.length - 1; index >= 0; index--) {
  16264. if (this.lights[index].id === id) {
  16265. return this.lights[index];
  16266. }
  16267. }
  16268. return null;
  16269. };
  16270. Scene.prototype.getNodeByID = function (id) {
  16271. var mesh = this.getMeshByID(id);
  16272. if (mesh) {
  16273. return mesh;
  16274. }
  16275. var light = this.getLightByID(id);
  16276. if (light) {
  16277. return light;
  16278. }
  16279. var camera = this.getCameraByID(id);
  16280. if (camera) {
  16281. return camera;
  16282. }
  16283. var bone = this.getBoneByID(id);
  16284. return bone;
  16285. };
  16286. Scene.prototype.getNodeByName = function (name) {
  16287. var mesh = this.getMeshByName(name);
  16288. if (mesh) {
  16289. return mesh;
  16290. }
  16291. var light = this.getLightByName(name);
  16292. if (light) {
  16293. return light;
  16294. }
  16295. var camera = this.getCameraByName(name);
  16296. if (camera) {
  16297. return camera;
  16298. }
  16299. var bone = this.getBoneByName(name);
  16300. return bone;
  16301. };
  16302. Scene.prototype.getMeshByName = function (name) {
  16303. for (var index = 0; index < this.meshes.length; index++) {
  16304. if (this.meshes[index].name === name) {
  16305. return this.meshes[index];
  16306. }
  16307. }
  16308. return null;
  16309. };
  16310. Scene.prototype.getSoundByName = function (name) {
  16311. var index;
  16312. if (BABYLON.AudioEngine) {
  16313. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16314. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16315. return this.mainSoundTrack.soundCollection[index];
  16316. }
  16317. }
  16318. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16319. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16320. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16321. return this.soundTracks[sdIndex].soundCollection[index];
  16322. }
  16323. }
  16324. }
  16325. }
  16326. return null;
  16327. };
  16328. Scene.prototype.getLastSkeletonByID = function (id) {
  16329. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16330. if (this.skeletons[index].id === id) {
  16331. return this.skeletons[index];
  16332. }
  16333. }
  16334. return null;
  16335. };
  16336. Scene.prototype.getSkeletonById = function (id) {
  16337. for (var index = 0; index < this.skeletons.length; index++) {
  16338. if (this.skeletons[index].id === id) {
  16339. return this.skeletons[index];
  16340. }
  16341. }
  16342. return null;
  16343. };
  16344. Scene.prototype.getSkeletonByName = function (name) {
  16345. for (var index = 0; index < this.skeletons.length; index++) {
  16346. if (this.skeletons[index].name === name) {
  16347. return this.skeletons[index];
  16348. }
  16349. }
  16350. return null;
  16351. };
  16352. Scene.prototype.isActiveMesh = function (mesh) {
  16353. return (this._activeMeshes.indexOf(mesh) !== -1);
  16354. };
  16355. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16356. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16357. var material = subMesh.getMaterial();
  16358. if (mesh.showSubMeshesBoundingBox) {
  16359. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16360. }
  16361. if (material) {
  16362. // Render targets
  16363. if (material.getRenderTargetTextures) {
  16364. if (this._processedMaterials.indexOf(material) === -1) {
  16365. this._processedMaterials.push(material);
  16366. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16367. }
  16368. }
  16369. // Dispatch
  16370. this._activeIndices.addCount(subMesh.indexCount, false);
  16371. this._renderingManager.dispatch(subMesh);
  16372. }
  16373. }
  16374. };
  16375. Scene.prototype._isInIntermediateRendering = function () {
  16376. return this._intermediateRendering;
  16377. };
  16378. Scene.prototype._evaluateActiveMeshes = function () {
  16379. this.activeCamera._activeMeshes.reset();
  16380. this._activeMeshes.reset();
  16381. this._renderingManager.reset();
  16382. this._processedMaterials.reset();
  16383. this._activeParticleSystems.reset();
  16384. this._activeSkeletons.reset();
  16385. this._softwareSkinnedMeshes.reset();
  16386. this._boundingBoxRenderer.reset();
  16387. this._edgesRenderers.reset();
  16388. // Meshes
  16389. var meshes;
  16390. var len;
  16391. if (this._selectionOctree) {
  16392. var selection = this._selectionOctree.select(this._frustumPlanes);
  16393. meshes = selection.data;
  16394. len = selection.length;
  16395. }
  16396. else {
  16397. len = this.meshes.length;
  16398. meshes = this.meshes;
  16399. }
  16400. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16401. var mesh = meshes[meshIndex];
  16402. if (mesh.isBlocked) {
  16403. continue;
  16404. }
  16405. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16406. if (!mesh.isReady() || !mesh.isEnabled()) {
  16407. continue;
  16408. }
  16409. mesh.computeWorldMatrix();
  16410. // Intersections
  16411. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16412. this._meshesForIntersections.pushNoDuplicate(mesh);
  16413. }
  16414. // Switch to current LOD
  16415. var meshLOD = mesh.getLOD(this.activeCamera);
  16416. if (!meshLOD) {
  16417. continue;
  16418. }
  16419. mesh._preActivate();
  16420. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16421. this._activeMeshes.push(mesh);
  16422. this.activeCamera._activeMeshes.push(mesh);
  16423. mesh._activate(this._renderId);
  16424. this._activeMesh(meshLOD);
  16425. }
  16426. }
  16427. // Particle systems
  16428. this._particlesDuration.beginMonitoring();
  16429. var beforeParticlesDate = BABYLON.Tools.Now;
  16430. if (this.particlesEnabled) {
  16431. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16432. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16433. var particleSystem = this.particleSystems[particleIndex];
  16434. if (!particleSystem.isStarted()) {
  16435. continue;
  16436. }
  16437. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16438. this._activeParticleSystems.push(particleSystem);
  16439. particleSystem.animate();
  16440. }
  16441. }
  16442. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16443. }
  16444. this._particlesDuration.endMonitoring(false);
  16445. };
  16446. Scene.prototype._activeMesh = function (mesh) {
  16447. if (mesh.skeleton && this.skeletonsEnabled) {
  16448. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16449. mesh.skeleton.prepare();
  16450. }
  16451. if (!mesh.computeBonesUsingShaders) {
  16452. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16453. }
  16454. }
  16455. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16456. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  16457. }
  16458. if (mesh._edgesRenderer) {
  16459. this._edgesRenderers.push(mesh._edgesRenderer);
  16460. }
  16461. if (mesh && mesh.subMeshes) {
  16462. // Submeshes Octrees
  16463. var len;
  16464. var subMeshes;
  16465. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16466. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16467. len = intersections.length;
  16468. subMeshes = intersections.data;
  16469. }
  16470. else {
  16471. subMeshes = mesh.subMeshes;
  16472. len = subMeshes.length;
  16473. }
  16474. for (var subIndex = 0; subIndex < len; subIndex++) {
  16475. var subMesh = subMeshes[subIndex];
  16476. this._evaluateSubMesh(subMesh, mesh);
  16477. }
  16478. }
  16479. };
  16480. Scene.prototype.updateTransformMatrix = function (force) {
  16481. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16482. };
  16483. Scene.prototype._renderForCamera = function (camera) {
  16484. var engine = this._engine;
  16485. var startTime = BABYLON.Tools.Now;
  16486. this.activeCamera = camera;
  16487. if (!this.activeCamera)
  16488. throw new Error("Active camera not set");
  16489. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16490. // Viewport
  16491. engine.setViewport(this.activeCamera.viewport);
  16492. // Camera
  16493. this.resetCachedMaterial();
  16494. this._renderId++;
  16495. this.updateTransformMatrix();
  16496. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16497. // Meshes
  16498. this._evaluateActiveMeshesDuration.beginMonitoring();
  16499. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16500. this._evaluateActiveMeshes();
  16501. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16502. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16503. // Software skinning
  16504. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16505. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16506. mesh.applySkeleton(mesh.skeleton);
  16507. }
  16508. // Render targets
  16509. this._renderTargetsDuration.beginMonitoring();
  16510. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16511. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16512. this._intermediateRendering = true;
  16513. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16514. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16515. var renderTarget = this._renderTargets.data[renderIndex];
  16516. if (renderTarget._shouldRender()) {
  16517. this._renderId++;
  16518. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16519. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16520. }
  16521. }
  16522. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16523. this._intermediateRendering = false;
  16524. this._renderId++;
  16525. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16526. }
  16527. this._renderTargetsDuration.endMonitoring(false);
  16528. // Prepare Frame
  16529. this.postProcessManager._prepareFrame();
  16530. this._renderDuration.beginMonitoring();
  16531. // Backgrounds
  16532. var layerIndex;
  16533. var layer;
  16534. if (this.layers.length) {
  16535. engine.setDepthBuffer(false);
  16536. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16537. layer = this.layers[layerIndex];
  16538. if (layer.isBackground) {
  16539. layer.render();
  16540. }
  16541. }
  16542. engine.setDepthBuffer(true);
  16543. }
  16544. // Render
  16545. BABYLON.Tools.StartPerformanceCounter("Main render");
  16546. this._renderingManager.render(null, null, true, true);
  16547. BABYLON.Tools.EndPerformanceCounter("Main render");
  16548. // Bounding boxes
  16549. this._boundingBoxRenderer.render();
  16550. // Edges
  16551. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16552. this._edgesRenderers.data[edgesRendererIndex].render();
  16553. }
  16554. // Lens flares
  16555. if (this.lensFlaresEnabled) {
  16556. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16557. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16558. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16559. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16560. lensFlareSystem.render();
  16561. }
  16562. }
  16563. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16564. }
  16565. // Foregrounds
  16566. if (this.layers.length) {
  16567. engine.setDepthBuffer(false);
  16568. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16569. layer = this.layers[layerIndex];
  16570. if (!layer.isBackground) {
  16571. layer.render();
  16572. }
  16573. }
  16574. engine.setDepthBuffer(true);
  16575. }
  16576. this._renderDuration.endMonitoring(false);
  16577. // Finalize frame
  16578. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16579. // Update camera
  16580. this.activeCamera._updateFromScene();
  16581. // Reset some special arrays
  16582. this._renderTargets.reset();
  16583. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16584. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16585. };
  16586. Scene.prototype._processSubCameras = function (camera) {
  16587. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16588. this._renderForCamera(camera);
  16589. return;
  16590. }
  16591. // rig cameras
  16592. for (var index = 0; index < camera._rigCameras.length; index++) {
  16593. this._renderForCamera(camera._rigCameras[index]);
  16594. }
  16595. this.activeCamera = camera;
  16596. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16597. // Update camera
  16598. this.activeCamera._updateFromScene();
  16599. };
  16600. Scene.prototype._checkIntersections = function () {
  16601. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16602. var sourceMesh = this._meshesForIntersections.data[index];
  16603. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16604. var action = sourceMesh.actionManager.actions[actionIndex];
  16605. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16606. var parameters = action.getTriggerParameter();
  16607. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16608. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16609. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16610. if (areIntersecting && currentIntersectionInProgress === -1) {
  16611. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16612. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16613. sourceMesh._intersectionsInProgress.push(otherMesh);
  16614. }
  16615. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16616. sourceMesh._intersectionsInProgress.push(otherMesh);
  16617. }
  16618. }
  16619. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16620. //They intersected, and now they don't.
  16621. //is this trigger an exit trigger? execute an event.
  16622. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16623. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16624. }
  16625. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16626. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16627. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16628. }
  16629. }
  16630. }
  16631. }
  16632. }
  16633. };
  16634. Scene.prototype.render = function () {
  16635. this._lastFrameDuration.beginMonitoring();
  16636. this._particlesDuration.fetchNewFrame();
  16637. this._spritesDuration.fetchNewFrame();
  16638. this._activeParticles.fetchNewFrame();
  16639. this._renderDuration.fetchNewFrame();
  16640. this._renderTargetsDuration.fetchNewFrame();
  16641. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16642. this._totalVertices.fetchNewFrame();
  16643. this._activeIndices.fetchNewFrame();
  16644. this._activeBones.fetchNewFrame();
  16645. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16646. this._meshesForIntersections.reset();
  16647. this.resetCachedMaterial();
  16648. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16649. // Actions
  16650. if (this.actionManager) {
  16651. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16652. }
  16653. //Simplification Queue
  16654. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16655. this.simplificationQueue.executeNext();
  16656. }
  16657. // Animations
  16658. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16659. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16660. this._animate();
  16661. // Physics
  16662. if (this._physicsEngine) {
  16663. BABYLON.Tools.StartPerformanceCounter("Physics");
  16664. this._physicsEngine._step(deltaTime / 1000.0);
  16665. BABYLON.Tools.EndPerformanceCounter("Physics");
  16666. }
  16667. // Before render
  16668. this.onBeforeRenderObservable.notifyObservers(this);
  16669. // Customs render targets
  16670. this._renderTargetsDuration.beginMonitoring();
  16671. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16672. var engine = this.getEngine();
  16673. var currentActiveCamera = this.activeCamera;
  16674. if (this.renderTargetsEnabled) {
  16675. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16676. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16677. var renderTarget = this.customRenderTargets[customIndex];
  16678. if (renderTarget._shouldRender()) {
  16679. this._renderId++;
  16680. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16681. if (!this.activeCamera)
  16682. throw new Error("Active camera not set");
  16683. // Viewport
  16684. engine.setViewport(this.activeCamera.viewport);
  16685. // Camera
  16686. this.updateTransformMatrix();
  16687. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16688. }
  16689. }
  16690. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16691. this._renderId++;
  16692. }
  16693. if (this.customRenderTargets.length > 0) {
  16694. engine.restoreDefaultFramebuffer();
  16695. }
  16696. this._renderTargetsDuration.endMonitoring();
  16697. this.activeCamera = currentActiveCamera;
  16698. // Procedural textures
  16699. if (this.proceduralTexturesEnabled) {
  16700. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16701. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16702. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16703. if (proceduralTexture._shouldRender()) {
  16704. proceduralTexture.render();
  16705. }
  16706. }
  16707. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16708. }
  16709. // Clear
  16710. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16711. // Shadows
  16712. if (this.shadowsEnabled) {
  16713. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16714. var light = this.lights[lightIndex];
  16715. var shadowGenerator = light.getShadowGenerator();
  16716. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16717. this._renderTargets.push(shadowGenerator.getShadowMap());
  16718. }
  16719. }
  16720. }
  16721. // Depth renderer
  16722. if (this._depthRenderer) {
  16723. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16724. }
  16725. // RenderPipeline
  16726. this.postProcessRenderPipelineManager.update();
  16727. // Multi-cameras?
  16728. if (this.activeCameras.length > 0) {
  16729. var currentRenderId = this._renderId;
  16730. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16731. this._renderId = currentRenderId;
  16732. if (cameraIndex > 0) {
  16733. this._engine.clear(0, false, true);
  16734. }
  16735. this._processSubCameras(this.activeCameras[cameraIndex]);
  16736. }
  16737. }
  16738. else {
  16739. if (!this.activeCamera) {
  16740. throw new Error("No camera defined");
  16741. }
  16742. this._processSubCameras(this.activeCamera);
  16743. }
  16744. // Intersection checks
  16745. this._checkIntersections();
  16746. // Update the audio listener attached to the camera
  16747. if (BABYLON.AudioEngine) {
  16748. this._updateAudioParameters();
  16749. }
  16750. // After render
  16751. if (this.afterRender) {
  16752. this.afterRender();
  16753. }
  16754. this.onAfterRenderObservable.notifyObservers(this);
  16755. // Cleaning
  16756. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16757. this._toBeDisposed.data[index].dispose();
  16758. this._toBeDisposed[index] = null;
  16759. }
  16760. this._toBeDisposed.reset();
  16761. if (this.dumpNextRenderTargets) {
  16762. this.dumpNextRenderTargets = false;
  16763. }
  16764. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16765. this._lastFrameDuration.endMonitoring();
  16766. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16767. this._totalLightsCounter.addCount(this.lights.length, true);
  16768. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16769. this._totalTexturesCounter.addCount(this.textures.length, true);
  16770. this._activeBones.addCount(0, true);
  16771. this._activeIndices.addCount(0, true);
  16772. this._activeParticles.addCount(0, true);
  16773. };
  16774. Scene.prototype._updateAudioParameters = function () {
  16775. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16776. return;
  16777. }
  16778. var listeningCamera;
  16779. var audioEngine = BABYLON.Engine.audioEngine;
  16780. if (this.activeCameras.length > 0) {
  16781. listeningCamera = this.activeCameras[0];
  16782. }
  16783. else {
  16784. listeningCamera = this.activeCamera;
  16785. }
  16786. if (listeningCamera && audioEngine.canUseWebAudio) {
  16787. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16788. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16789. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16790. cameraDirection.normalize();
  16791. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16792. var i;
  16793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16794. var sound = this.mainSoundTrack.soundCollection[i];
  16795. if (sound.useCustomAttenuation) {
  16796. sound.updateDistanceFromListener();
  16797. }
  16798. }
  16799. for (i = 0; i < this.soundTracks.length; i++) {
  16800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16801. sound = this.soundTracks[i].soundCollection[j];
  16802. if (sound.useCustomAttenuation) {
  16803. sound.updateDistanceFromListener();
  16804. }
  16805. }
  16806. }
  16807. }
  16808. };
  16809. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16810. // Audio
  16811. get: function () {
  16812. return this._audioEnabled;
  16813. },
  16814. set: function (value) {
  16815. this._audioEnabled = value;
  16816. if (BABYLON.AudioEngine) {
  16817. if (this._audioEnabled) {
  16818. this._enableAudio();
  16819. }
  16820. else {
  16821. this._disableAudio();
  16822. }
  16823. }
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Scene.prototype._disableAudio = function () {
  16829. var i;
  16830. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16831. this.mainSoundTrack.soundCollection[i].pause();
  16832. }
  16833. for (i = 0; i < this.soundTracks.length; i++) {
  16834. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16835. this.soundTracks[i].soundCollection[j].pause();
  16836. }
  16837. }
  16838. };
  16839. Scene.prototype._enableAudio = function () {
  16840. var i;
  16841. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16842. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16843. this.mainSoundTrack.soundCollection[i].play();
  16844. }
  16845. }
  16846. for (i = 0; i < this.soundTracks.length; i++) {
  16847. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16848. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16849. this.soundTracks[i].soundCollection[j].play();
  16850. }
  16851. }
  16852. }
  16853. };
  16854. Object.defineProperty(Scene.prototype, "headphone", {
  16855. get: function () {
  16856. return this._headphone;
  16857. },
  16858. set: function (value) {
  16859. this._headphone = value;
  16860. if (BABYLON.AudioEngine) {
  16861. if (this._headphone) {
  16862. this._switchAudioModeForHeadphones();
  16863. }
  16864. else {
  16865. this._switchAudioModeForNormalSpeakers();
  16866. }
  16867. }
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. Scene.prototype._switchAudioModeForHeadphones = function () {
  16873. this.mainSoundTrack.switchPanningModelToHRTF();
  16874. for (var i = 0; i < this.soundTracks.length; i++) {
  16875. this.soundTracks[i].switchPanningModelToHRTF();
  16876. }
  16877. };
  16878. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16879. this.mainSoundTrack.switchPanningModelToEqualPower();
  16880. for (var i = 0; i < this.soundTracks.length; i++) {
  16881. this.soundTracks[i].switchPanningModelToEqualPower();
  16882. }
  16883. };
  16884. Scene.prototype.enableDepthRenderer = function () {
  16885. if (this._depthRenderer) {
  16886. return this._depthRenderer;
  16887. }
  16888. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16889. return this._depthRenderer;
  16890. };
  16891. Scene.prototype.disableDepthRenderer = function () {
  16892. if (!this._depthRenderer) {
  16893. return;
  16894. }
  16895. this._depthRenderer.dispose();
  16896. this._depthRenderer = null;
  16897. };
  16898. Scene.prototype.freezeMaterials = function () {
  16899. for (var i = 0; i < this.materials.length; i++) {
  16900. this.materials[i].freeze();
  16901. }
  16902. };
  16903. Scene.prototype.unfreezeMaterials = function () {
  16904. for (var i = 0; i < this.materials.length; i++) {
  16905. this.materials[i].unfreeze();
  16906. }
  16907. };
  16908. Scene.prototype.dispose = function () {
  16909. this.beforeRender = null;
  16910. this.afterRender = null;
  16911. this.skeletons = [];
  16912. this._boundingBoxRenderer.dispose();
  16913. if (this._depthRenderer) {
  16914. this._depthRenderer.dispose();
  16915. }
  16916. // Debug layer
  16917. if (this._debugLayer) {
  16918. this._debugLayer.hide();
  16919. }
  16920. // Events
  16921. this.onDisposeObservable.notifyObservers(this);
  16922. this.onDisposeObservable.clear();
  16923. this.onBeforeRenderObservable.clear();
  16924. this.onAfterRenderObservable.clear();
  16925. this.detachControl();
  16926. // Release sounds & sounds tracks
  16927. if (BABYLON.AudioEngine) {
  16928. this.disposeSounds();
  16929. }
  16930. // Detach cameras
  16931. var canvas = this._engine.getRenderingCanvas();
  16932. var index;
  16933. for (index = 0; index < this.cameras.length; index++) {
  16934. this.cameras[index].detachControl(canvas);
  16935. }
  16936. // Release lights
  16937. while (this.lights.length) {
  16938. this.lights[0].dispose();
  16939. }
  16940. // Release meshes
  16941. while (this.meshes.length) {
  16942. this.meshes[0].dispose(true);
  16943. }
  16944. // Release cameras
  16945. while (this.cameras.length) {
  16946. this.cameras[0].dispose();
  16947. }
  16948. // Release materials
  16949. while (this.materials.length) {
  16950. this.materials[0].dispose();
  16951. }
  16952. // Release particles
  16953. while (this.particleSystems.length) {
  16954. this.particleSystems[0].dispose();
  16955. }
  16956. // Release sprites
  16957. while (this.spriteManagers.length) {
  16958. this.spriteManagers[0].dispose();
  16959. }
  16960. // Release layers
  16961. while (this.layers.length) {
  16962. this.layers[0].dispose();
  16963. }
  16964. // Release textures
  16965. while (this.textures.length) {
  16966. this.textures[0].dispose();
  16967. }
  16968. // Post-processes
  16969. this.postProcessManager.dispose();
  16970. // Physics
  16971. if (this._physicsEngine) {
  16972. this.disablePhysicsEngine();
  16973. }
  16974. // Remove from engine
  16975. index = this._engine.scenes.indexOf(this);
  16976. if (index > -1) {
  16977. this._engine.scenes.splice(index, 1);
  16978. }
  16979. this._engine.wipeCaches();
  16980. };
  16981. // Release sounds & sounds tracks
  16982. Scene.prototype.disposeSounds = function () {
  16983. this.mainSoundTrack.dispose();
  16984. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16985. this.soundTracks[scIndex].dispose();
  16986. }
  16987. };
  16988. // Octrees
  16989. Scene.prototype.getWorldExtends = function () {
  16990. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16991. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16992. for (var index = 0; index < this.meshes.length; index++) {
  16993. var mesh = this.meshes[index];
  16994. mesh.computeWorldMatrix(true);
  16995. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16996. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16997. BABYLON.Tools.CheckExtends(minBox, min, max);
  16998. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16999. }
  17000. return {
  17001. min: min,
  17002. max: max
  17003. };
  17004. };
  17005. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17006. if (maxCapacity === void 0) { maxCapacity = 64; }
  17007. if (maxDepth === void 0) { maxDepth = 2; }
  17008. if (!this._selectionOctree) {
  17009. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17010. }
  17011. var worldExtends = this.getWorldExtends();
  17012. // Update octree
  17013. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17014. return this._selectionOctree;
  17015. };
  17016. // Picking
  17017. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17018. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17019. var engine = this._engine;
  17020. if (!camera) {
  17021. if (!this.activeCamera)
  17022. throw new Error("Active camera not set");
  17023. camera = this.activeCamera;
  17024. }
  17025. var cameraViewport = camera.viewport;
  17026. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17027. // Moving coordinates to local viewport world
  17028. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17029. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17030. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17031. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17032. };
  17033. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17034. var engine = this._engine;
  17035. if (!camera) {
  17036. if (!this.activeCamera)
  17037. throw new Error("Active camera not set");
  17038. camera = this.activeCamera;
  17039. }
  17040. var cameraViewport = camera.viewport;
  17041. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17042. var identity = BABYLON.Matrix.Identity();
  17043. // Moving coordinates to local viewport world
  17044. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17045. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17046. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17047. };
  17048. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17049. var pickingInfo = null;
  17050. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17051. var mesh = this.meshes[meshIndex];
  17052. if (predicate) {
  17053. if (!predicate(mesh)) {
  17054. continue;
  17055. }
  17056. }
  17057. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17058. continue;
  17059. }
  17060. var world = mesh.getWorldMatrix();
  17061. var ray = rayFunction(world);
  17062. var result = mesh.intersects(ray, fastCheck);
  17063. if (!result || !result.hit)
  17064. continue;
  17065. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17066. continue;
  17067. pickingInfo = result;
  17068. if (fastCheck) {
  17069. break;
  17070. }
  17071. }
  17072. return pickingInfo || new BABYLON.PickingInfo();
  17073. };
  17074. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17075. var pickingInfo = null;
  17076. camera = camera || this.activeCamera;
  17077. if (this.spriteManagers.length > 0) {
  17078. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17079. var spriteManager = this.spriteManagers[spriteIndex];
  17080. if (!spriteManager.isPickable) {
  17081. continue;
  17082. }
  17083. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17084. if (!result || !result.hit)
  17085. continue;
  17086. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17087. continue;
  17088. pickingInfo = result;
  17089. if (fastCheck) {
  17090. break;
  17091. }
  17092. }
  17093. }
  17094. return pickingInfo || new BABYLON.PickingInfo();
  17095. };
  17096. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17097. var _this = this;
  17098. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17099. /// <param name="x">X position on screen</param>
  17100. /// <param name="y">Y position on screen</param>
  17101. /// <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>
  17102. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17103. /// <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>
  17104. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17105. };
  17106. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17107. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17108. /// <param name="x">X position on screen</param>
  17109. /// <param name="y">Y position on screen</param>
  17110. /// <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>
  17111. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17112. /// <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>
  17113. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17114. };
  17115. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17116. var _this = this;
  17117. return this._internalPick(function (world) {
  17118. if (!_this._pickWithRayInverseMatrix) {
  17119. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17120. }
  17121. world.invertToRef(_this._pickWithRayInverseMatrix);
  17122. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17123. }, predicate, fastCheck);
  17124. };
  17125. Scene.prototype.setPointerOverMesh = function (mesh) {
  17126. if (this._pointerOverMesh === mesh) {
  17127. return;
  17128. }
  17129. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17130. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17131. }
  17132. this._pointerOverMesh = mesh;
  17133. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17134. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17135. }
  17136. };
  17137. Scene.prototype.getPointerOverMesh = function () {
  17138. return this._pointerOverMesh;
  17139. };
  17140. Scene.prototype.setPointerOverSprite = function (sprite) {
  17141. if (this._pointerOverSprite === sprite) {
  17142. return;
  17143. }
  17144. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17145. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17146. }
  17147. this._pointerOverSprite = sprite;
  17148. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17149. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17150. }
  17151. };
  17152. Scene.prototype.getPointerOverSprite = function () {
  17153. return this._pointerOverSprite;
  17154. };
  17155. // Physics
  17156. Scene.prototype.getPhysicsEngine = function () {
  17157. return this._physicsEngine;
  17158. };
  17159. /**
  17160. * Enables physics to the current scene
  17161. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17162. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17163. * @return {boolean} was the physics engine initialized
  17164. */
  17165. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17166. if (this._physicsEngine) {
  17167. return true;
  17168. }
  17169. try {
  17170. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17171. return true;
  17172. }
  17173. catch (e) {
  17174. BABYLON.Tools.Error(e.message);
  17175. return false;
  17176. }
  17177. };
  17178. Scene.prototype.disablePhysicsEngine = function () {
  17179. if (!this._physicsEngine) {
  17180. return;
  17181. }
  17182. this._physicsEngine.dispose();
  17183. this._physicsEngine = undefined;
  17184. };
  17185. Scene.prototype.isPhysicsEnabled = function () {
  17186. return this._physicsEngine !== undefined;
  17187. };
  17188. /**
  17189. *
  17190. * Sets the gravity of the physics engine (and NOT of the scene)
  17191. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17192. */
  17193. Scene.prototype.setGravity = function (gravity) {
  17194. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17195. if (!this._physicsEngine) {
  17196. return;
  17197. }
  17198. this._physicsEngine.setGravity(gravity);
  17199. };
  17200. /**
  17201. * Legacy support, using the new API
  17202. * @Deprecated
  17203. */
  17204. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17205. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17206. if (parts.parts) {
  17207. options = parts;
  17208. parts = parts.parts;
  17209. }
  17210. var mainMesh = parts[0].mesh;
  17211. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17212. for (var index = 1; index < parts.length; index++) {
  17213. var mesh = parts[index].mesh;
  17214. if (mesh.parent !== mainMesh) {
  17215. mesh.position = mesh.position.subtract(mainMesh.position);
  17216. mesh.parent = mainMesh;
  17217. }
  17218. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17219. }
  17220. mainMesh.physicsImpostor.forceUpdate();
  17221. };
  17222. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17223. var mesh = compound.parts[0].mesh;
  17224. mesh.physicsImpostor.dispose();
  17225. mesh.physicsImpostor = null;
  17226. };
  17227. // Misc.
  17228. Scene.prototype.createDefaultCameraOrLight = function () {
  17229. // Light
  17230. if (this.lights.length === 0) {
  17231. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17232. }
  17233. // Camera
  17234. if (!this.activeCamera) {
  17235. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17236. // Compute position
  17237. var worldExtends = this.getWorldExtends();
  17238. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17239. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17240. camera.setTarget(worldCenter);
  17241. this.activeCamera = camera;
  17242. }
  17243. };
  17244. // Tags
  17245. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17246. if (tagsQuery === undefined) {
  17247. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17248. return list;
  17249. }
  17250. var listByTags = [];
  17251. forEach = forEach || (function (item) { return; });
  17252. for (var i in list) {
  17253. var item = list[i];
  17254. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17255. listByTags.push(item);
  17256. forEach(item);
  17257. }
  17258. }
  17259. return listByTags;
  17260. };
  17261. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17262. return this._getByTags(this.meshes, tagsQuery, forEach);
  17263. };
  17264. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17265. return this._getByTags(this.cameras, tagsQuery, forEach);
  17266. };
  17267. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17268. return this._getByTags(this.lights, tagsQuery, forEach);
  17269. };
  17270. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17271. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17272. };
  17273. // Statics
  17274. Scene._FOGMODE_NONE = 0;
  17275. Scene._FOGMODE_EXP = 1;
  17276. Scene._FOGMODE_EXP2 = 2;
  17277. Scene._FOGMODE_LINEAR = 3;
  17278. Scene.MinDeltaTime = 1.0;
  17279. Scene.MaxDeltaTime = 1000.0;
  17280. return Scene;
  17281. })();
  17282. BABYLON.Scene = Scene;
  17283. })(BABYLON || (BABYLON = {}));
  17284. var BABYLON;
  17285. (function (BABYLON) {
  17286. var Buffer = (function () {
  17287. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17288. if (engine instanceof BABYLON.Mesh) {
  17289. this._engine = engine.getScene().getEngine();
  17290. }
  17291. else {
  17292. this._engine = engine;
  17293. }
  17294. this._updatable = updatable;
  17295. this._data = data;
  17296. this._strideSize = stride;
  17297. if (!postponeInternalCreation) {
  17298. this.create();
  17299. }
  17300. this._instanced = instanced;
  17301. }
  17302. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17303. // a lot of these parameters are ignored as they are overriden by the buffer
  17304. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17305. };
  17306. // Properties
  17307. Buffer.prototype.isUpdatable = function () {
  17308. return this._updatable;
  17309. };
  17310. Buffer.prototype.getData = function () {
  17311. return this._data;
  17312. };
  17313. Buffer.prototype.getBuffer = function () {
  17314. return this._buffer;
  17315. };
  17316. Buffer.prototype.getStrideSize = function () {
  17317. return this._strideSize;
  17318. };
  17319. Buffer.prototype.getIsInstanced = function () {
  17320. return this._instanced;
  17321. };
  17322. // Methods
  17323. Buffer.prototype.create = function (data) {
  17324. if (!data && this._buffer) {
  17325. return; // nothing to do
  17326. }
  17327. data = data || this._data;
  17328. if (!this._buffer) {
  17329. if (this._updatable) {
  17330. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17331. this._data = data;
  17332. }
  17333. else {
  17334. this._buffer = this._engine.createVertexBuffer(data);
  17335. }
  17336. }
  17337. else if (this._updatable) {
  17338. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17339. this._data = data;
  17340. }
  17341. };
  17342. Buffer.prototype.update = function (data) {
  17343. this.create(data);
  17344. };
  17345. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17346. if (!this._buffer) {
  17347. return;
  17348. }
  17349. if (this._updatable) {
  17350. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17351. this._data = null;
  17352. }
  17353. };
  17354. Buffer.prototype.dispose = function () {
  17355. if (!this._buffer) {
  17356. return;
  17357. }
  17358. if (this._engine._releaseBuffer(this._buffer)) {
  17359. this._buffer = null;
  17360. }
  17361. };
  17362. return Buffer;
  17363. })();
  17364. BABYLON.Buffer = Buffer;
  17365. })(BABYLON || (BABYLON = {}));
  17366. var BABYLON;
  17367. (function (BABYLON) {
  17368. var VertexBuffer = (function () {
  17369. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17370. if (!stride) {
  17371. // Deduce stride from kind
  17372. switch (kind) {
  17373. case VertexBuffer.PositionKind:
  17374. stride = 3;
  17375. break;
  17376. case VertexBuffer.NormalKind:
  17377. stride = 3;
  17378. break;
  17379. case VertexBuffer.UVKind:
  17380. case VertexBuffer.UV2Kind:
  17381. case VertexBuffer.UV3Kind:
  17382. case VertexBuffer.UV4Kind:
  17383. case VertexBuffer.UV5Kind:
  17384. case VertexBuffer.UV6Kind:
  17385. stride = 2;
  17386. break;
  17387. case VertexBuffer.ColorKind:
  17388. stride = 4;
  17389. break;
  17390. case VertexBuffer.MatricesIndicesKind:
  17391. case VertexBuffer.MatricesIndicesExtraKind:
  17392. stride = 4;
  17393. break;
  17394. case VertexBuffer.MatricesWeightsKind:
  17395. case VertexBuffer.MatricesWeightsExtraKind:
  17396. stride = 4;
  17397. break;
  17398. }
  17399. }
  17400. if (data instanceof BABYLON.Buffer) {
  17401. if (!stride) {
  17402. stride = data.getStrideSize();
  17403. }
  17404. this._buffer = data;
  17405. this._ownsBuffer = false;
  17406. }
  17407. else {
  17408. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17409. this._ownsBuffer = true;
  17410. }
  17411. this._stride = stride;
  17412. this._offset = offset ? offset : 0;
  17413. this._size = size ? size : stride;
  17414. this._kind = kind;
  17415. }
  17416. VertexBuffer.prototype.getKind = function () {
  17417. return this._kind;
  17418. };
  17419. // Properties
  17420. VertexBuffer.prototype.isUpdatable = function () {
  17421. return this._buffer.isUpdatable();
  17422. };
  17423. VertexBuffer.prototype.getData = function () {
  17424. return this._buffer.getData();
  17425. };
  17426. VertexBuffer.prototype.getBuffer = function () {
  17427. return this._buffer.getBuffer();
  17428. };
  17429. VertexBuffer.prototype.getStrideSize = function () {
  17430. return this._stride;
  17431. };
  17432. VertexBuffer.prototype.getOffset = function () {
  17433. return this._offset;
  17434. };
  17435. VertexBuffer.prototype.getSize = function () {
  17436. return this._size;
  17437. };
  17438. VertexBuffer.prototype.getIsInstanced = function () {
  17439. return this._buffer.getIsInstanced();
  17440. };
  17441. // Methods
  17442. VertexBuffer.prototype.create = function (data) {
  17443. return this._buffer.create(data);
  17444. };
  17445. VertexBuffer.prototype.update = function (data) {
  17446. return this._buffer.update(data);
  17447. };
  17448. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17449. return this._buffer.updateDirectly(data, offset);
  17450. };
  17451. VertexBuffer.prototype.dispose = function () {
  17452. if (this._ownsBuffer) {
  17453. this._buffer.dispose();
  17454. }
  17455. };
  17456. Object.defineProperty(VertexBuffer, "PositionKind", {
  17457. get: function () {
  17458. return VertexBuffer._PositionKind;
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Object.defineProperty(VertexBuffer, "NormalKind", {
  17464. get: function () {
  17465. return VertexBuffer._NormalKind;
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. Object.defineProperty(VertexBuffer, "UVKind", {
  17471. get: function () {
  17472. return VertexBuffer._UVKind;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17478. get: function () {
  17479. return VertexBuffer._UV2Kind;
  17480. },
  17481. enumerable: true,
  17482. configurable: true
  17483. });
  17484. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17485. get: function () {
  17486. return VertexBuffer._UV3Kind;
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17492. get: function () {
  17493. return VertexBuffer._UV4Kind;
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17499. get: function () {
  17500. return VertexBuffer._UV5Kind;
  17501. },
  17502. enumerable: true,
  17503. configurable: true
  17504. });
  17505. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17506. get: function () {
  17507. return VertexBuffer._UV6Kind;
  17508. },
  17509. enumerable: true,
  17510. configurable: true
  17511. });
  17512. Object.defineProperty(VertexBuffer, "ColorKind", {
  17513. get: function () {
  17514. return VertexBuffer._ColorKind;
  17515. },
  17516. enumerable: true,
  17517. configurable: true
  17518. });
  17519. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17520. get: function () {
  17521. return VertexBuffer._MatricesIndicesKind;
  17522. },
  17523. enumerable: true,
  17524. configurable: true
  17525. });
  17526. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17527. get: function () {
  17528. return VertexBuffer._MatricesWeightsKind;
  17529. },
  17530. enumerable: true,
  17531. configurable: true
  17532. });
  17533. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17534. get: function () {
  17535. return VertexBuffer._MatricesIndicesExtraKind;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17541. get: function () {
  17542. return VertexBuffer._MatricesWeightsExtraKind;
  17543. },
  17544. enumerable: true,
  17545. configurable: true
  17546. });
  17547. // Enums
  17548. VertexBuffer._PositionKind = "position";
  17549. VertexBuffer._NormalKind = "normal";
  17550. VertexBuffer._UVKind = "uv";
  17551. VertexBuffer._UV2Kind = "uv2";
  17552. VertexBuffer._UV3Kind = "uv3";
  17553. VertexBuffer._UV4Kind = "uv4";
  17554. VertexBuffer._UV5Kind = "uv5";
  17555. VertexBuffer._UV6Kind = "uv6";
  17556. VertexBuffer._ColorKind = "color";
  17557. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17558. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17559. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17560. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17561. return VertexBuffer;
  17562. })();
  17563. BABYLON.VertexBuffer = VertexBuffer;
  17564. })(BABYLON || (BABYLON = {}));
  17565. var BABYLON;
  17566. (function (BABYLON) {
  17567. /**
  17568. * Creates an instance based on a source mesh.
  17569. */
  17570. var InstancedMesh = (function (_super) {
  17571. __extends(InstancedMesh, _super);
  17572. function InstancedMesh(name, source) {
  17573. _super.call(this, name, source.getScene());
  17574. source.instances.push(this);
  17575. this._sourceMesh = source;
  17576. this.position.copyFrom(source.position);
  17577. this.rotation.copyFrom(source.rotation);
  17578. this.scaling.copyFrom(source.scaling);
  17579. if (source.rotationQuaternion) {
  17580. this.rotationQuaternion = source.rotationQuaternion.clone();
  17581. }
  17582. this.infiniteDistance = source.infiniteDistance;
  17583. this.setPivotMatrix(source.getPivotMatrix());
  17584. this.refreshBoundingInfo();
  17585. this._syncSubMeshes();
  17586. }
  17587. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17588. // Methods
  17589. get: function () {
  17590. return this._sourceMesh.receiveShadows;
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. Object.defineProperty(InstancedMesh.prototype, "material", {
  17596. get: function () {
  17597. return this._sourceMesh.material;
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17603. get: function () {
  17604. return this._sourceMesh.visibility;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17610. get: function () {
  17611. return this._sourceMesh.skeleton;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17617. get: function () {
  17618. return this._sourceMesh.renderingGroupId;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. InstancedMesh.prototype.getTotalVertices = function () {
  17624. return this._sourceMesh.getTotalVertices();
  17625. };
  17626. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17627. get: function () {
  17628. return this._sourceMesh;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17634. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17635. };
  17636. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17637. return this._sourceMesh.isVerticesDataPresent(kind);
  17638. };
  17639. InstancedMesh.prototype.getIndices = function () {
  17640. return this._sourceMesh.getIndices();
  17641. };
  17642. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17643. get: function () {
  17644. return this._sourceMesh._positions;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17650. var meshBB = this._sourceMesh.getBoundingInfo();
  17651. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17652. this._updateBoundingInfo();
  17653. };
  17654. InstancedMesh.prototype._preActivate = function () {
  17655. if (this._currentLOD) {
  17656. this._currentLOD._preActivate();
  17657. }
  17658. };
  17659. InstancedMesh.prototype._activate = function (renderId) {
  17660. if (this._currentLOD) {
  17661. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17662. }
  17663. };
  17664. InstancedMesh.prototype.getLOD = function (camera) {
  17665. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17666. if (this._currentLOD === this.sourceMesh) {
  17667. return this;
  17668. }
  17669. return this._currentLOD;
  17670. };
  17671. InstancedMesh.prototype._syncSubMeshes = function () {
  17672. this.releaseSubMeshes();
  17673. if (this._sourceMesh.subMeshes) {
  17674. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17675. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17676. }
  17677. }
  17678. };
  17679. InstancedMesh.prototype._generatePointsArray = function () {
  17680. return this._sourceMesh._generatePointsArray();
  17681. };
  17682. // Clone
  17683. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17684. var result = this._sourceMesh.createInstance(name);
  17685. // Deep copy
  17686. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17687. // Bounding info
  17688. this.refreshBoundingInfo();
  17689. // Parent
  17690. if (newParent) {
  17691. result.parent = newParent;
  17692. }
  17693. if (!doNotCloneChildren) {
  17694. // Children
  17695. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17696. var mesh = this.getScene().meshes[index];
  17697. if (mesh.parent === this) {
  17698. mesh.clone(mesh.name, result);
  17699. }
  17700. }
  17701. }
  17702. result.computeWorldMatrix(true);
  17703. return result;
  17704. };
  17705. // Dispoe
  17706. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17707. // Remove from mesh
  17708. var index = this._sourceMesh.instances.indexOf(this);
  17709. this._sourceMesh.instances.splice(index, 1);
  17710. _super.prototype.dispose.call(this, doNotRecurse);
  17711. };
  17712. return InstancedMesh;
  17713. })(BABYLON.AbstractMesh);
  17714. BABYLON.InstancedMesh = InstancedMesh;
  17715. })(BABYLON || (BABYLON = {}));
  17716. var BABYLON;
  17717. (function (BABYLON) {
  17718. var _InstancesBatch = (function () {
  17719. function _InstancesBatch() {
  17720. this.mustReturn = false;
  17721. this.visibleInstances = new Array();
  17722. this.renderSelf = new Array();
  17723. }
  17724. return _InstancesBatch;
  17725. })();
  17726. BABYLON._InstancesBatch = _InstancesBatch;
  17727. var Mesh = (function (_super) {
  17728. __extends(Mesh, _super);
  17729. /**
  17730. * @constructor
  17731. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17732. * @param {Scene} scene The scene to add this mesh to.
  17733. * @param {Node} parent The parent of this mesh, if it has one
  17734. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17735. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17736. * When false, achieved by calling a clone(), also passing False.
  17737. * This will make creation of children, recursive.
  17738. */
  17739. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17740. if (parent === void 0) { parent = null; }
  17741. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17742. _super.call(this, name, scene);
  17743. // Events
  17744. /**
  17745. * An event triggered before rendering the mesh
  17746. * @type {BABYLON.Observable}
  17747. */
  17748. this.onBeforeRenderObservable = new BABYLON.Observable();
  17749. /**
  17750. * An event triggered after rendering the mesh
  17751. * @type {BABYLON.Observable}
  17752. */
  17753. this.onAfterRenderObservable = new BABYLON.Observable();
  17754. /**
  17755. * An event triggered before drawing the mesh
  17756. * @type {BABYLON.Observable}
  17757. */
  17758. this.onBeforeDrawObservable = new BABYLON.Observable();
  17759. // Members
  17760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17761. this.instances = new Array();
  17762. this._LODLevels = new Array();
  17763. this._visibleInstances = {};
  17764. this._renderIdForInstances = new Array();
  17765. this._batchCache = new _InstancesBatch();
  17766. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17767. this._sideOrientation = Mesh._DEFAULTSIDE;
  17768. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17769. if (source) {
  17770. // Geometry
  17771. if (source._geometry) {
  17772. source._geometry.applyToMesh(this);
  17773. }
  17774. // Deep copy
  17775. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17776. // Pivot
  17777. this.setPivotMatrix(source.getPivotMatrix());
  17778. this.id = name + "." + source.id;
  17779. // Material
  17780. this.material = source.material;
  17781. var index;
  17782. if (!doNotCloneChildren) {
  17783. // Children
  17784. for (index = 0; index < scene.meshes.length; index++) {
  17785. var mesh = scene.meshes[index];
  17786. if (mesh.parent === source) {
  17787. // doNotCloneChildren is always going to be False
  17788. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17789. }
  17790. }
  17791. }
  17792. // Physics clone
  17793. var physicsEngine = this.getScene().getPhysicsEngine();
  17794. if (clonePhysicsImpostor && physicsEngine) {
  17795. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17796. if (impostor) {
  17797. this.physicsImpostor = impostor.clone(this);
  17798. }
  17799. }
  17800. // Particles
  17801. for (index = 0; index < scene.particleSystems.length; index++) {
  17802. var system = scene.particleSystems[index];
  17803. if (system.emitter === source) {
  17804. system.clone(system.name, this);
  17805. }
  17806. }
  17807. this.computeWorldMatrix(true);
  17808. }
  17809. // Parent
  17810. if (parent !== null) {
  17811. this.parent = parent;
  17812. }
  17813. }
  17814. Object.defineProperty(Mesh, "FRONTSIDE", {
  17815. /**
  17816. * Mesh side orientation : usually the external or front surface
  17817. */
  17818. get: function () {
  17819. return Mesh._FRONTSIDE;
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(Mesh, "BACKSIDE", {
  17825. /**
  17826. * Mesh side orientation : usually the internal or back surface
  17827. */
  17828. get: function () {
  17829. return Mesh._BACKSIDE;
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17835. /**
  17836. * Mesh side orientation : both internal and external or front and back surfaces
  17837. */
  17838. get: function () {
  17839. return Mesh._DOUBLESIDE;
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17845. /**
  17846. * Mesh side orientation : by default, `FRONTSIDE`
  17847. */
  17848. get: function () {
  17849. return Mesh._DEFAULTSIDE;
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. Object.defineProperty(Mesh, "NO_CAP", {
  17855. /**
  17856. * Mesh cap setting : no cap
  17857. */
  17858. get: function () {
  17859. return Mesh._NO_CAP;
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. Object.defineProperty(Mesh, "CAP_START", {
  17865. /**
  17866. * Mesh cap setting : one cap at the beginning of the mesh
  17867. */
  17868. get: function () {
  17869. return Mesh._CAP_START;
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. Object.defineProperty(Mesh, "CAP_END", {
  17875. /**
  17876. * Mesh cap setting : one cap at the end of the mesh
  17877. */
  17878. get: function () {
  17879. return Mesh._CAP_END;
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(Mesh, "CAP_ALL", {
  17885. /**
  17886. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17887. */
  17888. get: function () {
  17889. return Mesh._CAP_ALL;
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17895. set: function (callback) {
  17896. if (this._onBeforeDrawObserver) {
  17897. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17898. }
  17899. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. // Methods
  17905. /**
  17906. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17907. */
  17908. Mesh.prototype.toString = function (fullDetails) {
  17909. var ret = _super.prototype.toString.call(this, fullDetails);
  17910. ret += ", n vertices: " + this.getTotalVertices();
  17911. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17912. if (this.animations) {
  17913. for (var i = 0; i < this.animations.length; i++) {
  17914. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17915. }
  17916. }
  17917. if (fullDetails) {
  17918. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17919. }
  17920. return ret;
  17921. };
  17922. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17923. get: function () {
  17924. return this._LODLevels.length > 0;
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Mesh.prototype._sortLODLevels = function () {
  17930. this._LODLevels.sort(function (a, b) {
  17931. if (a.distance < b.distance) {
  17932. return 1;
  17933. }
  17934. if (a.distance > b.distance) {
  17935. return -1;
  17936. }
  17937. return 0;
  17938. });
  17939. };
  17940. /**
  17941. * Add a mesh as LOD level triggered at the given distance.
  17942. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17943. * @param {number} distance The distance from the center of the object to show this level
  17944. * @param {Mesh} mesh The mesh to be added as LOD level
  17945. * @return {Mesh} This mesh (for chaining)
  17946. */
  17947. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17948. if (mesh && mesh._masterMesh) {
  17949. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17950. return this;
  17951. }
  17952. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17953. this._LODLevels.push(level);
  17954. if (mesh) {
  17955. mesh._masterMesh = this;
  17956. }
  17957. this._sortLODLevels();
  17958. return this;
  17959. };
  17960. /**
  17961. * Returns the LOD level mesh at the passed distance or null if not found.
  17962. * It is related to the method `addLODLevel(distance, mesh)`.
  17963. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17964. */
  17965. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17966. for (var index = 0; index < this._LODLevels.length; index++) {
  17967. var level = this._LODLevels[index];
  17968. if (level.distance === distance) {
  17969. return level.mesh;
  17970. }
  17971. }
  17972. return null;
  17973. };
  17974. /**
  17975. * Remove a mesh from the LOD array
  17976. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17977. * @param {Mesh} mesh The mesh to be removed.
  17978. * @return {Mesh} This mesh (for chaining)
  17979. */
  17980. Mesh.prototype.removeLODLevel = function (mesh) {
  17981. for (var index = 0; index < this._LODLevels.length; index++) {
  17982. if (this._LODLevels[index].mesh === mesh) {
  17983. this._LODLevels.splice(index, 1);
  17984. if (mesh) {
  17985. mesh._masterMesh = null;
  17986. }
  17987. }
  17988. }
  17989. this._sortLODLevels();
  17990. return this;
  17991. };
  17992. /**
  17993. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17994. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17995. */
  17996. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17997. if (!this._LODLevels || this._LODLevels.length === 0) {
  17998. return this;
  17999. }
  18000. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18001. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18002. if (this.onLODLevelSelection) {
  18003. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18004. }
  18005. return this;
  18006. }
  18007. for (var index = 0; index < this._LODLevels.length; index++) {
  18008. var level = this._LODLevels[index];
  18009. if (level.distance < distanceToCamera) {
  18010. if (level.mesh) {
  18011. level.mesh._preActivate();
  18012. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18013. }
  18014. if (this.onLODLevelSelection) {
  18015. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18016. }
  18017. return level.mesh;
  18018. }
  18019. }
  18020. if (this.onLODLevelSelection) {
  18021. this.onLODLevelSelection(distanceToCamera, this, this);
  18022. }
  18023. return this;
  18024. };
  18025. Object.defineProperty(Mesh.prototype, "geometry", {
  18026. /**
  18027. * Returns the mesh internal Geometry object.
  18028. */
  18029. get: function () {
  18030. return this._geometry;
  18031. },
  18032. enumerable: true,
  18033. configurable: true
  18034. });
  18035. /**
  18036. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18037. */
  18038. Mesh.prototype.getTotalVertices = function () {
  18039. if (!this._geometry) {
  18040. return 0;
  18041. }
  18042. return this._geometry.getTotalVertices();
  18043. };
  18044. /**
  18045. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18046. * 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.
  18047. * Returns null if the mesh has no geometry or no vertex buffer.
  18048. * Possible `kind` values :
  18049. * - BABYLON.VertexBuffer.PositionKind
  18050. * - BABYLON.VertexBuffer.UVKind
  18051. * - BABYLON.VertexBuffer.UV2Kind
  18052. * - BABYLON.VertexBuffer.UV3Kind
  18053. * - BABYLON.VertexBuffer.UV4Kind
  18054. * - BABYLON.VertexBuffer.UV5Kind
  18055. * - BABYLON.VertexBuffer.UV6Kind
  18056. * - BABYLON.VertexBuffer.ColorKind
  18057. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18058. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18059. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18060. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18061. */
  18062. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18063. if (!this._geometry) {
  18064. return null;
  18065. }
  18066. return this._geometry.getVerticesData(kind, copyWhenShared);
  18067. };
  18068. /**
  18069. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18070. * Returns `undefined` if the mesh has no geometry.
  18071. * Possible `kind` values :
  18072. * - BABYLON.VertexBuffer.PositionKind
  18073. * - BABYLON.VertexBuffer.UVKind
  18074. * - BABYLON.VertexBuffer.UV2Kind
  18075. * - BABYLON.VertexBuffer.UV3Kind
  18076. * - BABYLON.VertexBuffer.UV4Kind
  18077. * - BABYLON.VertexBuffer.UV5Kind
  18078. * - BABYLON.VertexBuffer.UV6Kind
  18079. * - BABYLON.VertexBuffer.ColorKind
  18080. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18081. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18082. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18083. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18084. */
  18085. Mesh.prototype.getVertexBuffer = function (kind) {
  18086. if (!this._geometry) {
  18087. return undefined;
  18088. }
  18089. return this._geometry.getVertexBuffer(kind);
  18090. };
  18091. /**
  18092. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18093. * Possible `kind` values :
  18094. * - BABYLON.VertexBuffer.PositionKind
  18095. * - BABYLON.VertexBuffer.UVKind
  18096. * - BABYLON.VertexBuffer.UV2Kind
  18097. * - BABYLON.VertexBuffer.UV3Kind
  18098. * - BABYLON.VertexBuffer.UV4Kind
  18099. * - BABYLON.VertexBuffer.UV5Kind
  18100. * - BABYLON.VertexBuffer.UV6Kind
  18101. * - BABYLON.VertexBuffer.ColorKind
  18102. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18103. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18104. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18105. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18106. */
  18107. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18108. if (!this._geometry) {
  18109. if (this._delayInfo) {
  18110. return this._delayInfo.indexOf(kind) !== -1;
  18111. }
  18112. return false;
  18113. }
  18114. return this._geometry.isVerticesDataPresent(kind);
  18115. };
  18116. /**
  18117. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18118. * Possible `kind` values :
  18119. * - BABYLON.VertexBuffer.PositionKind
  18120. * - BABYLON.VertexBuffer.UVKind
  18121. * - BABYLON.VertexBuffer.UV2Kind
  18122. * - BABYLON.VertexBuffer.UV3Kind
  18123. * - BABYLON.VertexBuffer.UV4Kind
  18124. * - BABYLON.VertexBuffer.UV5Kind
  18125. * - BABYLON.VertexBuffer.UV6Kind
  18126. * - BABYLON.VertexBuffer.ColorKind
  18127. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18128. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18129. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18130. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18131. */
  18132. Mesh.prototype.getVerticesDataKinds = function () {
  18133. if (!this._geometry) {
  18134. var result = [];
  18135. if (this._delayInfo) {
  18136. for (var kind in this._delayInfo) {
  18137. result.push(kind);
  18138. }
  18139. }
  18140. return result;
  18141. }
  18142. return this._geometry.getVerticesDataKinds();
  18143. };
  18144. /**
  18145. * Returns a positive integer : the total number of indices in this mesh geometry.
  18146. * Returns zero if the mesh has no geometry.
  18147. */
  18148. Mesh.prototype.getTotalIndices = function () {
  18149. if (!this._geometry) {
  18150. return 0;
  18151. }
  18152. return this._geometry.getTotalIndices();
  18153. };
  18154. /**
  18155. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18156. * 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.
  18157. * Returns an empty array if the mesh has no geometry.
  18158. */
  18159. Mesh.prototype.getIndices = function (copyWhenShared) {
  18160. if (!this._geometry) {
  18161. return [];
  18162. }
  18163. return this._geometry.getIndices(copyWhenShared);
  18164. };
  18165. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18166. get: function () {
  18167. return this._masterMesh !== null && this._masterMesh !== undefined;
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. /**
  18173. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18174. */
  18175. Mesh.prototype.isReady = function () {
  18176. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18177. return false;
  18178. }
  18179. return _super.prototype.isReady.call(this);
  18180. };
  18181. /**
  18182. * Boolean : true if the mesh has been disposed.
  18183. */
  18184. Mesh.prototype.isDisposed = function () {
  18185. return this._isDisposed;
  18186. };
  18187. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18188. get: function () {
  18189. return this._sideOrientation;
  18190. },
  18191. /**
  18192. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18193. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18194. */
  18195. set: function (sideO) {
  18196. this._sideOrientation = sideO;
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18202. /**
  18203. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18204. * This property is pertinent only for updatable parametric shapes.
  18205. */
  18206. get: function () {
  18207. return this._areNormalsFrozen;
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. /**
  18213. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18214. * It has no effect at all on other shapes.
  18215. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18216. */
  18217. Mesh.prototype.freezeNormals = function () {
  18218. this._areNormalsFrozen = true;
  18219. };
  18220. /**
  18221. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18222. * It has no effect at all on other shapes.
  18223. * It reactivates the mesh normals computation if it was previously frozen.
  18224. */
  18225. Mesh.prototype.unfreezeNormals = function () {
  18226. this._areNormalsFrozen = false;
  18227. };
  18228. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18229. /**
  18230. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18231. */
  18232. set: function (count) {
  18233. this._overridenInstanceCount = count;
  18234. },
  18235. enumerable: true,
  18236. configurable: true
  18237. });
  18238. // Methods
  18239. Mesh.prototype._preActivate = function () {
  18240. var sceneRenderId = this.getScene().getRenderId();
  18241. if (this._preActivateId === sceneRenderId) {
  18242. return;
  18243. }
  18244. this._preActivateId = sceneRenderId;
  18245. this._visibleInstances = null;
  18246. };
  18247. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18248. if (this._visibleInstances) {
  18249. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18250. }
  18251. };
  18252. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18253. if (!this._visibleInstances) {
  18254. this._visibleInstances = {};
  18255. this._visibleInstances.defaultRenderId = renderId;
  18256. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18257. }
  18258. if (!this._visibleInstances[renderId]) {
  18259. this._visibleInstances[renderId] = new Array();
  18260. }
  18261. this._visibleInstances[renderId].push(instance);
  18262. };
  18263. /**
  18264. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18265. * This means the mesh underlying bounding box and sphere are recomputed.
  18266. */
  18267. Mesh.prototype.refreshBoundingInfo = function () {
  18268. if (this._boundingInfo.isLocked) {
  18269. return;
  18270. }
  18271. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18272. if (data) {
  18273. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18274. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18275. }
  18276. if (this.subMeshes) {
  18277. for (var index = 0; index < this.subMeshes.length; index++) {
  18278. this.subMeshes[index].refreshBoundingInfo();
  18279. }
  18280. }
  18281. this._updateBoundingInfo();
  18282. };
  18283. Mesh.prototype._createGlobalSubMesh = function () {
  18284. var totalVertices = this.getTotalVertices();
  18285. if (!totalVertices || !this.getIndices()) {
  18286. return null;
  18287. }
  18288. this.releaseSubMeshes();
  18289. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18290. };
  18291. Mesh.prototype.subdivide = function (count) {
  18292. if (count < 1) {
  18293. return;
  18294. }
  18295. var totalIndices = this.getTotalIndices();
  18296. var subdivisionSize = (totalIndices / count) | 0;
  18297. var offset = 0;
  18298. // Ensure that subdivisionSize is a multiple of 3
  18299. while (subdivisionSize % 3 !== 0) {
  18300. subdivisionSize++;
  18301. }
  18302. this.releaseSubMeshes();
  18303. for (var index = 0; index < count; index++) {
  18304. if (offset >= totalIndices) {
  18305. break;
  18306. }
  18307. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18308. offset += subdivisionSize;
  18309. }
  18310. this.synchronizeInstances();
  18311. };
  18312. /**
  18313. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18314. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18315. * The `data` are either a numeric array either a Float32Array.
  18316. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18317. * 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).
  18318. * Note that a new underlying VertexBuffer object is created each call.
  18319. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18320. *
  18321. * Possible `kind` values :
  18322. * - BABYLON.VertexBuffer.PositionKind
  18323. * - BABYLON.VertexBuffer.UVKind
  18324. * - BABYLON.VertexBuffer.UV2Kind
  18325. * - BABYLON.VertexBuffer.UV3Kind
  18326. * - BABYLON.VertexBuffer.UV4Kind
  18327. * - BABYLON.VertexBuffer.UV5Kind
  18328. * - BABYLON.VertexBuffer.UV6Kind
  18329. * - BABYLON.VertexBuffer.ColorKind
  18330. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18331. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18332. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18333. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18334. */
  18335. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18336. if (!this._geometry) {
  18337. var vertexData = new BABYLON.VertexData();
  18338. vertexData.set(data, kind);
  18339. var scene = this.getScene();
  18340. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18341. }
  18342. else {
  18343. this._geometry.setVerticesData(kind, data, updatable, stride);
  18344. }
  18345. };
  18346. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18347. if (!this._geometry) {
  18348. var scene = this.getScene();
  18349. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18350. }
  18351. this._geometry.setVerticesBuffer(buffer);
  18352. };
  18353. /**
  18354. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18355. * If the mesh has no geometry, it is simply returned as it is.
  18356. * The `data` are either a numeric array either a Float32Array.
  18357. * No new underlying VertexBuffer object is created.
  18358. * 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.
  18359. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18360. *
  18361. * Possible `kind` values :
  18362. * - BABYLON.VertexBuffer.PositionKind
  18363. * - BABYLON.VertexBuffer.UVKind
  18364. * - BABYLON.VertexBuffer.UV2Kind
  18365. * - BABYLON.VertexBuffer.UV3Kind
  18366. * - BABYLON.VertexBuffer.UV4Kind
  18367. * - BABYLON.VertexBuffer.UV5Kind
  18368. * - BABYLON.VertexBuffer.UV6Kind
  18369. * - BABYLON.VertexBuffer.ColorKind
  18370. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18371. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18372. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18373. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18374. */
  18375. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18376. if (!this._geometry) {
  18377. return;
  18378. }
  18379. if (!makeItUnique) {
  18380. this._geometry.updateVerticesData(kind, data, updateExtends);
  18381. }
  18382. else {
  18383. this.makeGeometryUnique();
  18384. this.updateVerticesData(kind, data, updateExtends, false);
  18385. }
  18386. };
  18387. /**
  18388. * Deprecated since BabylonJS v2.3
  18389. */
  18390. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18391. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18392. if (!this._geometry) {
  18393. return;
  18394. }
  18395. if (!makeItUnique) {
  18396. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18397. }
  18398. else {
  18399. this.makeGeometryUnique();
  18400. this.updateVerticesDataDirectly(kind, data, offset, false);
  18401. }
  18402. };
  18403. /**
  18404. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18405. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18406. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18407. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18408. */
  18409. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18410. if (computeNormals === void 0) { computeNormals = true; }
  18411. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18412. positionFunction(positions);
  18413. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18414. if (computeNormals) {
  18415. var indices = this.getIndices();
  18416. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18417. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18418. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18419. }
  18420. };
  18421. Mesh.prototype.makeGeometryUnique = function () {
  18422. if (!this._geometry) {
  18423. return;
  18424. }
  18425. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18426. geometry.applyToMesh(this);
  18427. };
  18428. /**
  18429. * Sets the mesh indices.
  18430. * Expects an array populated with integers or a Int32Array.
  18431. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18432. * This method creates a new index buffer each call.
  18433. */
  18434. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18435. if (!this._geometry) {
  18436. var vertexData = new BABYLON.VertexData();
  18437. vertexData.indices = indices;
  18438. var scene = this.getScene();
  18439. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18440. }
  18441. else {
  18442. this._geometry.setIndices(indices, totalVertices);
  18443. }
  18444. };
  18445. /**
  18446. * Invert the geometry to move from a right handed system to a left handed one.
  18447. */
  18448. Mesh.prototype.toLeftHanded = function () {
  18449. if (!this._geometry) {
  18450. return;
  18451. }
  18452. this._geometry.toLeftHanded();
  18453. };
  18454. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18455. var engine = this.getScene().getEngine();
  18456. // Wireframe
  18457. var indexToBind;
  18458. if (this._unIndexed) {
  18459. indexToBind = null;
  18460. }
  18461. else {
  18462. switch (fillMode) {
  18463. case BABYLON.Material.PointFillMode:
  18464. indexToBind = null;
  18465. break;
  18466. case BABYLON.Material.WireFrameFillMode:
  18467. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18468. break;
  18469. default:
  18470. case BABYLON.Material.TriangleFillMode:
  18471. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18472. break;
  18473. }
  18474. }
  18475. // VBOs
  18476. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18477. };
  18478. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18479. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18480. return;
  18481. }
  18482. this.onBeforeDrawObservable.notifyObservers(this);
  18483. var engine = this.getScene().getEngine();
  18484. // Draw order
  18485. switch (fillMode) {
  18486. case BABYLON.Material.PointFillMode:
  18487. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18488. break;
  18489. case BABYLON.Material.WireFrameFillMode:
  18490. if (this._unIndexed) {
  18491. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18492. }
  18493. else {
  18494. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18495. }
  18496. break;
  18497. default:
  18498. if (this._unIndexed) {
  18499. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18500. }
  18501. else {
  18502. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18503. }
  18504. }
  18505. };
  18506. /**
  18507. * Registers for this mesh a javascript function called just before the rendering process.
  18508. * This function is passed the current mesh and doesn't return anything.
  18509. */
  18510. Mesh.prototype.registerBeforeRender = function (func) {
  18511. this.onBeforeRenderObservable.add(func);
  18512. };
  18513. /**
  18514. * Disposes a previously registered javascript function called before the rendering.
  18515. * This function is passed the current mesh and doesn't return anything.
  18516. */
  18517. Mesh.prototype.unregisterBeforeRender = function (func) {
  18518. this.onBeforeRenderObservable.removeCallback(func);
  18519. };
  18520. /**
  18521. * Registers for this mesh a javascript function called just after the rendering is complete.
  18522. * This function is passed the current mesh and doesn't return anything.
  18523. */
  18524. Mesh.prototype.registerAfterRender = function (func) {
  18525. this.onAfterRenderObservable.add(func);
  18526. };
  18527. /**
  18528. * Disposes a previously registered javascript function called after the rendering.
  18529. * This function is passed the current mesh and doesn't return anything.
  18530. */
  18531. Mesh.prototype.unregisterAfterRender = function (func) {
  18532. this.onAfterRenderObservable.removeCallback(func);
  18533. };
  18534. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18535. var scene = this.getScene();
  18536. this._batchCache.mustReturn = false;
  18537. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18538. this._batchCache.visibleInstances[subMeshId] = null;
  18539. if (this._visibleInstances) {
  18540. var currentRenderId = scene.getRenderId();
  18541. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18542. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18543. var selfRenderId = this._renderId;
  18544. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18545. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18546. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18547. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18548. }
  18549. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18550. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18551. this._batchCache.mustReturn = true;
  18552. return this._batchCache;
  18553. }
  18554. if (currentRenderId !== selfRenderId) {
  18555. this._batchCache.renderSelf[subMeshId] = false;
  18556. }
  18557. }
  18558. this._renderIdForInstances[subMeshId] = currentRenderId;
  18559. }
  18560. return this._batchCache;
  18561. };
  18562. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18563. var visibleInstances = batch.visibleInstances[subMesh._id];
  18564. var matricesCount = visibleInstances.length + 1;
  18565. var bufferSize = matricesCount * 16 * 4;
  18566. var currentInstancesBufferSize = this._instancesBufferSize;
  18567. var instancesBuffer = this._instancesBuffer;
  18568. while (this._instancesBufferSize < bufferSize) {
  18569. this._instancesBufferSize *= 2;
  18570. }
  18571. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18572. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18573. }
  18574. var offset = 0;
  18575. var instancesCount = 0;
  18576. var world = this.getWorldMatrix();
  18577. if (batch.renderSelf[subMesh._id]) {
  18578. world.copyToArray(this._instancesData, offset);
  18579. offset += 16;
  18580. instancesCount++;
  18581. }
  18582. if (visibleInstances) {
  18583. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18584. var instance = visibleInstances[instanceIndex];
  18585. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18586. offset += 16;
  18587. instancesCount++;
  18588. }
  18589. }
  18590. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18591. if (instancesBuffer) {
  18592. instancesBuffer.dispose();
  18593. }
  18594. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18595. this._instancesBuffer = instancesBuffer;
  18596. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18597. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18598. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18599. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18600. }
  18601. else {
  18602. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18603. }
  18604. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18605. this._draw(subMesh, fillMode, instancesCount);
  18606. engine.unbindInstanceAttributes();
  18607. };
  18608. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18609. var scene = this.getScene();
  18610. var engine = scene.getEngine();
  18611. if (hardwareInstancedRendering) {
  18612. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18613. }
  18614. else {
  18615. if (batch.renderSelf[subMesh._id]) {
  18616. // Draw
  18617. if (onBeforeDraw) {
  18618. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18619. }
  18620. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18621. }
  18622. if (batch.visibleInstances[subMesh._id]) {
  18623. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18624. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18625. // World
  18626. var world = instance.getWorldMatrix();
  18627. if (onBeforeDraw) {
  18628. onBeforeDraw(true, world, effectiveMaterial);
  18629. }
  18630. // Draw
  18631. this._draw(subMesh, fillMode);
  18632. }
  18633. }
  18634. }
  18635. };
  18636. /**
  18637. * Triggers the draw call for the mesh.
  18638. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18639. */
  18640. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18641. var scene = this.getScene();
  18642. // Managing instances
  18643. var batch = this._getInstancesRenderList(subMesh._id);
  18644. if (batch.mustReturn) {
  18645. return;
  18646. }
  18647. // Checking geometry state
  18648. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18649. return;
  18650. }
  18651. var callbackIndex;
  18652. this.onBeforeRenderObservable.notifyObservers(this);
  18653. var engine = scene.getEngine();
  18654. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18655. // Material
  18656. var effectiveMaterial = subMesh.getMaterial();
  18657. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18658. return;
  18659. }
  18660. // Outline - step 1
  18661. var savedDepthWrite = engine.getDepthWrite();
  18662. if (this.renderOutline) {
  18663. engine.setDepthWrite(false);
  18664. scene.getOutlineRenderer().render(subMesh, batch);
  18665. engine.setDepthWrite(savedDepthWrite);
  18666. }
  18667. effectiveMaterial._preBind();
  18668. var effect = effectiveMaterial.getEffect();
  18669. // Bind
  18670. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18671. this._bind(subMesh, effect, fillMode);
  18672. var world = this.getWorldMatrix();
  18673. effectiveMaterial.bind(world, this);
  18674. // Alpha mode
  18675. if (enableAlphaMode) {
  18676. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18677. }
  18678. // Draw
  18679. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18680. // Unbind
  18681. effectiveMaterial.unbind();
  18682. // Outline - step 2
  18683. if (this.renderOutline && savedDepthWrite) {
  18684. engine.setDepthWrite(true);
  18685. engine.setColorWrite(false);
  18686. scene.getOutlineRenderer().render(subMesh, batch);
  18687. engine.setColorWrite(true);
  18688. }
  18689. // Overlay
  18690. if (this.renderOverlay) {
  18691. var currentMode = engine.getAlphaMode();
  18692. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18693. scene.getOutlineRenderer().render(subMesh, batch, true);
  18694. engine.setAlphaMode(currentMode);
  18695. }
  18696. this.onAfterRenderObservable.notifyObservers(this);
  18697. };
  18698. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18699. if (isInstance) {
  18700. effectiveMaterial.bindOnlyWorldMatrix(world);
  18701. }
  18702. };
  18703. /**
  18704. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18705. */
  18706. Mesh.prototype.getEmittedParticleSystems = function () {
  18707. var results = new Array();
  18708. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18709. var particleSystem = this.getScene().particleSystems[index];
  18710. if (particleSystem.emitter === this) {
  18711. results.push(particleSystem);
  18712. }
  18713. }
  18714. return results;
  18715. };
  18716. /**
  18717. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18718. */
  18719. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18720. var results = new Array();
  18721. var descendants = this.getDescendants();
  18722. descendants.push(this);
  18723. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18724. var particleSystem = this.getScene().particleSystems[index];
  18725. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18726. results.push(particleSystem);
  18727. }
  18728. }
  18729. return results;
  18730. };
  18731. Mesh.prototype._checkDelayState = function () {
  18732. var scene = this.getScene();
  18733. if (this._geometry) {
  18734. this._geometry.load(scene);
  18735. }
  18736. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18738. this._queueLoad(this, scene);
  18739. }
  18740. };
  18741. Mesh.prototype._queueLoad = function (mesh, scene) {
  18742. var _this = this;
  18743. scene._addPendingData(mesh);
  18744. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18745. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18746. if (data instanceof ArrayBuffer) {
  18747. _this._delayLoadingFunction(data, _this);
  18748. }
  18749. else {
  18750. _this._delayLoadingFunction(JSON.parse(data), _this);
  18751. }
  18752. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18753. scene._removePendingData(_this);
  18754. }, function () { }, scene.database, getBinaryData);
  18755. };
  18756. /**
  18757. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18758. */
  18759. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18760. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18761. return false;
  18762. }
  18763. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18764. return false;
  18765. }
  18766. this._checkDelayState();
  18767. return true;
  18768. };
  18769. /**
  18770. * Sets the mesh material by the material or multiMaterial `id` property.
  18771. * The material `id` is a string identifying the material or the multiMaterial.
  18772. * This method returns nothing.
  18773. */
  18774. Mesh.prototype.setMaterialByID = function (id) {
  18775. var materials = this.getScene().materials;
  18776. var index;
  18777. for (index = 0; index < materials.length; index++) {
  18778. if (materials[index].id === id) {
  18779. this.material = materials[index];
  18780. return;
  18781. }
  18782. }
  18783. // Multi
  18784. var multiMaterials = this.getScene().multiMaterials;
  18785. for (index = 0; index < multiMaterials.length; index++) {
  18786. if (multiMaterials[index].id === id) {
  18787. this.material = multiMaterials[index];
  18788. return;
  18789. }
  18790. }
  18791. };
  18792. /**
  18793. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18794. */
  18795. Mesh.prototype.getAnimatables = function () {
  18796. var results = [];
  18797. if (this.material) {
  18798. results.push(this.material);
  18799. }
  18800. if (this.skeleton) {
  18801. results.push(this.skeleton);
  18802. }
  18803. return results;
  18804. };
  18805. /**
  18806. * Modifies the mesh geometry according to the passed transformation matrix.
  18807. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18808. * The mesh normals are modified accordingly the same transformation.
  18809. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18810. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18811. */
  18812. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18813. // Position
  18814. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18815. return;
  18816. }
  18817. var submeshes = this.subMeshes.splice(0);
  18818. this._resetPointsArrayCache();
  18819. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18820. var temp = [];
  18821. var index;
  18822. for (index = 0; index < data.length; index += 3) {
  18823. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18824. }
  18825. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18826. // Normals
  18827. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18828. return;
  18829. }
  18830. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18831. temp = [];
  18832. for (index = 0; index < data.length; index += 3) {
  18833. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18834. }
  18835. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18836. // flip faces?
  18837. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18838. this.flipFaces();
  18839. }
  18840. // Restore submeshes
  18841. this.releaseSubMeshes();
  18842. this.subMeshes = submeshes;
  18843. };
  18844. /**
  18845. * Modifies the mesh geometry according to its own current World Matrix.
  18846. * The mesh World Matrix is then reset.
  18847. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18848. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18849. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18850. */
  18851. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18852. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18853. this.scaling.copyFromFloats(1, 1, 1);
  18854. this.position.copyFromFloats(0, 0, 0);
  18855. this.rotation.copyFromFloats(0, 0, 0);
  18856. //only if quaternion is already set
  18857. if (this.rotationQuaternion) {
  18858. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18859. }
  18860. this._worldMatrix = BABYLON.Matrix.Identity();
  18861. };
  18862. // Cache
  18863. Mesh.prototype._resetPointsArrayCache = function () {
  18864. this._positions = null;
  18865. };
  18866. Mesh.prototype._generatePointsArray = function () {
  18867. if (this._positions)
  18868. return true;
  18869. this._positions = [];
  18870. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18871. if (!data) {
  18872. return false;
  18873. }
  18874. for (var index = 0; index < data.length; index += 3) {
  18875. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18876. }
  18877. return true;
  18878. };
  18879. /**
  18880. * Returns a new Mesh object generated from the current mesh properties.
  18881. * This method must not get confused with createInstance().
  18882. * The parameter `name` is a string, the name given to the new mesh.
  18883. * The optional parameter `newParent` can be any Node object (default `null`).
  18884. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18885. * 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.
  18886. */
  18887. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18888. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18889. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18890. };
  18891. /**
  18892. * Disposes the mesh.
  18893. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18894. */
  18895. Mesh.prototype.dispose = function (doNotRecurse) {
  18896. if (this._geometry) {
  18897. this._geometry.releaseForMesh(this, true);
  18898. }
  18899. // Instances
  18900. if (this._instancesBuffer) {
  18901. this._instancesBuffer.dispose();
  18902. this._instancesBuffer = null;
  18903. }
  18904. while (this.instances.length) {
  18905. this.instances[0].dispose();
  18906. }
  18907. _super.prototype.dispose.call(this, doNotRecurse);
  18908. };
  18909. /**
  18910. * Modifies the mesh geometry according to a displacement map.
  18911. * 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.
  18912. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18913. * This method returns nothing.
  18914. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18915. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18916. * 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.
  18917. */
  18918. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18919. var _this = this;
  18920. var scene = this.getScene();
  18921. var onload = function (img) {
  18922. // Getting height map data
  18923. var canvas = document.createElement("canvas");
  18924. var context = canvas.getContext("2d");
  18925. var heightMapWidth = img.width;
  18926. var heightMapHeight = img.height;
  18927. canvas.width = heightMapWidth;
  18928. canvas.height = heightMapHeight;
  18929. context.drawImage(img, 0, 0);
  18930. // Create VertexData from map data
  18931. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18932. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18933. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18934. //execute success callback, if set
  18935. if (onSuccess) {
  18936. onSuccess(_this);
  18937. }
  18938. };
  18939. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18940. };
  18941. /**
  18942. * Modifies the mesh geometry according to a displacementMap buffer.
  18943. * 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.
  18944. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18945. * This method returns nothing.
  18946. * 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.
  18947. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18948. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18949. */
  18950. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18951. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18952. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18953. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18954. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18955. return;
  18956. }
  18957. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18958. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18959. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18960. var position = BABYLON.Vector3.Zero();
  18961. var normal = BABYLON.Vector3.Zero();
  18962. var uv = BABYLON.Vector2.Zero();
  18963. for (var index = 0; index < positions.length; index += 3) {
  18964. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18965. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18966. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18967. // Compute height
  18968. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18969. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18970. var pos = (u + v * heightMapWidth) * 4;
  18971. var r = buffer[pos] / 255.0;
  18972. var g = buffer[pos + 1] / 255.0;
  18973. var b = buffer[pos + 2] / 255.0;
  18974. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18975. normal.normalize();
  18976. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18977. position = position.add(normal);
  18978. position.toArray(positions, index);
  18979. }
  18980. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18981. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18982. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18983. };
  18984. /**
  18985. * Modify the mesh to get a flat shading rendering.
  18986. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18987. * This method returns nothing.
  18988. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18989. */
  18990. Mesh.prototype.convertToFlatShadedMesh = function () {
  18991. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18992. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18993. var kinds = this.getVerticesDataKinds();
  18994. var vbs = [];
  18995. var data = [];
  18996. var newdata = [];
  18997. var updatableNormals = false;
  18998. var kindIndex;
  18999. var kind;
  19000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19001. kind = kinds[kindIndex];
  19002. var vertexBuffer = this.getVertexBuffer(kind);
  19003. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19004. updatableNormals = vertexBuffer.isUpdatable();
  19005. kinds.splice(kindIndex, 1);
  19006. kindIndex--;
  19007. continue;
  19008. }
  19009. vbs[kind] = vertexBuffer;
  19010. data[kind] = vbs[kind].getData();
  19011. newdata[kind] = [];
  19012. }
  19013. // Save previous submeshes
  19014. var previousSubmeshes = this.subMeshes.slice(0);
  19015. var indices = this.getIndices();
  19016. var totalIndices = this.getTotalIndices();
  19017. // Generating unique vertices per face
  19018. var index;
  19019. for (index = 0; index < totalIndices; index++) {
  19020. var vertexIndex = indices[index];
  19021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19022. kind = kinds[kindIndex];
  19023. var stride = vbs[kind].getStrideSize();
  19024. for (var offset = 0; offset < stride; offset++) {
  19025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19026. }
  19027. }
  19028. }
  19029. // Updating faces & normal
  19030. var normals = [];
  19031. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19032. for (index = 0; index < totalIndices; index += 3) {
  19033. indices[index] = index;
  19034. indices[index + 1] = index + 1;
  19035. indices[index + 2] = index + 2;
  19036. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19037. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19038. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19039. var p1p2 = p1.subtract(p2);
  19040. var p3p2 = p3.subtract(p2);
  19041. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19042. // Store same normals for every vertex
  19043. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19044. normals.push(normal.x);
  19045. normals.push(normal.y);
  19046. normals.push(normal.z);
  19047. }
  19048. }
  19049. this.setIndices(indices);
  19050. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19051. // Updating vertex buffers
  19052. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19053. kind = kinds[kindIndex];
  19054. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19055. }
  19056. // Updating submeshes
  19057. this.releaseSubMeshes();
  19058. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19059. var previousOne = previousSubmeshes[submeshIndex];
  19060. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19061. }
  19062. this.synchronizeInstances();
  19063. };
  19064. /**
  19065. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19066. * In other words, more vertices, no more indices and a single bigger VBO.
  19067. * This method returns nothing.
  19068. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19069. *
  19070. */
  19071. Mesh.prototype.convertToUnIndexedMesh = function () {
  19072. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19073. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19074. var kinds = this.getVerticesDataKinds();
  19075. var vbs = [];
  19076. var data = [];
  19077. var newdata = [];
  19078. var updatableNormals = false;
  19079. var kindIndex;
  19080. var kind;
  19081. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19082. kind = kinds[kindIndex];
  19083. var vertexBuffer = this.getVertexBuffer(kind);
  19084. vbs[kind] = vertexBuffer;
  19085. data[kind] = vbs[kind].getData();
  19086. newdata[kind] = [];
  19087. }
  19088. // Save previous submeshes
  19089. var previousSubmeshes = this.subMeshes.slice(0);
  19090. var indices = this.getIndices();
  19091. var totalIndices = this.getTotalIndices();
  19092. // Generating unique vertices per face
  19093. var index;
  19094. for (index = 0; index < totalIndices; index++) {
  19095. var vertexIndex = indices[index];
  19096. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19097. kind = kinds[kindIndex];
  19098. var stride = vbs[kind].getStrideSize();
  19099. for (var offset = 0; offset < stride; offset++) {
  19100. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19101. }
  19102. }
  19103. }
  19104. // Updating indices
  19105. for (index = 0; index < totalIndices; index += 3) {
  19106. indices[index] = index;
  19107. indices[index + 1] = index + 1;
  19108. indices[index + 2] = index + 2;
  19109. }
  19110. this.setIndices(indices);
  19111. // Updating vertex buffers
  19112. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19113. kind = kinds[kindIndex];
  19114. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19115. }
  19116. // Updating submeshes
  19117. this.releaseSubMeshes();
  19118. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19119. var previousOne = previousSubmeshes[submeshIndex];
  19120. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19121. }
  19122. this._unIndexed = true;
  19123. this.synchronizeInstances();
  19124. };
  19125. /**
  19126. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19127. * This method returns nothing.
  19128. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19129. */
  19130. Mesh.prototype.flipFaces = function (flipNormals) {
  19131. if (flipNormals === void 0) { flipNormals = false; }
  19132. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19133. var i;
  19134. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19135. for (i = 0; i < vertex_data.normals.length; i++) {
  19136. vertex_data.normals[i] *= -1;
  19137. }
  19138. }
  19139. var temp;
  19140. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19141. // reassign indices
  19142. temp = vertex_data.indices[i + 1];
  19143. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19144. vertex_data.indices[i + 2] = temp;
  19145. }
  19146. vertex_data.applyToMesh(this);
  19147. };
  19148. // Instances
  19149. /**
  19150. * Creates a new InstancedMesh object from the mesh model.
  19151. * An instance shares the same properties and the same material than its model.
  19152. * Only these properties of each instance can then be set individually :
  19153. * - position
  19154. * - rotation
  19155. * - rotationQuaternion
  19156. * - setPivotMatrix
  19157. * - scaling
  19158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19159. * Warning : this method is not supported for Line mesh and LineSystem
  19160. */
  19161. Mesh.prototype.createInstance = function (name) {
  19162. return new BABYLON.InstancedMesh(name, this);
  19163. };
  19164. /**
  19165. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19166. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19167. * This method returns nothing.
  19168. */
  19169. Mesh.prototype.synchronizeInstances = function () {
  19170. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19171. var instance = this.instances[instanceIndex];
  19172. instance._syncSubMeshes();
  19173. }
  19174. };
  19175. /**
  19176. * Simplify the mesh according to the given array of settings.
  19177. * Function will return immediately and will simplify async. It returns nothing.
  19178. * @param settings a collection of simplification settings.
  19179. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19180. * @param type the type of simplification to run.
  19181. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19182. */
  19183. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19184. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19185. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19186. this.getScene().simplificationQueue.addTask({
  19187. settings: settings,
  19188. parallelProcessing: parallelProcessing,
  19189. mesh: this,
  19190. simplificationType: simplificationType,
  19191. successCallback: successCallback
  19192. });
  19193. };
  19194. /**
  19195. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19196. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19197. * This should be used together with the simplification to avoid disappearing triangles.
  19198. * @param successCallback an optional success callback to be called after the optimization finished.
  19199. */
  19200. Mesh.prototype.optimizeIndices = function (successCallback) {
  19201. var _this = this;
  19202. var indices = this.getIndices();
  19203. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19204. var vectorPositions = [];
  19205. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19206. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19207. }
  19208. var dupes = [];
  19209. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19210. var realPos = vectorPositions.length - 1 - iteration;
  19211. var testedPosition = vectorPositions[realPos];
  19212. for (var j = 0; j < realPos; ++j) {
  19213. var againstPosition = vectorPositions[j];
  19214. if (testedPosition.equals(againstPosition)) {
  19215. dupes[realPos] = j;
  19216. break;
  19217. }
  19218. }
  19219. }, function () {
  19220. for (var i = 0; i < indices.length; ++i) {
  19221. indices[i] = dupes[indices[i]] || indices[i];
  19222. }
  19223. //indices are now reordered
  19224. var originalSubMeshes = _this.subMeshes.slice(0);
  19225. _this.setIndices(indices);
  19226. _this.subMeshes = originalSubMeshes;
  19227. if (successCallback) {
  19228. successCallback(_this);
  19229. }
  19230. });
  19231. };
  19232. // Statics
  19233. /**
  19234. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19235. * The parameter `parsedMesh` is the mesh to be copied.
  19236. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19237. */
  19238. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19239. var mesh = new Mesh(parsedMesh.name, scene);
  19240. mesh.id = parsedMesh.id;
  19241. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19242. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19243. if (parsedMesh.rotationQuaternion) {
  19244. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19245. }
  19246. else if (parsedMesh.rotation) {
  19247. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19248. }
  19249. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19250. if (parsedMesh.localMatrix) {
  19251. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19252. }
  19253. else if (parsedMesh.pivotMatrix) {
  19254. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19255. }
  19256. mesh.setEnabled(parsedMesh.isEnabled);
  19257. mesh.isVisible = parsedMesh.isVisible;
  19258. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19259. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19260. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19261. if (parsedMesh.applyFog !== undefined) {
  19262. mesh.applyFog = parsedMesh.applyFog;
  19263. }
  19264. if (parsedMesh.pickable !== undefined) {
  19265. mesh.isPickable = parsedMesh.pickable;
  19266. }
  19267. if (parsedMesh.alphaIndex !== undefined) {
  19268. mesh.alphaIndex = parsedMesh.alphaIndex;
  19269. }
  19270. mesh.receiveShadows = parsedMesh.receiveShadows;
  19271. mesh.billboardMode = parsedMesh.billboardMode;
  19272. if (parsedMesh.visibility !== undefined) {
  19273. mesh.visibility = parsedMesh.visibility;
  19274. }
  19275. mesh.checkCollisions = parsedMesh.checkCollisions;
  19276. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19277. // freezeWorldMatrix
  19278. if (parsedMesh.freezeWorldMatrix) {
  19279. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19280. }
  19281. // Parent
  19282. if (parsedMesh.parentId) {
  19283. mesh._waitingParentId = parsedMesh.parentId;
  19284. }
  19285. // Actions
  19286. if (parsedMesh.actions !== undefined) {
  19287. mesh._waitingActions = parsedMesh.actions;
  19288. }
  19289. // Geometry
  19290. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19291. if (parsedMesh.delayLoadingFile) {
  19292. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19293. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19294. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19295. if (parsedMesh._binaryInfo) {
  19296. mesh._binaryInfo = parsedMesh._binaryInfo;
  19297. }
  19298. mesh._delayInfo = [];
  19299. if (parsedMesh.hasUVs) {
  19300. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19301. }
  19302. if (parsedMesh.hasUVs2) {
  19303. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19304. }
  19305. if (parsedMesh.hasUVs3) {
  19306. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19307. }
  19308. if (parsedMesh.hasUVs4) {
  19309. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19310. }
  19311. if (parsedMesh.hasUVs5) {
  19312. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19313. }
  19314. if (parsedMesh.hasUVs6) {
  19315. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19316. }
  19317. if (parsedMesh.hasColors) {
  19318. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19319. }
  19320. if (parsedMesh.hasMatricesIndices) {
  19321. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19322. }
  19323. if (parsedMesh.hasMatricesWeights) {
  19324. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19325. }
  19326. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19327. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19328. mesh._checkDelayState();
  19329. }
  19330. }
  19331. else {
  19332. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19333. }
  19334. // Material
  19335. if (parsedMesh.materialId) {
  19336. mesh.setMaterialByID(parsedMesh.materialId);
  19337. }
  19338. else {
  19339. mesh.material = null;
  19340. }
  19341. // Skeleton
  19342. if (parsedMesh.skeletonId > -1) {
  19343. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19344. if (parsedMesh.numBoneInfluencers) {
  19345. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19346. }
  19347. }
  19348. // Animations
  19349. if (parsedMesh.animations) {
  19350. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19351. var parsedAnimation = parsedMesh.animations[animationIndex];
  19352. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19353. }
  19354. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19355. }
  19356. if (parsedMesh.autoAnimate) {
  19357. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19358. }
  19359. // Layer Mask
  19360. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19361. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19362. }
  19363. else {
  19364. mesh.layerMask = 0x0FFFFFFF;
  19365. }
  19366. //(Deprecated) physics
  19367. if (parsedMesh.physicsImpostor) {
  19368. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19369. mass: parsedMesh.physicsMass,
  19370. friction: parsedMesh.physicsFriction,
  19371. restitution: parsedMesh.physicsRestitution
  19372. }, scene);
  19373. }
  19374. // Instances
  19375. if (parsedMesh.instances) {
  19376. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19377. var parsedInstance = parsedMesh.instances[index];
  19378. var instance = mesh.createInstance(parsedInstance.name);
  19379. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19380. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19381. if (parsedInstance.rotationQuaternion) {
  19382. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19383. }
  19384. else if (parsedInstance.rotation) {
  19385. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19386. }
  19387. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19388. instance.checkCollisions = mesh.checkCollisions;
  19389. if (parsedMesh.animations) {
  19390. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19391. parsedAnimation = parsedMesh.animations[animationIndex];
  19392. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19393. }
  19394. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19395. }
  19396. }
  19397. }
  19398. return mesh;
  19399. };
  19400. /**
  19401. * Creates a ribbon mesh.
  19402. * Please consider using the same method from the MeshBuilder class instead.
  19403. * 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.
  19404. *
  19405. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19406. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19407. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19408. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19409. * 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.
  19410. * 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.
  19411. * 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
  19412. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19415. */
  19416. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19417. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19418. pathArray: pathArray,
  19419. closeArray: closeArray,
  19420. closePath: closePath,
  19421. offset: offset,
  19422. updatable: updatable,
  19423. sideOrientation: sideOrientation,
  19424. instance: instance
  19425. }, scene);
  19426. };
  19427. /**
  19428. * Creates a plane polygonal mesh. By default, this is a disc.
  19429. * Please consider using the same method from the MeshBuilder class instead.
  19430. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19431. * 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.
  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.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19437. var options = {
  19438. radius: radius,
  19439. tessellation: tessellation,
  19440. sideOrientation: sideOrientation,
  19441. updatable: updatable
  19442. };
  19443. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19444. };
  19445. /**
  19446. * Creates a box mesh.
  19447. * Please consider using the same method from the MeshBuilder class instead.
  19448. * The parameter `size` sets the size (float) of each box side (default 1).
  19449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19452. */
  19453. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19454. var options = {
  19455. size: size,
  19456. sideOrientation: sideOrientation,
  19457. updatable: updatable
  19458. };
  19459. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19460. };
  19461. /**
  19462. * Creates a sphere mesh.
  19463. * Please consider using the same method from the MeshBuilder class instead.
  19464. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19465. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19469. */
  19470. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19471. var options = {
  19472. segments: segments,
  19473. diameterX: diameter,
  19474. diameterY: diameter,
  19475. diameterZ: diameter,
  19476. sideOrientation: sideOrientation,
  19477. updatable: updatable
  19478. };
  19479. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19480. };
  19481. /**
  19482. * Creates a cylinder or a cone mesh.
  19483. * Please consider using the same method from the MeshBuilder class instead.
  19484. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19485. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19486. * 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.
  19487. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19488. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19492. */
  19493. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19494. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19495. if (scene !== undefined) {
  19496. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19497. updatable = scene;
  19498. }
  19499. scene = subdivisions;
  19500. subdivisions = 1;
  19501. }
  19502. var options = {
  19503. height: height,
  19504. diameterTop: diameterTop,
  19505. diameterBottom: diameterBottom,
  19506. tessellation: tessellation,
  19507. subdivisions: subdivisions,
  19508. sideOrientation: sideOrientation,
  19509. updatable: updatable
  19510. };
  19511. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19512. };
  19513. // Torus (Code from SharpDX.org)
  19514. /**
  19515. * Creates a torus mesh.
  19516. * Please consider using the same method from the MeshBuilder class instead.
  19517. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19518. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19519. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19523. */
  19524. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19525. var options = {
  19526. diameter: diameter,
  19527. thickness: thickness,
  19528. tessellation: tessellation,
  19529. sideOrientation: sideOrientation,
  19530. updatable: updatable
  19531. };
  19532. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19533. };
  19534. /**
  19535. * Creates a torus knot mesh.
  19536. * Please consider using the same method from the MeshBuilder class instead.
  19537. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19538. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19539. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19540. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19544. */
  19545. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19546. var options = {
  19547. radius: radius,
  19548. tube: tube,
  19549. radialSegments: radialSegments,
  19550. tubularSegments: tubularSegments,
  19551. p: p,
  19552. q: q,
  19553. sideOrientation: sideOrientation,
  19554. updatable: updatable
  19555. };
  19556. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19557. };
  19558. /**
  19559. * Creates a line mesh.
  19560. * Please consider using the same method from the MeshBuilder class instead.
  19561. * 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.
  19562. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19563. * The parameter `points` is an array successive Vector3.
  19564. * 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
  19565. * When updating an instance, remember that only point positions can change, not the number of points.
  19566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19567. */
  19568. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19569. var options = {
  19570. points: points,
  19571. updatable: updatable,
  19572. instance: instance
  19573. };
  19574. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19575. };
  19576. /**
  19577. * Creates a dashed line mesh.
  19578. * Please consider using the same method from the MeshBuilder class instead.
  19579. * 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.
  19580. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19581. * The parameter `points` is an array successive Vector3.
  19582. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19583. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19584. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19585. * 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
  19586. * When updating an instance, remember that only point positions can change, not the number of points.
  19587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19588. */
  19589. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19590. var options = {
  19591. points: points,
  19592. dashSize: dashSize,
  19593. gapSize: gapSize,
  19594. dashNb: dashNb,
  19595. updatable: updatable,
  19596. instance: instance
  19597. };
  19598. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19599. };
  19600. /**
  19601. * Creates an extruded shape mesh.
  19602. * 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.
  19603. * Please consider using the same method from the MeshBuilder class instead.
  19604. *
  19605. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19606. * 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
  19607. * extruded along the Z axis.
  19608. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19609. * 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.
  19610. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19611. * 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
  19612. * 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
  19613. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19615. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19617. */
  19618. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19619. var options = {
  19620. shape: shape,
  19621. path: path,
  19622. scale: scale,
  19623. rotation: rotation,
  19624. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19625. sideOrientation: sideOrientation,
  19626. instance: instance,
  19627. updatable: updatable
  19628. };
  19629. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19630. };
  19631. /**
  19632. * Creates an custom extruded shape mesh.
  19633. * 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.
  19634. * Please consider using the same method from the MeshBuilder class instead.
  19635. *
  19636. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19637. * 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
  19638. * extruded along the Z axis.
  19639. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19640. * 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
  19641. * and the distance of this point from the begining of the path :
  19642. * ```javascript
  19643. * var rotationFunction = function(i, distance) {
  19644. * // do things
  19645. * return rotationValue; }
  19646. * ```
  19647. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19648. * 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
  19649. * and the distance of this point from the begining of the path :
  19650. * ```javascript
  19651. * var scaleFunction = function(i, distance) {
  19652. * // do things
  19653. * return scaleValue;}
  19654. * ```
  19655. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19656. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19657. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19658. * 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
  19659. * 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
  19660. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19664. */
  19665. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19666. var options = {
  19667. shape: shape,
  19668. path: path,
  19669. scaleFunction: scaleFunction,
  19670. rotationFunction: rotationFunction,
  19671. ribbonCloseArray: ribbonCloseArray,
  19672. ribbonClosePath: ribbonClosePath,
  19673. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19674. sideOrientation: sideOrientation,
  19675. instance: instance,
  19676. updatable: updatable
  19677. };
  19678. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19679. };
  19680. /**
  19681. * Creates lathe mesh.
  19682. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19683. * Please consider using the same method from the MeshBuilder class instead.
  19684. * 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
  19685. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19686. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19687. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19689. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19691. */
  19692. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19693. var options = {
  19694. shape: shape,
  19695. radius: radius,
  19696. tessellation: tessellation,
  19697. sideOrientation: sideOrientation,
  19698. updatable: updatable
  19699. };
  19700. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19701. };
  19702. /**
  19703. * Creates a plane mesh.
  19704. * Please consider using the same method from the MeshBuilder class instead.
  19705. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19709. */
  19710. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19711. var options = {
  19712. size: size,
  19713. width: size,
  19714. height: size,
  19715. sideOrientation: sideOrientation,
  19716. updatable: updatable
  19717. };
  19718. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19719. };
  19720. /**
  19721. * Creates a ground mesh.
  19722. * Please consider using the same method from the MeshBuilder class instead.
  19723. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19724. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19726. */
  19727. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19728. var options = {
  19729. width: width,
  19730. height: height,
  19731. subdivisions: subdivisions,
  19732. updatable: updatable
  19733. };
  19734. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19735. };
  19736. /**
  19737. * Creates a tiled ground mesh.
  19738. * Please consider using the same method from the MeshBuilder class instead.
  19739. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19740. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19741. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19742. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19743. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19744. * numbers of subdivisions on the ground width and height of each tile.
  19745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19746. */
  19747. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19748. var options = {
  19749. xmin: xmin,
  19750. zmin: zmin,
  19751. xmax: xmax,
  19752. zmax: zmax,
  19753. subdivisions: subdivisions,
  19754. precision: precision,
  19755. updatable: updatable
  19756. };
  19757. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19758. };
  19759. /**
  19760. * Creates a ground mesh from a height map.
  19761. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19762. * Please consider using the same method from the MeshBuilder class instead.
  19763. * The parameter `url` sets the URL of the height map image resource.
  19764. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19765. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19766. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19767. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19768. * 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).
  19769. * This function is passed the newly built mesh :
  19770. * ```javascript
  19771. * function(mesh) { // do things
  19772. * return; }
  19773. * ```
  19774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19775. */
  19776. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19777. var options = {
  19778. width: width,
  19779. height: height,
  19780. subdivisions: subdivisions,
  19781. minHeight: minHeight,
  19782. maxHeight: maxHeight,
  19783. updatable: updatable,
  19784. onReady: onReady
  19785. };
  19786. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19787. };
  19788. /**
  19789. * Creates a tube mesh.
  19790. * 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.
  19791. * Please consider using the same method from the MeshBuilder class instead.
  19792. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19793. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19794. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19795. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19796. * 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.
  19797. * It must return a radius value (positive float) :
  19798. * ```javascript
  19799. * var radiusFunction = function(i, distance) {
  19800. * // do things
  19801. * return radius; }
  19802. * ```
  19803. * 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
  19804. * 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
  19805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19806. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19808. */
  19809. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19810. var options = {
  19811. path: path,
  19812. radius: radius,
  19813. tessellation: tessellation,
  19814. radiusFunction: radiusFunction,
  19815. arc: 1,
  19816. cap: cap,
  19817. updatable: updatable,
  19818. sideOrientation: sideOrientation,
  19819. instance: instance
  19820. };
  19821. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19822. };
  19823. /**
  19824. * Creates a polyhedron mesh.
  19825. * Please consider using the same method from the MeshBuilder class instead.
  19826. * 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
  19827. * to choose the wanted type.
  19828. * The parameter `size` (positive float, default 1) sets the polygon size.
  19829. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19830. * 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`.
  19831. * 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
  19832. * 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)`).
  19833. * 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
  19834. * 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.
  19835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19838. */
  19839. Mesh.CreatePolyhedron = function (name, options, scene) {
  19840. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19841. };
  19842. /**
  19843. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19844. * Please consider using the same method from the MeshBuilder class instead.
  19845. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19846. * 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`).
  19847. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19848. * 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.
  19849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19852. */
  19853. Mesh.CreateIcoSphere = function (name, options, scene) {
  19854. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19855. };
  19856. /**
  19857. * Creates a decal mesh.
  19858. * Please consider using the same method from the MeshBuilder class instead.
  19859. * 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.
  19860. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19861. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19862. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  19863. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19864. */
  19865. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19866. var options = {
  19867. position: position,
  19868. normal: normal,
  19869. size: size,
  19870. angle: angle
  19871. };
  19872. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19873. };
  19874. // Skeletons
  19875. /**
  19876. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19877. */
  19878. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19879. var source;
  19880. if (!this._sourcePositions) {
  19881. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19882. this._sourcePositions = new Float32Array(source);
  19883. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19884. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19885. }
  19886. }
  19887. return this._sourcePositions;
  19888. };
  19889. /**
  19890. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19891. */
  19892. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19893. var source;
  19894. if (!this._sourceNormals) {
  19895. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19896. this._sourceNormals = new Float32Array(source);
  19897. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19898. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19899. }
  19900. }
  19901. return this._sourceNormals;
  19902. };
  19903. /**
  19904. * Update the vertex buffers by applying transformation from the bones
  19905. * @param {skeleton} skeleton to apply
  19906. */
  19907. Mesh.prototype.applySkeleton = function (skeleton) {
  19908. if (!this.geometry) {
  19909. return;
  19910. }
  19911. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19912. return;
  19913. }
  19914. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19915. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19916. return this;
  19917. }
  19918. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19919. return this;
  19920. }
  19921. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19922. return this;
  19923. }
  19924. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19925. return this;
  19926. }
  19927. if (!this._sourcePositions) {
  19928. this.setPositionsForCPUSkinning();
  19929. }
  19930. if (!this._sourceNormals) {
  19931. this.setNormalsForCPUSkinning();
  19932. }
  19933. // positionsData checks for not being Float32Array will only pass at most once
  19934. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19935. if (!(positionsData instanceof Float32Array)) {
  19936. positionsData = new Float32Array(positionsData);
  19937. }
  19938. // normalsData checks for not being Float32Array will only pass at most once
  19939. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19940. if (!(normalsData instanceof Float32Array)) {
  19941. normalsData = new Float32Array(normalsData);
  19942. }
  19943. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19944. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19945. var needExtras = this.numBoneInfluencers > 4;
  19946. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19947. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19948. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19949. var tempVector3 = BABYLON.Vector3.Zero();
  19950. var finalMatrix = new BABYLON.Matrix();
  19951. var tempMatrix = new BABYLON.Matrix();
  19952. var matWeightIdx = 0;
  19953. var inf;
  19954. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19955. var weight;
  19956. for (inf = 0; inf < 4; inf++) {
  19957. weight = matricesWeightsData[matWeightIdx + inf];
  19958. if (weight > 0) {
  19959. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19960. finalMatrix.addToSelf(tempMatrix);
  19961. }
  19962. else
  19963. break;
  19964. }
  19965. if (needExtras) {
  19966. for (inf = 0; inf < 4; inf++) {
  19967. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19968. if (weight > 0) {
  19969. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19970. finalMatrix.addToSelf(tempMatrix);
  19971. }
  19972. else
  19973. break;
  19974. }
  19975. }
  19976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19977. tempVector3.toArray(positionsData, index);
  19978. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19979. tempVector3.toArray(normalsData, index);
  19980. finalMatrix.reset();
  19981. }
  19982. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19983. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19984. return this;
  19985. };
  19986. // Tools
  19987. /**
  19988. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  19989. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19990. */
  19991. Mesh.MinMax = function (meshes) {
  19992. var minVector = null;
  19993. var maxVector = null;
  19994. for (var i in meshes) {
  19995. var mesh = meshes[i];
  19996. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19997. if (!minVector) {
  19998. minVector = boundingBox.minimumWorld;
  19999. maxVector = boundingBox.maximumWorld;
  20000. continue;
  20001. }
  20002. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20003. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20004. }
  20005. return {
  20006. min: minVector,
  20007. max: maxVector
  20008. };
  20009. };
  20010. /**
  20011. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20012. */
  20013. Mesh.Center = function (meshesOrMinMaxVector) {
  20014. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20015. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20016. };
  20017. /**
  20018. * Merge the array of meshes into a single mesh for performance reasons.
  20019. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20020. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20021. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20022. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20023. */
  20024. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20025. if (disposeSource === void 0) { disposeSource = true; }
  20026. var index;
  20027. if (!allow32BitsIndices) {
  20028. var totalVertices = 0;
  20029. // Counting vertices
  20030. for (index = 0; index < meshes.length; index++) {
  20031. if (meshes[index]) {
  20032. totalVertices += meshes[index].getTotalVertices();
  20033. if (totalVertices > 65536) {
  20034. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20035. return null;
  20036. }
  20037. }
  20038. }
  20039. }
  20040. // Merge
  20041. var vertexData;
  20042. var otherVertexData;
  20043. var source;
  20044. for (index = 0; index < meshes.length; index++) {
  20045. if (meshes[index]) {
  20046. meshes[index].computeWorldMatrix(true);
  20047. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20048. otherVertexData.transform(meshes[index].getWorldMatrix());
  20049. if (vertexData) {
  20050. vertexData.merge(otherVertexData);
  20051. }
  20052. else {
  20053. vertexData = otherVertexData;
  20054. source = meshes[index];
  20055. }
  20056. }
  20057. }
  20058. if (!meshSubclass) {
  20059. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20060. }
  20061. vertexData.applyToMesh(meshSubclass);
  20062. // Setting properties
  20063. meshSubclass.material = source.material;
  20064. meshSubclass.checkCollisions = source.checkCollisions;
  20065. // Cleaning
  20066. if (disposeSource) {
  20067. for (index = 0; index < meshes.length; index++) {
  20068. if (meshes[index]) {
  20069. meshes[index].dispose();
  20070. }
  20071. }
  20072. }
  20073. return meshSubclass;
  20074. };
  20075. // Consts
  20076. Mesh._FRONTSIDE = 0;
  20077. Mesh._BACKSIDE = 1;
  20078. Mesh._DOUBLESIDE = 2;
  20079. Mesh._DEFAULTSIDE = 0;
  20080. Mesh._NO_CAP = 0;
  20081. Mesh._CAP_START = 1;
  20082. Mesh._CAP_END = 2;
  20083. Mesh._CAP_ALL = 3;
  20084. return Mesh;
  20085. })(BABYLON.AbstractMesh);
  20086. BABYLON.Mesh = Mesh;
  20087. })(BABYLON || (BABYLON = {}));
  20088. var BABYLON;
  20089. (function (BABYLON) {
  20090. var SubMesh = (function () {
  20091. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20092. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20093. this.materialIndex = materialIndex;
  20094. this.verticesStart = verticesStart;
  20095. this.verticesCount = verticesCount;
  20096. this.indexStart = indexStart;
  20097. this.indexCount = indexCount;
  20098. this._renderId = 0;
  20099. this._mesh = mesh;
  20100. this._renderingMesh = renderingMesh || mesh;
  20101. mesh.subMeshes.push(this);
  20102. this._trianglePlanes = [];
  20103. this._id = mesh.subMeshes.length - 1;
  20104. if (createBoundingBox) {
  20105. this.refreshBoundingInfo();
  20106. mesh.computeWorldMatrix(true);
  20107. }
  20108. }
  20109. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20110. get: function () {
  20111. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. SubMesh.prototype.getBoundingInfo = function () {
  20117. if (this.IsGlobal) {
  20118. return this._mesh.getBoundingInfo();
  20119. }
  20120. return this._boundingInfo;
  20121. };
  20122. SubMesh.prototype.getMesh = function () {
  20123. return this._mesh;
  20124. };
  20125. SubMesh.prototype.getRenderingMesh = function () {
  20126. return this._renderingMesh;
  20127. };
  20128. SubMesh.prototype.getMaterial = function () {
  20129. var rootMaterial = this._renderingMesh.material;
  20130. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20131. var multiMaterial = rootMaterial;
  20132. return multiMaterial.getSubMaterial(this.materialIndex);
  20133. }
  20134. if (!rootMaterial) {
  20135. return this._mesh.getScene().defaultMaterial;
  20136. }
  20137. return rootMaterial;
  20138. };
  20139. // Methods
  20140. SubMesh.prototype.refreshBoundingInfo = function () {
  20141. this._lastColliderWorldVertices = null;
  20142. if (this.IsGlobal) {
  20143. return;
  20144. }
  20145. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20146. if (!data) {
  20147. this._boundingInfo = this._mesh._boundingInfo;
  20148. return;
  20149. }
  20150. var indices = this._renderingMesh.getIndices();
  20151. var extend;
  20152. //is this the only submesh?
  20153. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20154. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20155. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20156. }
  20157. else {
  20158. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20159. }
  20160. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20161. };
  20162. SubMesh.prototype._checkCollision = function (collider) {
  20163. return this.getBoundingInfo()._checkCollision(collider);
  20164. };
  20165. SubMesh.prototype.updateBoundingInfo = function (world) {
  20166. if (!this.getBoundingInfo()) {
  20167. this.refreshBoundingInfo();
  20168. }
  20169. this.getBoundingInfo().update(world);
  20170. };
  20171. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20172. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20173. };
  20174. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20175. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20176. };
  20177. SubMesh.prototype.render = function (enableAlphaMode) {
  20178. this._renderingMesh.render(this, enableAlphaMode);
  20179. };
  20180. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20181. if (!this._linesIndexBuffer) {
  20182. var linesIndices = [];
  20183. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20184. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20185. }
  20186. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20187. this.linesIndexCount = linesIndices.length;
  20188. }
  20189. return this._linesIndexBuffer;
  20190. };
  20191. SubMesh.prototype.canIntersects = function (ray) {
  20192. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20193. };
  20194. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20195. var intersectInfo = null;
  20196. // LineMesh first as it's also a Mesh...
  20197. if (this._mesh instanceof BABYLON.LinesMesh) {
  20198. var lineMesh = this._mesh;
  20199. // Line test
  20200. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20201. var p0 = positions[indices[index]];
  20202. var p1 = positions[indices[index + 1]];
  20203. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20204. if (length < 0) {
  20205. continue;
  20206. }
  20207. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20208. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20209. if (fastCheck) {
  20210. break;
  20211. }
  20212. }
  20213. }
  20214. }
  20215. else {
  20216. // Triangles test
  20217. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20218. var p0 = positions[indices[index]];
  20219. var p1 = positions[indices[index + 1]];
  20220. var p2 = positions[indices[index + 2]];
  20221. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20222. if (currentIntersectInfo) {
  20223. if (currentIntersectInfo.distance < 0) {
  20224. continue;
  20225. }
  20226. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20227. intersectInfo = currentIntersectInfo;
  20228. intersectInfo.faceId = index / 3;
  20229. if (fastCheck) {
  20230. break;
  20231. }
  20232. }
  20233. }
  20234. }
  20235. }
  20236. return intersectInfo;
  20237. };
  20238. // Clone
  20239. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20240. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20241. if (!this.IsGlobal) {
  20242. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20243. }
  20244. return result;
  20245. };
  20246. // Dispose
  20247. SubMesh.prototype.dispose = function () {
  20248. if (this._linesIndexBuffer) {
  20249. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20250. this._linesIndexBuffer = null;
  20251. }
  20252. // Remove from mesh
  20253. var index = this._mesh.subMeshes.indexOf(this);
  20254. this._mesh.subMeshes.splice(index, 1);
  20255. };
  20256. // Statics
  20257. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20258. var minVertexIndex = Number.MAX_VALUE;
  20259. var maxVertexIndex = -Number.MAX_VALUE;
  20260. renderingMesh = renderingMesh || mesh;
  20261. var indices = renderingMesh.getIndices();
  20262. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20263. var vertexIndex = indices[index];
  20264. if (vertexIndex < minVertexIndex)
  20265. minVertexIndex = vertexIndex;
  20266. if (vertexIndex > maxVertexIndex)
  20267. maxVertexIndex = vertexIndex;
  20268. }
  20269. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20270. };
  20271. return SubMesh;
  20272. })();
  20273. BABYLON.SubMesh = SubMesh;
  20274. })(BABYLON || (BABYLON = {}));
  20275. var BABYLON;
  20276. (function (BABYLON) {
  20277. var MeshBuilder = (function () {
  20278. function MeshBuilder() {
  20279. }
  20280. /**
  20281. * Creates a box mesh.
  20282. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20283. * The parameter `size` sets the size (float) of each box side (default 1).
  20284. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20285. * 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).
  20286. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20290. */
  20291. MeshBuilder.CreateBox = function (name, options, scene) {
  20292. var box = new BABYLON.Mesh(name, scene);
  20293. var vertexData = BABYLON.VertexData.CreateBox(options);
  20294. vertexData.applyToMesh(box, options.updatable);
  20295. return box;
  20296. };
  20297. /**
  20298. * Creates a sphere mesh.
  20299. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20300. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20301. * 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`).
  20302. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20303. * 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
  20304. * 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).
  20305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20308. */
  20309. MeshBuilder.CreateSphere = function (name, options, scene) {
  20310. var sphere = new BABYLON.Mesh(name, scene);
  20311. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20312. vertexData.applyToMesh(sphere, options.updatable);
  20313. return sphere;
  20314. };
  20315. /**
  20316. * Creates a plane polygonal mesh. By default, this is a disc.
  20317. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20318. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20319. * 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.
  20320. * 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
  20321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20324. */
  20325. MeshBuilder.CreateDisc = function (name, options, scene) {
  20326. var disc = new BABYLON.Mesh(name, scene);
  20327. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20328. vertexData.applyToMesh(disc, options.updatable);
  20329. return disc;
  20330. };
  20331. /**
  20332. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20333. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20334. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20335. * 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`).
  20336. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20337. * 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.
  20338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20341. */
  20342. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20343. var sphere = new BABYLON.Mesh(name, scene);
  20344. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20345. vertexData.applyToMesh(sphere, options.updatable);
  20346. return sphere;
  20347. };
  20348. ;
  20349. /**
  20350. * Creates a ribbon mesh.
  20351. * 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.
  20352. *
  20353. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20354. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20355. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20356. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20357. * 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.
  20358. * 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.
  20359. * 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
  20360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20361. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20362. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20364. */
  20365. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20366. var pathArray = options.pathArray;
  20367. var closeArray = options.closeArray;
  20368. var closePath = options.closePath;
  20369. var offset = options.offset;
  20370. var sideOrientation = options.sideOrientation;
  20371. var instance = options.instance;
  20372. var updatable = options.updatable;
  20373. if (instance) {
  20374. // positionFunction : ribbon case
  20375. // only pathArray and sideOrientation parameters are taken into account for positions update
  20376. var positionFunction = function (positions) {
  20377. var minlg = pathArray[0].length;
  20378. var i = 0;
  20379. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20380. for (var si = 1; si <= ns; si++) {
  20381. for (var p = 0; p < pathArray.length; p++) {
  20382. var path = pathArray[p];
  20383. var l = path.length;
  20384. minlg = (minlg < l) ? minlg : l;
  20385. var j = 0;
  20386. while (j < minlg) {
  20387. positions[i] = path[j].x;
  20388. positions[i + 1] = path[j].y;
  20389. positions[i + 2] = path[j].z;
  20390. j++;
  20391. i += 3;
  20392. }
  20393. if (instance._closePath) {
  20394. positions[i] = path[0].x;
  20395. positions[i + 1] = path[0].y;
  20396. positions[i + 2] = path[0].z;
  20397. i += 3;
  20398. }
  20399. }
  20400. }
  20401. };
  20402. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20403. positionFunction(positions);
  20404. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20405. if (!(instance.areNormalsFrozen)) {
  20406. var indices = instance.getIndices();
  20407. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20408. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20409. if (instance._closePath) {
  20410. var indexFirst = 0;
  20411. var indexLast = 0;
  20412. for (var p = 0; p < pathArray.length; p++) {
  20413. indexFirst = instance._idx[p] * 3;
  20414. if (p + 1 < pathArray.length) {
  20415. indexLast = (instance._idx[p + 1] - 1) * 3;
  20416. }
  20417. else {
  20418. indexLast = normals.length - 3;
  20419. }
  20420. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20421. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20422. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20423. normals[indexLast] = normals[indexFirst];
  20424. normals[indexLast + 1] = normals[indexFirst + 1];
  20425. normals[indexLast + 2] = normals[indexFirst + 2];
  20426. }
  20427. }
  20428. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20429. }
  20430. return instance;
  20431. }
  20432. else {
  20433. var ribbon = new BABYLON.Mesh(name, scene);
  20434. ribbon.sideOrientation = sideOrientation;
  20435. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20436. if (closePath) {
  20437. ribbon._idx = vertexData._idx;
  20438. }
  20439. ribbon._closePath = closePath;
  20440. ribbon._closeArray = closeArray;
  20441. vertexData.applyToMesh(ribbon, updatable);
  20442. return ribbon;
  20443. }
  20444. };
  20445. /**
  20446. * Creates a cylinder or a cone mesh.
  20447. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20448. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20449. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20450. * 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.
  20451. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20452. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20453. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20454. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20455. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20456. * 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).
  20457. * 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
  20458. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20459. * 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
  20460. * 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.
  20461. * If `enclose` is false, a ring surface is one element.
  20462. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20463. * 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
  20464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20467. */
  20468. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20469. var cylinder = new BABYLON.Mesh(name, scene);
  20470. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20471. vertexData.applyToMesh(cylinder, options.updatable);
  20472. return cylinder;
  20473. };
  20474. /**
  20475. * Creates a torus mesh.
  20476. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20477. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20478. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20479. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20480. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20481. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20483. */
  20484. MeshBuilder.CreateTorus = function (name, options, scene) {
  20485. var torus = new BABYLON.Mesh(name, scene);
  20486. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20487. vertexData.applyToMesh(torus, options.updatable);
  20488. return torus;
  20489. };
  20490. /**
  20491. * Creates a torus knot mesh.
  20492. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20493. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20494. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20495. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20496. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20500. */
  20501. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20502. var torusKnot = new BABYLON.Mesh(name, scene);
  20503. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20504. vertexData.applyToMesh(torusKnot, options.updatable);
  20505. return torusKnot;
  20506. };
  20507. /**
  20508. * Creates a line system mesh.
  20509. * A line system is a pool of many lines gathered in a single mesh.
  20510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20511. * 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.
  20512. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20513. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20514. * 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
  20515. * 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
  20516. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20518. */
  20519. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20520. var instance = options.instance;
  20521. var lines = options.lines;
  20522. if (instance) {
  20523. var positionFunction = function (positions) {
  20524. var i = 0;
  20525. for (var l = 0; l < lines.length; l++) {
  20526. var points = lines[l];
  20527. for (var p = 0; p < points.length; p++) {
  20528. positions[i] = points[p].x;
  20529. positions[i + 1] = points[p].y;
  20530. positions[i + 2] = points[p].z;
  20531. i += 3;
  20532. }
  20533. }
  20534. };
  20535. instance.updateMeshPositions(positionFunction, false);
  20536. return instance;
  20537. }
  20538. // line system creation
  20539. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20540. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20541. vertexData.applyToMesh(lineSystem, options.updatable);
  20542. return lineSystem;
  20543. };
  20544. /**
  20545. * Creates a line mesh.
  20546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20547. * 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.
  20548. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20549. * The parameter `points` is an array successive Vector3.
  20550. * 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
  20551. * When updating an instance, remember that only point positions can change, not the number of points.
  20552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20553. */
  20554. MeshBuilder.CreateLines = function (name, options, scene) {
  20555. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20556. return lines;
  20557. };
  20558. /**
  20559. * Creates a dashed line mesh.
  20560. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20561. * 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.
  20562. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20563. * The parameter `points` is an array successive Vector3.
  20564. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20565. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20566. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20567. * 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
  20568. * When updating an instance, remember that only point positions can change, not the number of points.
  20569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20570. */
  20571. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20572. var points = options.points;
  20573. var instance = options.instance;
  20574. var gapSize = options.gapSize;
  20575. var dashNb = options.dashNb;
  20576. var dashSize = options.dashSize;
  20577. if (instance) {
  20578. var positionFunction = function (positions) {
  20579. var curvect = BABYLON.Vector3.Zero();
  20580. var nbSeg = positions.length / 6;
  20581. var lg = 0;
  20582. var nb = 0;
  20583. var shft = 0;
  20584. var dashshft = 0;
  20585. var curshft = 0;
  20586. var p = 0;
  20587. var i = 0;
  20588. var j = 0;
  20589. for (i = 0; i < points.length - 1; i++) {
  20590. points[i + 1].subtractToRef(points[i], curvect);
  20591. lg += curvect.length();
  20592. }
  20593. shft = lg / nbSeg;
  20594. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20595. for (i = 0; i < points.length - 1; i++) {
  20596. points[i + 1].subtractToRef(points[i], curvect);
  20597. nb = Math.floor(curvect.length() / shft);
  20598. curvect.normalize();
  20599. j = 0;
  20600. while (j < nb && p < positions.length) {
  20601. curshft = shft * j;
  20602. positions[p] = points[i].x + curshft * curvect.x;
  20603. positions[p + 1] = points[i].y + curshft * curvect.y;
  20604. positions[p + 2] = points[i].z + curshft * curvect.z;
  20605. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20606. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20607. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20608. p += 6;
  20609. j++;
  20610. }
  20611. }
  20612. while (p < positions.length) {
  20613. positions[p] = points[i].x;
  20614. positions[p + 1] = points[i].y;
  20615. positions[p + 2] = points[i].z;
  20616. p += 3;
  20617. }
  20618. };
  20619. instance.updateMeshPositions(positionFunction, false);
  20620. return instance;
  20621. }
  20622. // dashed lines creation
  20623. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20624. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20625. vertexData.applyToMesh(dashedLines, options.updatable);
  20626. dashedLines.dashSize = dashSize;
  20627. dashedLines.gapSize = gapSize;
  20628. return dashedLines;
  20629. };
  20630. /**
  20631. * Creates an extruded shape mesh.
  20632. * 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.
  20633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20634. *
  20635. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20636. * 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
  20637. * extruded along the Z axis.
  20638. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20639. * 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.
  20640. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20641. * 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
  20642. * 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
  20643. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20646. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20648. */
  20649. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20650. var path = options.path;
  20651. var shape = options.shape;
  20652. var scale = options.scale || 1;
  20653. var rotation = options.rotation || 0;
  20654. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20655. var updatable = options.updatable;
  20656. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20657. var instance = options.instance;
  20658. var invertUV = options.invertUV || false;
  20659. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20660. };
  20661. /**
  20662. * Creates an custom extruded shape mesh.
  20663. * 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.
  20664. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20665. *
  20666. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20667. * 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
  20668. * extruded along the Z axis.
  20669. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20670. * 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
  20671. * and the distance of this point from the begining of the path :
  20672. * ```javascript
  20673. * var rotationFunction = function(i, distance) {
  20674. * // do things
  20675. * return rotationValue; }
  20676. * ```
  20677. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20678. * 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
  20679. * and the distance of this point from the begining of the path :
  20680. * ```javascript
  20681. * var scaleFunction = function(i, distance) {
  20682. * // do things
  20683. * return scaleValue;}
  20684. * ```
  20685. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20686. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20687. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20688. * 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
  20689. * 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
  20690. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20691. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20692. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20693. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20695. */
  20696. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20697. var path = options.path;
  20698. var shape = options.shape;
  20699. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20700. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20701. var ribbonCloseArray = options.ribbonCloseArray || false;
  20702. var ribbonClosePath = options.ribbonClosePath || false;
  20703. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20704. var updatable = options.updatable;
  20705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20706. var instance = options.instance;
  20707. var invertUV = options.invertUV || false;
  20708. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20709. };
  20710. /**
  20711. * Creates lathe mesh.
  20712. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20713. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20714. *
  20715. * 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
  20716. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20717. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20718. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20719. * 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.
  20720. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20721. * 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
  20722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20723. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20724. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20726. */
  20727. MeshBuilder.CreateLathe = function (name, options, scene) {
  20728. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20729. var closed = (options.closed === undefined) ? true : options.closed;
  20730. var shape = options.shape;
  20731. var radius = options.radius || 1;
  20732. var tessellation = options.tessellation || 64;
  20733. var updatable = options.updatable;
  20734. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20735. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20736. var pi2 = Math.PI * 2;
  20737. var paths = new Array();
  20738. var invertUV = options.invertUV || false;
  20739. var i = 0;
  20740. var p = 0;
  20741. var step = pi2 / tessellation * arc;
  20742. var rotated;
  20743. var path = new Array();
  20744. ;
  20745. for (i = 0; i <= tessellation; i++) {
  20746. var path = [];
  20747. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20748. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20749. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20750. }
  20751. for (p = 0; p < shape.length; p++) {
  20752. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20753. path.push(rotated);
  20754. }
  20755. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20756. 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));
  20757. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20758. }
  20759. paths.push(path);
  20760. }
  20761. // lathe ribbon
  20762. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20763. return lathe;
  20764. };
  20765. /**
  20766. * Creates a plane mesh.
  20767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20768. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20769. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20770. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20771. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20772. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20774. */
  20775. MeshBuilder.CreatePlane = function (name, options, scene) {
  20776. var plane = new BABYLON.Mesh(name, scene);
  20777. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20778. vertexData.applyToMesh(plane, options.updatable);
  20779. if (options.sourcePlane) {
  20780. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20781. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20782. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20783. plane.rotate(vectorProduct, product);
  20784. }
  20785. return plane;
  20786. };
  20787. /**
  20788. * Creates a ground mesh.
  20789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20790. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20791. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20793. */
  20794. MeshBuilder.CreateGround = function (name, options, scene) {
  20795. var ground = new BABYLON.GroundMesh(name, scene);
  20796. ground._setReady(false);
  20797. ground._subdivisions = options.subdivisions || 1;
  20798. ground._width = options.width || 1;
  20799. ground._height = options.height || 1;
  20800. ground._maxX = ground._width / 2;
  20801. ground._maxZ = ground._height / 2;
  20802. ground._minX = -ground._maxX;
  20803. ground._minZ = -ground._maxZ;
  20804. var vertexData = BABYLON.VertexData.CreateGround(options);
  20805. vertexData.applyToMesh(ground, options.updatable);
  20806. ground._setReady(true);
  20807. return ground;
  20808. };
  20809. /**
  20810. * Creates a tiled ground mesh.
  20811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20812. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20813. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20814. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20815. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20816. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20817. * numbers of subdivisions on the ground width and height of each tile.
  20818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20819. */
  20820. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20821. var tiledGround = new BABYLON.Mesh(name, scene);
  20822. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20823. vertexData.applyToMesh(tiledGround, options.updatable);
  20824. return tiledGround;
  20825. };
  20826. /**
  20827. * Creates a ground mesh from a height map.
  20828. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20829. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20830. * The parameter `url` sets the URL of the height map image resource.
  20831. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20832. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20833. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20834. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20835. * 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).
  20836. * This function is passed the newly built mesh :
  20837. * ```javascript
  20838. * function(mesh) { // do things
  20839. * return; }
  20840. * ```
  20841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20842. */
  20843. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20844. var width = options.width || 10.0;
  20845. var height = options.height || 10.0;
  20846. var subdivisions = options.subdivisions || 1 | 0;
  20847. var minHeight = options.minHeight || 0.0;
  20848. var maxHeight = options.maxHeight || 10.0;
  20849. var updatable = options.updatable;
  20850. var onReady = options.onReady;
  20851. var ground = new BABYLON.GroundMesh(name, scene);
  20852. ground._subdivisions = subdivisions;
  20853. ground._width = width;
  20854. ground._height = height;
  20855. ground._maxX = ground._width / 2.0;
  20856. ground._maxZ = ground._height / 2.0;
  20857. ground._minX = -ground._maxX;
  20858. ground._minZ = -ground._maxZ;
  20859. ground._setReady(false);
  20860. var onload = function (img) {
  20861. // Getting height map data
  20862. var canvas = document.createElement("canvas");
  20863. var context = canvas.getContext("2d");
  20864. var bufferWidth = img.width;
  20865. var bufferHeight = img.height;
  20866. canvas.width = bufferWidth;
  20867. canvas.height = bufferHeight;
  20868. context.drawImage(img, 0, 0);
  20869. // Create VertexData from map data
  20870. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20871. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20872. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20873. width: width, height: height,
  20874. subdivisions: subdivisions,
  20875. minHeight: minHeight, maxHeight: maxHeight,
  20876. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20877. });
  20878. vertexData.applyToMesh(ground, updatable);
  20879. ground._setReady(true);
  20880. //execute ready callback, if set
  20881. if (onReady) {
  20882. onReady(ground);
  20883. }
  20884. };
  20885. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20886. return ground;
  20887. };
  20888. /**
  20889. * Creates a tube mesh.
  20890. * 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.
  20891. *
  20892. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20893. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20894. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20895. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20896. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20897. * 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.
  20898. * It must return a radius value (positive float) :
  20899. * ```javascript
  20900. * var radiusFunction = function(i, distance) {
  20901. * // do things
  20902. * return radius; }
  20903. * ```
  20904. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20905. * 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
  20906. * 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
  20907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20909. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20911. */
  20912. MeshBuilder.CreateTube = function (name, options, scene) {
  20913. var path = options.path;
  20914. var radius = options.radius || 1.0;
  20915. var tessellation = options.tessellation || 64 | 0;
  20916. var radiusFunction = options.radiusFunction;
  20917. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20918. var invertUV = options.invertUV || false;
  20919. var updatable = options.updatable;
  20920. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20921. var instance = options.instance;
  20922. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  20923. // tube geometry
  20924. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20925. var tangents = path3D.getTangents();
  20926. var normals = path3D.getNormals();
  20927. var distances = path3D.getDistances();
  20928. var pi2 = Math.PI * 2;
  20929. var step = pi2 / tessellation * arc;
  20930. var returnRadius = function () { return radius; };
  20931. var radiusFunctionFinal = radiusFunction || returnRadius;
  20932. var circlePath;
  20933. var rad;
  20934. var normal;
  20935. var rotated;
  20936. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20937. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20938. for (var i = 0; i < path.length; i++) {
  20939. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20940. circlePath = Array(); // current circle array
  20941. normal = normals[i]; // current normal
  20942. for (var t = 0; t < tessellation; t++) {
  20943. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20944. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20945. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20946. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20947. circlePath[t] = rotated;
  20948. }
  20949. circlePaths[index] = circlePath;
  20950. index++;
  20951. }
  20952. // cap
  20953. var capPath = function (nbPoints, pathIndex) {
  20954. var pointCap = Array();
  20955. for (var i = 0; i < nbPoints; i++) {
  20956. pointCap.push(path[pathIndex]);
  20957. }
  20958. return pointCap;
  20959. };
  20960. switch (cap) {
  20961. case BABYLON.Mesh.NO_CAP:
  20962. break;
  20963. case BABYLON.Mesh.CAP_START:
  20964. circlePaths[0] = capPath(tessellation, 0);
  20965. circlePaths[1] = circlePaths[2].slice(0);
  20966. break;
  20967. case BABYLON.Mesh.CAP_END:
  20968. circlePaths[index] = circlePaths[index - 1].slice(0);
  20969. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20970. break;
  20971. case BABYLON.Mesh.CAP_ALL:
  20972. circlePaths[0] = capPath(tessellation, 0);
  20973. circlePaths[1] = circlePaths[2].slice(0);
  20974. circlePaths[index] = circlePaths[index - 1].slice(0);
  20975. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20976. break;
  20977. default:
  20978. break;
  20979. }
  20980. return circlePaths;
  20981. };
  20982. var path3D;
  20983. var pathArray;
  20984. if (instance) {
  20985. var arc = options.arc || instance.arc;
  20986. path3D = (instance.path3D).update(path);
  20987. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20988. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20989. instance.path3D = path3D;
  20990. instance.pathArray = pathArray;
  20991. instance.arc = arc;
  20992. return instance;
  20993. }
  20994. // tube creation
  20995. path3D = new BABYLON.Path3D(path);
  20996. var newPathArray = new Array();
  20997. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20998. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20999. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21000. tube.pathArray = pathArray;
  21001. tube.path3D = path3D;
  21002. tube.tessellation = tessellation;
  21003. tube.cap = cap;
  21004. tube.arc = options.arc;
  21005. return tube;
  21006. };
  21007. /**
  21008. * Creates a polyhedron mesh.
  21009. *
  21010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21011. * 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
  21012. * to choose the wanted type.
  21013. * The parameter `size` (positive float, default 1) sets the polygon size.
  21014. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21015. * 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`.
  21016. * 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
  21017. * 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)`).
  21018. * 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
  21019. * 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.
  21020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21023. */
  21024. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21025. var polyhedron = new BABYLON.Mesh(name, scene);
  21026. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21027. vertexData.applyToMesh(polyhedron, options.updatable);
  21028. return polyhedron;
  21029. };
  21030. /**
  21031. * Creates a decal mesh.
  21032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21033. * 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.
  21034. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21035. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21036. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21037. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21038. */
  21039. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21040. var indices = sourceMesh.getIndices();
  21041. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21042. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21043. var position = options.position || BABYLON.Vector3.Zero();
  21044. var normal = options.normal || BABYLON.Vector3.Up();
  21045. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21046. var angle = options.angle || 0;
  21047. // Getting correct rotation
  21048. if (!normal) {
  21049. var target = new BABYLON.Vector3(0, 0, 1);
  21050. var camera = sourceMesh.getScene().activeCamera;
  21051. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21052. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21053. }
  21054. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21055. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21056. var pitch = Math.atan2(normal.y, len);
  21057. // Matrix
  21058. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21059. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21060. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21061. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21062. var vertexData = new BABYLON.VertexData();
  21063. vertexData.indices = [];
  21064. vertexData.positions = [];
  21065. vertexData.normals = [];
  21066. vertexData.uvs = [];
  21067. var currentVertexDataIndex = 0;
  21068. var extractDecalVector3 = function (indexId) {
  21069. var vertexId = indices[indexId];
  21070. var result = new BABYLON.PositionNormalVertex();
  21071. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21072. // Send vector to decal local world
  21073. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21074. // Get normal
  21075. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21076. return result;
  21077. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21078. var clip = function (vertices, axis) {
  21079. if (vertices.length === 0) {
  21080. return vertices;
  21081. }
  21082. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21083. var clipVertices = function (v0, v1) {
  21084. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21085. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21086. };
  21087. var result = new Array();
  21088. for (var index = 0; index < vertices.length; index += 3) {
  21089. var v1Out;
  21090. var v2Out;
  21091. var v3Out;
  21092. var total = 0;
  21093. var nV1, nV2, nV3, nV4;
  21094. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21095. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21096. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21097. v1Out = d1 > 0;
  21098. v2Out = d2 > 0;
  21099. v3Out = d3 > 0;
  21100. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21101. switch (total) {
  21102. case 0:
  21103. result.push(vertices[index]);
  21104. result.push(vertices[index + 1]);
  21105. result.push(vertices[index + 2]);
  21106. break;
  21107. case 1:
  21108. if (v1Out) {
  21109. nV1 = vertices[index + 1];
  21110. nV2 = vertices[index + 2];
  21111. nV3 = clipVertices(vertices[index], nV1);
  21112. nV4 = clipVertices(vertices[index], nV2);
  21113. }
  21114. if (v2Out) {
  21115. nV1 = vertices[index];
  21116. nV2 = vertices[index + 2];
  21117. nV3 = clipVertices(vertices[index + 1], nV1);
  21118. nV4 = clipVertices(vertices[index + 1], nV2);
  21119. result.push(nV3);
  21120. result.push(nV2.clone());
  21121. result.push(nV1.clone());
  21122. result.push(nV2.clone());
  21123. result.push(nV3.clone());
  21124. result.push(nV4);
  21125. break;
  21126. }
  21127. if (v3Out) {
  21128. nV1 = vertices[index];
  21129. nV2 = vertices[index + 1];
  21130. nV3 = clipVertices(vertices[index + 2], nV1);
  21131. nV4 = clipVertices(vertices[index + 2], nV2);
  21132. }
  21133. result.push(nV1.clone());
  21134. result.push(nV2.clone());
  21135. result.push(nV3);
  21136. result.push(nV4);
  21137. result.push(nV3.clone());
  21138. result.push(nV2.clone());
  21139. break;
  21140. case 2:
  21141. if (!v1Out) {
  21142. nV1 = vertices[index].clone();
  21143. nV2 = clipVertices(nV1, vertices[index + 1]);
  21144. nV3 = clipVertices(nV1, vertices[index + 2]);
  21145. result.push(nV1);
  21146. result.push(nV2);
  21147. result.push(nV3);
  21148. }
  21149. if (!v2Out) {
  21150. nV1 = vertices[index + 1].clone();
  21151. nV2 = clipVertices(nV1, vertices[index + 2]);
  21152. nV3 = clipVertices(nV1, vertices[index]);
  21153. result.push(nV1);
  21154. result.push(nV2);
  21155. result.push(nV3);
  21156. }
  21157. if (!v3Out) {
  21158. nV1 = vertices[index + 2].clone();
  21159. nV2 = clipVertices(nV1, vertices[index]);
  21160. nV3 = clipVertices(nV1, vertices[index + 1]);
  21161. result.push(nV1);
  21162. result.push(nV2);
  21163. result.push(nV3);
  21164. }
  21165. break;
  21166. case 3:
  21167. break;
  21168. }
  21169. }
  21170. return result;
  21171. };
  21172. for (var index = 0; index < indices.length; index += 3) {
  21173. var faceVertices = new Array();
  21174. faceVertices.push(extractDecalVector3(index));
  21175. faceVertices.push(extractDecalVector3(index + 1));
  21176. faceVertices.push(extractDecalVector3(index + 2));
  21177. // Clip
  21178. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21179. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21180. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21181. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21182. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21183. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21184. if (faceVertices.length === 0) {
  21185. continue;
  21186. }
  21187. // Add UVs and get back to world
  21188. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21189. var vertex = faceVertices[vIndex];
  21190. //TODO check for Int32Array
  21191. vertexData.indices.push(currentVertexDataIndex);
  21192. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21193. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21194. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21195. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21196. currentVertexDataIndex++;
  21197. }
  21198. }
  21199. // Return mesh
  21200. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21201. vertexData.applyToMesh(decal);
  21202. decal.position = position.clone();
  21203. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21204. return decal;
  21205. };
  21206. // Privates
  21207. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21208. // extrusion geometry
  21209. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21210. var tangents = path3D.getTangents();
  21211. var normals = path3D.getNormals();
  21212. var binormals = path3D.getBinormals();
  21213. var distances = path3D.getDistances();
  21214. var angle = 0;
  21215. var returnScale = function () { return scale; };
  21216. var returnRotation = function () { return rotation; };
  21217. var rotate = custom ? rotateFunction : returnRotation;
  21218. var scl = custom ? scaleFunction : returnScale;
  21219. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21220. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21221. for (var i = 0; i < curve.length; i++) {
  21222. var shapePath = new Array();
  21223. var angleStep = rotate(i, distances[i]);
  21224. var scaleRatio = scl(i, distances[i]);
  21225. for (var p = 0; p < shape.length; p++) {
  21226. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21227. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21228. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21229. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21230. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21231. shapePath[p] = rotated;
  21232. }
  21233. shapePaths[index] = shapePath;
  21234. angle += angleStep;
  21235. index++;
  21236. }
  21237. // cap
  21238. var capPath = function (shapePath) {
  21239. var pointCap = Array();
  21240. var barycenter = BABYLON.Vector3.Zero();
  21241. var i;
  21242. for (i = 0; i < shapePath.length; i++) {
  21243. barycenter.addInPlace(shapePath[i]);
  21244. }
  21245. barycenter.scaleInPlace(1 / shapePath.length);
  21246. for (i = 0; i < shapePath.length; i++) {
  21247. pointCap.push(barycenter);
  21248. }
  21249. return pointCap;
  21250. };
  21251. switch (cap) {
  21252. case BABYLON.Mesh.NO_CAP:
  21253. break;
  21254. case BABYLON.Mesh.CAP_START:
  21255. shapePaths[0] = capPath(shapePaths[2]);
  21256. shapePaths[1] = shapePaths[2].slice(0);
  21257. break;
  21258. case BABYLON.Mesh.CAP_END:
  21259. shapePaths[index] = shapePaths[index - 1];
  21260. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21261. break;
  21262. case BABYLON.Mesh.CAP_ALL:
  21263. shapePaths[0] = capPath(shapePaths[2]);
  21264. shapePaths[1] = shapePaths[2].slice(0);
  21265. shapePaths[index] = shapePaths[index - 1];
  21266. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21267. break;
  21268. default:
  21269. break;
  21270. }
  21271. return shapePaths;
  21272. };
  21273. var path3D;
  21274. var pathArray;
  21275. if (instance) {
  21276. path3D = (instance.path3D).update(curve);
  21277. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21278. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21279. return instance;
  21280. }
  21281. // extruded shape creation
  21282. path3D = new BABYLON.Path3D(curve);
  21283. var newShapePaths = new Array();
  21284. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21285. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21286. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21287. extrudedGeneric.pathArray = pathArray;
  21288. extrudedGeneric.path3D = path3D;
  21289. extrudedGeneric.cap = cap;
  21290. return extrudedGeneric;
  21291. };
  21292. return MeshBuilder;
  21293. })();
  21294. BABYLON.MeshBuilder = MeshBuilder;
  21295. })(BABYLON || (BABYLON = {}));
  21296. var BABYLON;
  21297. (function (BABYLON) {
  21298. var BaseTexture = (function () {
  21299. function BaseTexture(scene) {
  21300. this.hasAlpha = false;
  21301. this.getAlphaFromRGB = false;
  21302. this.level = 1;
  21303. this.coordinatesIndex = 0;
  21304. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21305. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21306. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21307. this.anisotropicFilteringLevel = 4;
  21308. this.isCube = false;
  21309. this.isRenderTarget = false;
  21310. this.animations = new Array();
  21311. /**
  21312. * An event triggered when the texture is disposed.
  21313. * @type {BABYLON.Observable}
  21314. */
  21315. this.onDisposeObservable = new BABYLON.Observable();
  21316. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21317. this._scene = scene;
  21318. this._scene.textures.push(this);
  21319. }
  21320. BaseTexture.prototype.toString = function () {
  21321. return this.name;
  21322. };
  21323. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21324. set: function (callback) {
  21325. if (this._onDisposeObserver) {
  21326. this.onDisposeObservable.remove(this._onDisposeObserver);
  21327. }
  21328. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21329. },
  21330. enumerable: true,
  21331. configurable: true
  21332. });
  21333. BaseTexture.prototype.getScene = function () {
  21334. return this._scene;
  21335. };
  21336. BaseTexture.prototype.getTextureMatrix = function () {
  21337. return null;
  21338. };
  21339. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21340. return null;
  21341. };
  21342. BaseTexture.prototype.getInternalTexture = function () {
  21343. return this._texture;
  21344. };
  21345. BaseTexture.prototype.isReady = function () {
  21346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21347. return true;
  21348. }
  21349. if (this._texture) {
  21350. return this._texture.isReady;
  21351. }
  21352. return false;
  21353. };
  21354. BaseTexture.prototype.getSize = function () {
  21355. if (this._texture._width) {
  21356. return new BABYLON.Size(this._texture._width, this._texture._height);
  21357. }
  21358. if (this._texture._size) {
  21359. return new BABYLON.Size(this._texture._size, this._texture._size);
  21360. }
  21361. return BABYLON.Size.Zero();
  21362. };
  21363. BaseTexture.prototype.getBaseSize = function () {
  21364. if (!this.isReady() || !this._texture)
  21365. return BABYLON.Size.Zero();
  21366. if (this._texture._size) {
  21367. return new BABYLON.Size(this._texture._size, this._texture._size);
  21368. }
  21369. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  21370. };
  21371. BaseTexture.prototype.scale = function (ratio) {
  21372. };
  21373. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21374. get: function () {
  21375. return false;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21381. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21382. for (var index = 0; index < texturesCache.length; index++) {
  21383. var texturesCacheEntry = texturesCache[index];
  21384. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21385. texturesCache.splice(index, 1);
  21386. return;
  21387. }
  21388. }
  21389. };
  21390. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21391. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21392. for (var index = 0; index < texturesCache.length; index++) {
  21393. var texturesCacheEntry = texturesCache[index];
  21394. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21395. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21396. texturesCacheEntry.references++;
  21397. return texturesCacheEntry;
  21398. }
  21399. }
  21400. }
  21401. return null;
  21402. };
  21403. BaseTexture.prototype.delayLoad = function () {
  21404. };
  21405. BaseTexture.prototype.clone = function () {
  21406. return null;
  21407. };
  21408. BaseTexture.prototype.releaseInternalTexture = function () {
  21409. if (this._texture) {
  21410. this._scene.getEngine().releaseInternalTexture(this._texture);
  21411. delete this._texture;
  21412. }
  21413. };
  21414. BaseTexture.prototype.dispose = function () {
  21415. // Animations
  21416. this.getScene().stopAnimation(this);
  21417. // Remove from scene
  21418. var index = this._scene.textures.indexOf(this);
  21419. if (index >= 0) {
  21420. this._scene.textures.splice(index, 1);
  21421. }
  21422. if (this._texture === undefined) {
  21423. return;
  21424. }
  21425. // Release
  21426. this.releaseInternalTexture();
  21427. // Callback
  21428. this.onDisposeObservable.notifyObservers(this);
  21429. this.onDisposeObservable.clear();
  21430. };
  21431. BaseTexture.prototype.serialize = function () {
  21432. if (!this.name) {
  21433. return null;
  21434. }
  21435. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21436. // Animations
  21437. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21438. return serializationObject;
  21439. };
  21440. __decorate([
  21441. BABYLON.serialize()
  21442. ], BaseTexture.prototype, "name", void 0);
  21443. __decorate([
  21444. BABYLON.serialize()
  21445. ], BaseTexture.prototype, "hasAlpha", void 0);
  21446. __decorate([
  21447. BABYLON.serialize()
  21448. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21449. __decorate([
  21450. BABYLON.serialize()
  21451. ], BaseTexture.prototype, "level", void 0);
  21452. __decorate([
  21453. BABYLON.serialize()
  21454. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21455. __decorate([
  21456. BABYLON.serialize()
  21457. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21458. __decorate([
  21459. BABYLON.serialize()
  21460. ], BaseTexture.prototype, "wrapU", void 0);
  21461. __decorate([
  21462. BABYLON.serialize()
  21463. ], BaseTexture.prototype, "wrapV", void 0);
  21464. __decorate([
  21465. BABYLON.serialize()
  21466. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21467. __decorate([
  21468. BABYLON.serialize()
  21469. ], BaseTexture.prototype, "isCube", void 0);
  21470. __decorate([
  21471. BABYLON.serialize()
  21472. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21473. return BaseTexture;
  21474. })();
  21475. BABYLON.BaseTexture = BaseTexture;
  21476. })(BABYLON || (BABYLON = {}));
  21477. var BABYLON;
  21478. (function (BABYLON) {
  21479. var Texture = (function (_super) {
  21480. __extends(Texture, _super);
  21481. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21482. var _this = this;
  21483. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21484. if (onLoad === void 0) { onLoad = null; }
  21485. if (onError === void 0) { onError = null; }
  21486. if (buffer === void 0) { buffer = null; }
  21487. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21488. _super.call(this, scene);
  21489. this.uOffset = 0;
  21490. this.vOffset = 0;
  21491. this.uScale = 1.0;
  21492. this.vScale = 1.0;
  21493. this.uAng = 0;
  21494. this.vAng = 0;
  21495. this.wAng = 0;
  21496. this.name = url;
  21497. this.url = url;
  21498. this._noMipmap = noMipmap;
  21499. this._invertY = invertY;
  21500. this._samplingMode = samplingMode;
  21501. this._buffer = buffer;
  21502. this._deleteBuffer = deleteBuffer;
  21503. if (!url) {
  21504. return;
  21505. }
  21506. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21507. var load = function () {
  21508. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  21509. _this.onLoadObservable.notifyObservers(true);
  21510. }
  21511. if (onLoad) {
  21512. onLoad();
  21513. }
  21514. };
  21515. if (!this._texture) {
  21516. if (!scene.useDelayedTextureLoading) {
  21517. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  21518. if (deleteBuffer) {
  21519. delete this._buffer;
  21520. }
  21521. }
  21522. else {
  21523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21524. this._delayedOnLoad = load;
  21525. this._delayedOnError = onError;
  21526. }
  21527. }
  21528. else {
  21529. BABYLON.Tools.SetImmediate(function () { return load(); });
  21530. }
  21531. }
  21532. Object.defineProperty(Texture.prototype, "noMipmap", {
  21533. get: function () {
  21534. return this._noMipmap;
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Texture.prototype.delayLoad = function () {
  21540. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21541. return;
  21542. }
  21543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21544. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21545. if (!this._texture) {
  21546. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21547. if (this._deleteBuffer) {
  21548. delete this._buffer;
  21549. }
  21550. }
  21551. };
  21552. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21553. if (!this._texture) {
  21554. return;
  21555. }
  21556. this._samplingMode = samplingMode;
  21557. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21558. };
  21559. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21560. x *= this.uScale;
  21561. y *= this.vScale;
  21562. x -= 0.5 * this.uScale;
  21563. y -= 0.5 * this.vScale;
  21564. z -= 0.5;
  21565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21566. t.x += 0.5 * this.uScale + this.uOffset;
  21567. t.y += 0.5 * this.vScale + this.vOffset;
  21568. t.z += 0.5;
  21569. };
  21570. Texture.prototype.getTextureMatrix = function () {
  21571. if (this.uOffset === this._cachedUOffset &&
  21572. this.vOffset === this._cachedVOffset &&
  21573. this.uScale === this._cachedUScale &&
  21574. this.vScale === this._cachedVScale &&
  21575. this.uAng === this._cachedUAng &&
  21576. this.vAng === this._cachedVAng &&
  21577. this.wAng === this._cachedWAng) {
  21578. return this._cachedTextureMatrix;
  21579. }
  21580. this._cachedUOffset = this.uOffset;
  21581. this._cachedVOffset = this.vOffset;
  21582. this._cachedUScale = this.uScale;
  21583. this._cachedVScale = this.vScale;
  21584. this._cachedUAng = this.uAng;
  21585. this._cachedVAng = this.vAng;
  21586. this._cachedWAng = this.wAng;
  21587. if (!this._cachedTextureMatrix) {
  21588. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21589. this._rowGenerationMatrix = new BABYLON.Matrix();
  21590. this._t0 = BABYLON.Vector3.Zero();
  21591. this._t1 = BABYLON.Vector3.Zero();
  21592. this._t2 = BABYLON.Vector3.Zero();
  21593. }
  21594. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21595. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21596. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21597. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21598. this._t1.subtractInPlace(this._t0);
  21599. this._t2.subtractInPlace(this._t0);
  21600. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21601. this._cachedTextureMatrix.m[0] = this._t1.x;
  21602. this._cachedTextureMatrix.m[1] = this._t1.y;
  21603. this._cachedTextureMatrix.m[2] = this._t1.z;
  21604. this._cachedTextureMatrix.m[4] = this._t2.x;
  21605. this._cachedTextureMatrix.m[5] = this._t2.y;
  21606. this._cachedTextureMatrix.m[6] = this._t2.z;
  21607. this._cachedTextureMatrix.m[8] = this._t0.x;
  21608. this._cachedTextureMatrix.m[9] = this._t0.y;
  21609. this._cachedTextureMatrix.m[10] = this._t0.z;
  21610. return this._cachedTextureMatrix;
  21611. };
  21612. Texture.prototype.getReflectionTextureMatrix = function () {
  21613. if (this.uOffset === this._cachedUOffset &&
  21614. this.vOffset === this._cachedVOffset &&
  21615. this.uScale === this._cachedUScale &&
  21616. this.vScale === this._cachedVScale &&
  21617. this.coordinatesMode === this._cachedCoordinatesMode) {
  21618. return this._cachedTextureMatrix;
  21619. }
  21620. if (!this._cachedTextureMatrix) {
  21621. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21622. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21623. }
  21624. this._cachedCoordinatesMode = this.coordinatesMode;
  21625. switch (this.coordinatesMode) {
  21626. case Texture.PLANAR_MODE:
  21627. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21628. this._cachedTextureMatrix[0] = this.uScale;
  21629. this._cachedTextureMatrix[5] = this.vScale;
  21630. this._cachedTextureMatrix[12] = this.uOffset;
  21631. this._cachedTextureMatrix[13] = this.vOffset;
  21632. break;
  21633. case Texture.PROJECTION_MODE:
  21634. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21635. this._projectionModeMatrix.m[0] = 0.5;
  21636. this._projectionModeMatrix.m[5] = -0.5;
  21637. this._projectionModeMatrix.m[10] = 0.0;
  21638. this._projectionModeMatrix.m[12] = 0.5;
  21639. this._projectionModeMatrix.m[13] = 0.5;
  21640. this._projectionModeMatrix.m[14] = 1.0;
  21641. this._projectionModeMatrix.m[15] = 1.0;
  21642. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21643. break;
  21644. default:
  21645. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21646. break;
  21647. }
  21648. return this._cachedTextureMatrix;
  21649. };
  21650. Texture.prototype.clone = function () {
  21651. var _this = this;
  21652. return BABYLON.SerializationHelper.Clone(function () {
  21653. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21654. }, this);
  21655. };
  21656. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21657. get: function () {
  21658. if (!this._onLoadObservarble) {
  21659. this._onLoadObservarble = new BABYLON.Observable();
  21660. }
  21661. return this._onLoadObservarble;
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. // Statics
  21667. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21668. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21669. if (onLoad === void 0) { onLoad = null; }
  21670. if (onError === void 0) { onError = null; }
  21671. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21672. };
  21673. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21674. if (parsedTexture.isCube) {
  21675. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21676. }
  21677. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21678. return null;
  21679. }
  21680. var texture = BABYLON.SerializationHelper.Parse(function () {
  21681. if (parsedTexture.mirrorPlane) {
  21682. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21683. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21684. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21685. return mirrorTexture;
  21686. }
  21687. else if (parsedTexture.isRenderTarget) {
  21688. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21689. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21690. return renderTargetTexture;
  21691. }
  21692. else {
  21693. var texture;
  21694. if (parsedTexture.base64String) {
  21695. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21696. }
  21697. else {
  21698. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21699. }
  21700. return texture;
  21701. }
  21702. }, parsedTexture, scene);
  21703. // Animations
  21704. if (parsedTexture.animations) {
  21705. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21706. var parsedAnimation = parsedTexture.animations[animationIndex];
  21707. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21708. }
  21709. }
  21710. return texture;
  21711. };
  21712. // Constants
  21713. Texture.NEAREST_SAMPLINGMODE = 1;
  21714. Texture.BILINEAR_SAMPLINGMODE = 2;
  21715. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21716. Texture.EXPLICIT_MODE = 0;
  21717. Texture.SPHERICAL_MODE = 1;
  21718. Texture.PLANAR_MODE = 2;
  21719. Texture.CUBIC_MODE = 3;
  21720. Texture.PROJECTION_MODE = 4;
  21721. Texture.SKYBOX_MODE = 5;
  21722. Texture.INVCUBIC_MODE = 6;
  21723. Texture.EQUIRECTANGULAR_MODE = 7;
  21724. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21725. Texture.CLAMP_ADDRESSMODE = 0;
  21726. Texture.WRAP_ADDRESSMODE = 1;
  21727. Texture.MIRROR_ADDRESSMODE = 2;
  21728. __decorate([
  21729. BABYLON.serialize()
  21730. ], Texture.prototype, "url", void 0);
  21731. __decorate([
  21732. BABYLON.serialize()
  21733. ], Texture.prototype, "uOffset", void 0);
  21734. __decorate([
  21735. BABYLON.serialize()
  21736. ], Texture.prototype, "vOffset", void 0);
  21737. __decorate([
  21738. BABYLON.serialize()
  21739. ], Texture.prototype, "uScale", void 0);
  21740. __decorate([
  21741. BABYLON.serialize()
  21742. ], Texture.prototype, "vScale", void 0);
  21743. __decorate([
  21744. BABYLON.serialize()
  21745. ], Texture.prototype, "uAng", void 0);
  21746. __decorate([
  21747. BABYLON.serialize()
  21748. ], Texture.prototype, "vAng", void 0);
  21749. __decorate([
  21750. BABYLON.serialize()
  21751. ], Texture.prototype, "wAng", void 0);
  21752. return Texture;
  21753. })(BABYLON.BaseTexture);
  21754. BABYLON.Texture = Texture;
  21755. })(BABYLON || (BABYLON = {}));
  21756. var BABYLON;
  21757. (function (BABYLON) {
  21758. var CubeTexture = (function (_super) {
  21759. __extends(CubeTexture, _super);
  21760. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21761. _super.call(this, scene);
  21762. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21763. this.name = rootUrl;
  21764. this.url = rootUrl;
  21765. this._noMipmap = noMipmap;
  21766. this.hasAlpha = false;
  21767. if (!rootUrl && !files) {
  21768. return;
  21769. }
  21770. this._texture = this._getFromCache(rootUrl, noMipmap);
  21771. if (!files) {
  21772. if (!extensions) {
  21773. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21774. }
  21775. files = [];
  21776. for (var index = 0; index < extensions.length; index++) {
  21777. files.push(rootUrl + extensions[index]);
  21778. }
  21779. this._extensions = extensions;
  21780. }
  21781. this._files = files;
  21782. if (!this._texture) {
  21783. if (!scene.useDelayedTextureLoading) {
  21784. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21785. }
  21786. else {
  21787. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21788. }
  21789. }
  21790. this.isCube = true;
  21791. this._textureMatrix = BABYLON.Matrix.Identity();
  21792. }
  21793. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21794. return new CubeTexture("", scene, null, noMipmap, files);
  21795. };
  21796. // Methods
  21797. CubeTexture.prototype.delayLoad = function () {
  21798. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21799. return;
  21800. }
  21801. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21802. this._texture = this._getFromCache(this.url, this._noMipmap);
  21803. if (!this._texture) {
  21804. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  21805. }
  21806. };
  21807. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21808. return this._textureMatrix;
  21809. };
  21810. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21811. var texture = BABYLON.SerializationHelper.Parse(function () {
  21812. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21813. }, parsedTexture, scene);
  21814. // Animations
  21815. if (parsedTexture.animations) {
  21816. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21817. var parsedAnimation = parsedTexture.animations[animationIndex];
  21818. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21819. }
  21820. }
  21821. return texture;
  21822. };
  21823. CubeTexture.prototype.clone = function () {
  21824. var _this = this;
  21825. return BABYLON.SerializationHelper.Clone(function () {
  21826. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21827. }, this);
  21828. };
  21829. return CubeTexture;
  21830. })(BABYLON.BaseTexture);
  21831. BABYLON.CubeTexture = CubeTexture;
  21832. })(BABYLON || (BABYLON = {}));
  21833. var BABYLON;
  21834. (function (BABYLON) {
  21835. var RenderTargetTexture = (function (_super) {
  21836. __extends(RenderTargetTexture, _super);
  21837. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  21838. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21839. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21840. if (isCube === void 0) { isCube = false; }
  21841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21842. _super.call(this, null, scene, !generateMipMaps);
  21843. this.isCube = isCube;
  21844. /**
  21845. * Use this list to define the list of mesh you want to render.
  21846. */
  21847. this.renderList = new Array();
  21848. this.renderParticles = true;
  21849. this.renderSprites = false;
  21850. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21851. // Events
  21852. /**
  21853. * An event triggered when the texture is unbind.
  21854. * @type {BABYLON.Observable}
  21855. */
  21856. this.onAfterUnbindObservable = new BABYLON.Observable();
  21857. /**
  21858. * An event triggered before rendering the texture
  21859. * @type {BABYLON.Observable}
  21860. */
  21861. this.onBeforeRenderObservable = new BABYLON.Observable();
  21862. /**
  21863. * An event triggered after rendering the texture
  21864. * @type {BABYLON.Observable}
  21865. */
  21866. this.onAfterRenderObservable = new BABYLON.Observable();
  21867. /**
  21868. * An event triggered after the texture clear
  21869. * @type {BABYLON.Observable}
  21870. */
  21871. this.onClearObservable = new BABYLON.Observable();
  21872. this._currentRefreshId = -1;
  21873. this._refreshRate = 1;
  21874. this.name = name;
  21875. this.isRenderTarget = true;
  21876. this._size = size;
  21877. this._generateMipMaps = generateMipMaps;
  21878. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21879. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  21880. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21881. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21882. }
  21883. if (isCube) {
  21884. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  21885. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21886. this._textureMatrix = BABYLON.Matrix.Identity();
  21887. }
  21888. else {
  21889. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  21890. }
  21891. // Rendering groups
  21892. this._renderingManager = new BABYLON.RenderingManager(scene);
  21893. }
  21894. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21895. get: function () {
  21896. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21902. get: function () {
  21903. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21909. get: function () {
  21910. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21916. set: function (callback) {
  21917. if (this._onAfterUnbindObserver) {
  21918. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21919. }
  21920. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21926. set: function (callback) {
  21927. if (this._onBeforeRenderObserver) {
  21928. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21929. }
  21930. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21936. set: function (callback) {
  21937. if (this._onAfterRenderObserver) {
  21938. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21939. }
  21940. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21946. set: function (callback) {
  21947. if (this._onClearObserver) {
  21948. this.onClearObservable.remove(this._onClearObserver);
  21949. }
  21950. this._onClearObserver = this.onClearObservable.add(callback);
  21951. },
  21952. enumerable: true,
  21953. configurable: true
  21954. });
  21955. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21956. this._currentRefreshId = -1;
  21957. };
  21958. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21959. get: function () {
  21960. return this._refreshRate;
  21961. },
  21962. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21963. set: function (value) {
  21964. this._refreshRate = value;
  21965. this.resetRefreshCounter();
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. RenderTargetTexture.prototype._shouldRender = function () {
  21971. if (this._currentRefreshId === -1) {
  21972. this._currentRefreshId = 1;
  21973. return true;
  21974. }
  21975. if (this.refreshRate === this._currentRefreshId) {
  21976. this._currentRefreshId = 1;
  21977. return true;
  21978. }
  21979. this._currentRefreshId++;
  21980. return false;
  21981. };
  21982. RenderTargetTexture.prototype.isReady = function () {
  21983. if (!this.getScene().renderTargetsEnabled) {
  21984. return false;
  21985. }
  21986. return _super.prototype.isReady.call(this);
  21987. };
  21988. RenderTargetTexture.prototype.getRenderSize = function () {
  21989. return this._size;
  21990. };
  21991. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21992. get: function () {
  21993. return true;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. RenderTargetTexture.prototype.scale = function (ratio) {
  21999. var newSize = this._size * ratio;
  22000. this.resize(newSize, this._generateMipMaps);
  22001. };
  22002. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22003. if (this.isCube) {
  22004. return this._textureMatrix;
  22005. }
  22006. return _super.prototype.getReflectionTextureMatrix.call(this);
  22007. };
  22008. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22009. this.releaseInternalTexture();
  22010. if (this.isCube) {
  22011. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22012. }
  22013. else {
  22014. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22015. }
  22016. };
  22017. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22018. var scene = this.getScene();
  22019. if (this.useCameraPostProcesses !== undefined) {
  22020. useCameraPostProcess = this.useCameraPostProcesses;
  22021. }
  22022. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22023. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22024. }
  22025. if (this._waitingRenderList) {
  22026. this.renderList = [];
  22027. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22028. var id = this._waitingRenderList[index];
  22029. this.renderList.push(scene.getMeshByID(id));
  22030. }
  22031. delete this._waitingRenderList;
  22032. }
  22033. // Is predicate defined?
  22034. if (this.renderListPredicate) {
  22035. this.renderList.splice(0); // Clear previous renderList
  22036. var sceneMeshes = this.getScene().meshes;
  22037. for (var index = 0; index < sceneMeshes.length; index++) {
  22038. var mesh = sceneMeshes[index];
  22039. if (this.renderListPredicate(mesh)) {
  22040. this.renderList.push(mesh);
  22041. }
  22042. }
  22043. }
  22044. if (this.renderList && this.renderList.length === 0) {
  22045. return;
  22046. }
  22047. // Prepare renderingManager
  22048. this._renderingManager.reset();
  22049. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22050. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22051. var sceneRenderId = scene.getRenderId();
  22052. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22053. var mesh = currentRenderList[meshIndex];
  22054. if (mesh) {
  22055. if (!mesh.isReady()) {
  22056. // Reset _currentRefreshId
  22057. this.resetRefreshCounter();
  22058. continue;
  22059. }
  22060. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22061. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22062. mesh._activate(sceneRenderId);
  22063. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22064. var subMesh = mesh.subMeshes[subIndex];
  22065. scene._activeIndices.addCount(subMesh.indexCount, false);
  22066. this._renderingManager.dispatch(subMesh);
  22067. }
  22068. }
  22069. }
  22070. }
  22071. if (this.isCube) {
  22072. for (var face = 0; face < 6; face++) {
  22073. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22074. scene.incrementRenderId();
  22075. scene.resetCachedMaterial();
  22076. }
  22077. }
  22078. else {
  22079. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22080. }
  22081. this.onAfterUnbindObservable.notifyObservers(this);
  22082. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22083. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22084. }
  22085. scene.resetCachedMaterial();
  22086. };
  22087. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22088. var scene = this.getScene();
  22089. var engine = scene.getEngine();
  22090. // Bind
  22091. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22092. if (this.isCube) {
  22093. engine.bindFramebuffer(this._texture, faceIndex);
  22094. }
  22095. else {
  22096. engine.bindFramebuffer(this._texture);
  22097. }
  22098. }
  22099. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22100. // Clear
  22101. if (this.onClearObservable.hasObservers()) {
  22102. this.onClearObservable.notifyObservers(engine);
  22103. }
  22104. else {
  22105. engine.clear(scene.clearColor, true, true);
  22106. }
  22107. if (!this._doNotChangeAspectRatio) {
  22108. scene.updateTransformMatrix(true);
  22109. }
  22110. // Render
  22111. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22112. if (useCameraPostProcess) {
  22113. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22114. }
  22115. if (!this._doNotChangeAspectRatio) {
  22116. scene.updateTransformMatrix(true);
  22117. }
  22118. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22119. // Dump ?
  22120. if (dumpForDebug) {
  22121. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22122. }
  22123. // Unbind
  22124. if (!this.isCube || faceIndex === 5) {
  22125. if (this.isCube) {
  22126. if (faceIndex === 5) {
  22127. engine.generateMipMapsForCubemap(this._texture);
  22128. }
  22129. }
  22130. engine.unBindFramebuffer(this._texture, this.isCube);
  22131. }
  22132. };
  22133. RenderTargetTexture.prototype.clone = function () {
  22134. var textureSize = this.getSize();
  22135. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22136. // Base texture
  22137. newTexture.hasAlpha = this.hasAlpha;
  22138. newTexture.level = this.level;
  22139. // RenderTarget Texture
  22140. newTexture.coordinatesMode = this.coordinatesMode;
  22141. newTexture.renderList = this.renderList.slice(0);
  22142. return newTexture;
  22143. };
  22144. RenderTargetTexture.prototype.serialize = function () {
  22145. if (!this.name) {
  22146. return null;
  22147. }
  22148. var serializationObject = _super.prototype.serialize.call(this);
  22149. serializationObject.renderTargetSize = this.getRenderSize();
  22150. serializationObject.renderList = [];
  22151. for (var index = 0; index < this.renderList.length; index++) {
  22152. serializationObject.renderList.push(this.renderList[index].id);
  22153. }
  22154. return serializationObject;
  22155. };
  22156. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22157. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22158. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22159. return RenderTargetTexture;
  22160. })(BABYLON.Texture);
  22161. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22162. })(BABYLON || (BABYLON = {}));
  22163. var BABYLON;
  22164. (function (BABYLON) {
  22165. var ProceduralTexture = (function (_super) {
  22166. __extends(ProceduralTexture, _super);
  22167. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22169. if (isCube === void 0) { isCube = false; }
  22170. _super.call(this, null, scene, !generateMipMaps);
  22171. this.isCube = isCube;
  22172. this.isEnabled = true;
  22173. this._currentRefreshId = -1;
  22174. this._refreshRate = 1;
  22175. this._vertexBuffers = {};
  22176. this._uniforms = new Array();
  22177. this._samplers = new Array();
  22178. this._textures = new Array();
  22179. this._floats = new Array();
  22180. this._floatsArrays = {};
  22181. this._colors3 = new Array();
  22182. this._colors4 = new Array();
  22183. this._vectors2 = new Array();
  22184. this._vectors3 = new Array();
  22185. this._matrices = new Array();
  22186. this._fallbackTextureUsed = false;
  22187. scene._proceduralTextures.push(this);
  22188. this.name = name;
  22189. this.isRenderTarget = true;
  22190. this._size = size;
  22191. this._generateMipMaps = generateMipMaps;
  22192. this.setFragment(fragment);
  22193. this._fallbackTexture = fallbackTexture;
  22194. var engine = scene.getEngine();
  22195. if (isCube) {
  22196. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22197. this.setFloat("face", 0);
  22198. }
  22199. else {
  22200. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22201. }
  22202. // VBO
  22203. var vertices = [];
  22204. vertices.push(1, 1);
  22205. vertices.push(-1, 1);
  22206. vertices.push(-1, -1);
  22207. vertices.push(1, -1);
  22208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22209. // Indices
  22210. var indices = [];
  22211. indices.push(0);
  22212. indices.push(1);
  22213. indices.push(2);
  22214. indices.push(0);
  22215. indices.push(2);
  22216. indices.push(3);
  22217. this._indexBuffer = engine.createIndexBuffer(indices);
  22218. }
  22219. ProceduralTexture.prototype.reset = function () {
  22220. if (this._effect === undefined) {
  22221. return;
  22222. }
  22223. var engine = this.getScene().getEngine();
  22224. engine._releaseEffect(this._effect);
  22225. };
  22226. ProceduralTexture.prototype.isReady = function () {
  22227. var _this = this;
  22228. var engine = this.getScene().getEngine();
  22229. var shaders;
  22230. if (!this._fragment) {
  22231. return false;
  22232. }
  22233. if (this._fallbackTextureUsed) {
  22234. return true;
  22235. }
  22236. if (this._fragment.fragmentElement !== undefined) {
  22237. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22238. }
  22239. else {
  22240. shaders = { vertex: "procedural", fragment: this._fragment };
  22241. }
  22242. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22243. _this.releaseInternalTexture();
  22244. if (_this._fallbackTexture) {
  22245. _this._texture = _this._fallbackTexture._texture;
  22246. _this._texture.references++;
  22247. }
  22248. _this._fallbackTextureUsed = true;
  22249. });
  22250. return this._effect.isReady();
  22251. };
  22252. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22253. this._currentRefreshId = -1;
  22254. };
  22255. ProceduralTexture.prototype.setFragment = function (fragment) {
  22256. this._fragment = fragment;
  22257. };
  22258. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22259. get: function () {
  22260. return this._refreshRate;
  22261. },
  22262. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22263. set: function (value) {
  22264. this._refreshRate = value;
  22265. this.resetRefreshCounter();
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. ProceduralTexture.prototype._shouldRender = function () {
  22271. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22272. return false;
  22273. }
  22274. if (this._fallbackTextureUsed) {
  22275. return false;
  22276. }
  22277. if (this._currentRefreshId === -1) {
  22278. this._currentRefreshId = 1;
  22279. return true;
  22280. }
  22281. if (this.refreshRate === this._currentRefreshId) {
  22282. this._currentRefreshId = 1;
  22283. return true;
  22284. }
  22285. this._currentRefreshId++;
  22286. return false;
  22287. };
  22288. ProceduralTexture.prototype.getRenderSize = function () {
  22289. return this._size;
  22290. };
  22291. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22292. if (this._fallbackTextureUsed) {
  22293. return;
  22294. }
  22295. this.releaseInternalTexture();
  22296. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22297. };
  22298. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22299. if (this._uniforms.indexOf(uniformName) === -1) {
  22300. this._uniforms.push(uniformName);
  22301. }
  22302. };
  22303. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22304. if (this._samplers.indexOf(name) === -1) {
  22305. this._samplers.push(name);
  22306. }
  22307. this._textures[name] = texture;
  22308. return this;
  22309. };
  22310. ProceduralTexture.prototype.setFloat = function (name, value) {
  22311. this._checkUniform(name);
  22312. this._floats[name] = value;
  22313. return this;
  22314. };
  22315. ProceduralTexture.prototype.setFloats = function (name, value) {
  22316. this._checkUniform(name);
  22317. this._floatsArrays[name] = value;
  22318. return this;
  22319. };
  22320. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22321. this._checkUniform(name);
  22322. this._colors3[name] = value;
  22323. return this;
  22324. };
  22325. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22326. this._checkUniform(name);
  22327. this._colors4[name] = value;
  22328. return this;
  22329. };
  22330. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22331. this._checkUniform(name);
  22332. this._vectors2[name] = value;
  22333. return this;
  22334. };
  22335. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22336. this._checkUniform(name);
  22337. this._vectors3[name] = value;
  22338. return this;
  22339. };
  22340. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22341. this._checkUniform(name);
  22342. this._matrices[name] = value;
  22343. return this;
  22344. };
  22345. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22346. var scene = this.getScene();
  22347. var engine = scene.getEngine();
  22348. // Render
  22349. engine.enableEffect(this._effect);
  22350. engine.setState(false);
  22351. // Texture
  22352. for (var name in this._textures) {
  22353. this._effect.setTexture(name, this._textures[name]);
  22354. }
  22355. // Float
  22356. for (name in this._floats) {
  22357. this._effect.setFloat(name, this._floats[name]);
  22358. }
  22359. // Floats
  22360. for (name in this._floatsArrays) {
  22361. this._effect.setArray(name, this._floatsArrays[name]);
  22362. }
  22363. // Color3
  22364. for (name in this._colors3) {
  22365. this._effect.setColor3(name, this._colors3[name]);
  22366. }
  22367. // Color4
  22368. for (name in this._colors4) {
  22369. var color = this._colors4[name];
  22370. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22371. }
  22372. // Vector2
  22373. for (name in this._vectors2) {
  22374. this._effect.setVector2(name, this._vectors2[name]);
  22375. }
  22376. // Vector3
  22377. for (name in this._vectors3) {
  22378. this._effect.setVector3(name, this._vectors3[name]);
  22379. }
  22380. // Matrix
  22381. for (name in this._matrices) {
  22382. this._effect.setMatrix(name, this._matrices[name]);
  22383. }
  22384. // VBOs
  22385. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22386. if (this.isCube) {
  22387. for (var face = 0; face < 6; face++) {
  22388. engine.bindFramebuffer(this._texture, face);
  22389. this._effect.setFloat("face", face);
  22390. // Clear
  22391. engine.clear(scene.clearColor, true, true);
  22392. // Draw order
  22393. engine.draw(true, 0, 6);
  22394. // Mipmaps
  22395. if (face === 5) {
  22396. engine.generateMipMapsForCubemap(this._texture);
  22397. }
  22398. }
  22399. }
  22400. else {
  22401. engine.bindFramebuffer(this._texture);
  22402. // Clear
  22403. engine.clear(scene.clearColor, true, true);
  22404. // Draw order
  22405. engine.draw(true, 0, 6);
  22406. }
  22407. // Unbind
  22408. engine.unBindFramebuffer(this._texture, this.isCube);
  22409. if (this.onGenerated) {
  22410. this.onGenerated();
  22411. }
  22412. };
  22413. ProceduralTexture.prototype.clone = function () {
  22414. var textureSize = this.getSize();
  22415. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22416. // Base texture
  22417. newTexture.hasAlpha = this.hasAlpha;
  22418. newTexture.level = this.level;
  22419. // RenderTarget Texture
  22420. newTexture.coordinatesMode = this.coordinatesMode;
  22421. return newTexture;
  22422. };
  22423. ProceduralTexture.prototype.dispose = function () {
  22424. var index = this.getScene()._proceduralTextures.indexOf(this);
  22425. if (index >= 0) {
  22426. this.getScene()._proceduralTextures.splice(index, 1);
  22427. }
  22428. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22429. if (vertexBuffer) {
  22430. vertexBuffer.dispose();
  22431. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22432. }
  22433. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22434. this._indexBuffer = null;
  22435. }
  22436. _super.prototype.dispose.call(this);
  22437. };
  22438. return ProceduralTexture;
  22439. })(BABYLON.Texture);
  22440. BABYLON.ProceduralTexture = ProceduralTexture;
  22441. })(BABYLON || (BABYLON = {}));
  22442. var BABYLON;
  22443. (function (BABYLON) {
  22444. var MirrorTexture = (function (_super) {
  22445. __extends(MirrorTexture, _super);
  22446. function MirrorTexture(name, size, scene, generateMipMaps) {
  22447. var _this = this;
  22448. _super.call(this, name, size, scene, generateMipMaps, true);
  22449. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22450. this._transformMatrix = BABYLON.Matrix.Zero();
  22451. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22452. this.onBeforeRenderObservable.add(function () {
  22453. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22454. _this._savedViewMatrix = scene.getViewMatrix();
  22455. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22456. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22457. scene.clipPlane = _this.mirrorPlane;
  22458. scene.getEngine().cullBackFaces = false;
  22459. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22460. });
  22461. this.onAfterRenderObservable.add(function () {
  22462. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22463. scene.getEngine().cullBackFaces = true;
  22464. scene._mirroredCameraPosition = null;
  22465. delete scene.clipPlane;
  22466. });
  22467. }
  22468. MirrorTexture.prototype.clone = function () {
  22469. var textureSize = this.getSize();
  22470. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22471. // Base texture
  22472. newTexture.hasAlpha = this.hasAlpha;
  22473. newTexture.level = this.level;
  22474. // Mirror Texture
  22475. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22476. newTexture.renderList = this.renderList.slice(0);
  22477. return newTexture;
  22478. };
  22479. MirrorTexture.prototype.serialize = function () {
  22480. if (!this.name) {
  22481. return null;
  22482. }
  22483. var serializationObject = _super.prototype.serialize.call(this);
  22484. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22485. return serializationObject;
  22486. };
  22487. return MirrorTexture;
  22488. })(BABYLON.RenderTargetTexture);
  22489. BABYLON.MirrorTexture = MirrorTexture;
  22490. })(BABYLON || (BABYLON = {}));
  22491. var BABYLON;
  22492. (function (BABYLON) {
  22493. /**
  22494. * Creates a refraction texture used by refraction channel of the standard material.
  22495. * @param name the texture name
  22496. * @param size size of the underlying texture
  22497. * @param scene root scene
  22498. */
  22499. var RefractionTexture = (function (_super) {
  22500. __extends(RefractionTexture, _super);
  22501. function RefractionTexture(name, size, scene, generateMipMaps) {
  22502. var _this = this;
  22503. _super.call(this, name, size, scene, generateMipMaps, true);
  22504. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22505. this.depth = 2.0;
  22506. this.onBeforeRenderObservable.add(function () {
  22507. scene.clipPlane = _this.refractionPlane;
  22508. });
  22509. this.onAfterRenderObservable.add(function () {
  22510. delete scene.clipPlane;
  22511. });
  22512. }
  22513. RefractionTexture.prototype.clone = function () {
  22514. var textureSize = this.getSize();
  22515. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22516. // Base texture
  22517. newTexture.hasAlpha = this.hasAlpha;
  22518. newTexture.level = this.level;
  22519. // Refraction Texture
  22520. newTexture.refractionPlane = this.refractionPlane.clone();
  22521. newTexture.renderList = this.renderList.slice(0);
  22522. newTexture.depth = this.depth;
  22523. return newTexture;
  22524. };
  22525. RefractionTexture.prototype.serialize = function () {
  22526. if (!this.name) {
  22527. return null;
  22528. }
  22529. var serializationObject = _super.prototype.serialize.call(this);
  22530. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22531. serializationObject.depth = this.depth;
  22532. return serializationObject;
  22533. };
  22534. return RefractionTexture;
  22535. })(BABYLON.RenderTargetTexture);
  22536. BABYLON.RefractionTexture = RefractionTexture;
  22537. })(BABYLON || (BABYLON = {}));
  22538. var BABYLON;
  22539. (function (BABYLON) {
  22540. var DynamicTexture = (function (_super) {
  22541. __extends(DynamicTexture, _super);
  22542. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22543. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22544. _super.call(this, null, scene, !generateMipMaps);
  22545. this.name = name;
  22546. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22547. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22548. this._generateMipMaps = generateMipMaps;
  22549. if (options.getContext) {
  22550. this._canvas = options;
  22551. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22552. }
  22553. else {
  22554. this._canvas = document.createElement("canvas");
  22555. if (options.width) {
  22556. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22557. }
  22558. else {
  22559. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22560. }
  22561. }
  22562. var textureSize = this.getSize();
  22563. this._canvas.width = textureSize.width;
  22564. this._canvas.height = textureSize.height;
  22565. this._context = this._canvas.getContext("2d");
  22566. }
  22567. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22568. get: function () {
  22569. return true;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. DynamicTexture.prototype.scale = function (ratio) {
  22575. var textureSize = this.getSize();
  22576. textureSize.width *= ratio;
  22577. textureSize.height *= ratio;
  22578. this._canvas.width = textureSize.width;
  22579. this._canvas.height = textureSize.height;
  22580. this.releaseInternalTexture();
  22581. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22582. };
  22583. DynamicTexture.prototype.getContext = function () {
  22584. return this._context;
  22585. };
  22586. DynamicTexture.prototype.clear = function () {
  22587. var size = this.getSize();
  22588. this._context.fillRect(0, 0, size.width, size.height);
  22589. };
  22590. DynamicTexture.prototype.update = function (invertY) {
  22591. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22592. };
  22593. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22594. if (update === void 0) { update = true; }
  22595. var size = this.getSize();
  22596. if (clearColor) {
  22597. this._context.fillStyle = clearColor;
  22598. this._context.fillRect(0, 0, size.width, size.height);
  22599. }
  22600. this._context.font = font;
  22601. if (x === null) {
  22602. var textSize = this._context.measureText(text);
  22603. x = (size.width - textSize.width) / 2;
  22604. }
  22605. this._context.fillStyle = color;
  22606. this._context.fillText(text, x, y);
  22607. if (update) {
  22608. this.update(invertY);
  22609. }
  22610. };
  22611. DynamicTexture.prototype.clone = function () {
  22612. var textureSize = this.getSize();
  22613. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22614. // Base texture
  22615. newTexture.hasAlpha = this.hasAlpha;
  22616. newTexture.level = this.level;
  22617. // Dynamic Texture
  22618. newTexture.wrapU = this.wrapU;
  22619. newTexture.wrapV = this.wrapV;
  22620. return newTexture;
  22621. };
  22622. return DynamicTexture;
  22623. })(BABYLON.Texture);
  22624. BABYLON.DynamicTexture = DynamicTexture;
  22625. })(BABYLON || (BABYLON = {}));
  22626. var BABYLON;
  22627. (function (BABYLON) {
  22628. var VideoTexture = (function (_super) {
  22629. __extends(VideoTexture, _super);
  22630. /**
  22631. * Creates a video texture.
  22632. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22633. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22634. * @param {BABYLON.Scene} scene is obviously the current scene.
  22635. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22636. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22637. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22638. */
  22639. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22640. var _this = this;
  22641. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22642. if (invertY === void 0) { invertY = false; }
  22643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22644. _super.call(this, null, scene, !generateMipMaps, invertY);
  22645. this._autoLaunch = true;
  22646. var urls;
  22647. this.name = name;
  22648. if (urlsOrVideo instanceof HTMLVideoElement) {
  22649. this.video = urlsOrVideo;
  22650. }
  22651. else {
  22652. urls = urlsOrVideo;
  22653. this.video = document.createElement("video");
  22654. this.video.autoplay = false;
  22655. this.video.loop = true;
  22656. }
  22657. this._generateMipMaps = generateMipMaps;
  22658. this._samplingMode = samplingMode;
  22659. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22660. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22661. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22662. }
  22663. else {
  22664. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22665. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22666. this._generateMipMaps = false;
  22667. }
  22668. if (urls) {
  22669. this.video.addEventListener("canplaythrough", function () {
  22670. _this._createTexture();
  22671. });
  22672. urls.forEach(function (url) {
  22673. var source = document.createElement("source");
  22674. source.src = url;
  22675. _this.video.appendChild(source);
  22676. });
  22677. }
  22678. else {
  22679. this._createTexture();
  22680. }
  22681. this._lastUpdate = BABYLON.Tools.Now;
  22682. }
  22683. VideoTexture.prototype._createTexture = function () {
  22684. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22685. this._texture.isReady = true;
  22686. };
  22687. VideoTexture.prototype.update = function () {
  22688. if (this._autoLaunch) {
  22689. this._autoLaunch = false;
  22690. this.video.play();
  22691. }
  22692. var now = BABYLON.Tools.Now;
  22693. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22694. return false;
  22695. }
  22696. this._lastUpdate = now;
  22697. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22698. return true;
  22699. };
  22700. return VideoTexture;
  22701. })(BABYLON.Texture);
  22702. BABYLON.VideoTexture = VideoTexture;
  22703. })(BABYLON || (BABYLON = {}));
  22704. var BABYLON;
  22705. (function (BABYLON) {
  22706. var CustomProceduralTexture = (function (_super) {
  22707. __extends(CustomProceduralTexture, _super);
  22708. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22709. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22710. this._animate = true;
  22711. this._time = 0;
  22712. this._texturePath = texturePath;
  22713. //Try to load json
  22714. this.loadJson(texturePath);
  22715. this.refreshRate = 1;
  22716. }
  22717. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22718. var _this = this;
  22719. var that = this;
  22720. function noConfigFile() {
  22721. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22722. try {
  22723. that.setFragment(that._texturePath);
  22724. }
  22725. catch (ex) {
  22726. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22727. }
  22728. }
  22729. var configFileUrl = jsonUrl + "/config.json";
  22730. var xhr = new XMLHttpRequest();
  22731. xhr.open("GET", configFileUrl, true);
  22732. xhr.addEventListener("load", function () {
  22733. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22734. try {
  22735. _this._config = JSON.parse(xhr.response);
  22736. _this.updateShaderUniforms();
  22737. _this.updateTextures();
  22738. _this.setFragment(_this._texturePath + "/custom");
  22739. _this._animate = _this._config.animate;
  22740. _this.refreshRate = _this._config.refreshrate;
  22741. }
  22742. catch (ex) {
  22743. noConfigFile();
  22744. }
  22745. }
  22746. else {
  22747. noConfigFile();
  22748. }
  22749. }, false);
  22750. xhr.addEventListener("error", function () {
  22751. noConfigFile();
  22752. }, false);
  22753. try {
  22754. xhr.send();
  22755. }
  22756. catch (ex) {
  22757. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22758. }
  22759. };
  22760. CustomProceduralTexture.prototype.isReady = function () {
  22761. if (!_super.prototype.isReady.call(this)) {
  22762. return false;
  22763. }
  22764. for (var name in this._textures) {
  22765. var texture = this._textures[name];
  22766. if (!texture.isReady()) {
  22767. return false;
  22768. }
  22769. }
  22770. return true;
  22771. };
  22772. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22773. if (this._animate) {
  22774. this._time += this.getScene().getAnimationRatio() * 0.03;
  22775. this.updateShaderUniforms();
  22776. }
  22777. _super.prototype.render.call(this, useCameraPostProcess);
  22778. };
  22779. CustomProceduralTexture.prototype.updateTextures = function () {
  22780. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22781. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22782. }
  22783. };
  22784. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22785. if (this._config) {
  22786. for (var j = 0; j < this._config.uniforms.length; j++) {
  22787. var uniform = this._config.uniforms[j];
  22788. switch (uniform.type) {
  22789. case "float":
  22790. this.setFloat(uniform.name, uniform.value);
  22791. break;
  22792. case "color3":
  22793. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22794. break;
  22795. case "color4":
  22796. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22797. break;
  22798. case "vector2":
  22799. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22800. break;
  22801. case "vector3":
  22802. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22803. break;
  22804. }
  22805. }
  22806. }
  22807. this.setFloat("time", this._time);
  22808. };
  22809. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22810. get: function () {
  22811. return this._animate;
  22812. },
  22813. set: function (value) {
  22814. this._animate = value;
  22815. },
  22816. enumerable: true,
  22817. configurable: true
  22818. });
  22819. return CustomProceduralTexture;
  22820. })(BABYLON.ProceduralTexture);
  22821. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22822. })(BABYLON || (BABYLON = {}));
  22823. var BABYLON;
  22824. (function (BABYLON) {
  22825. var EffectFallbacks = (function () {
  22826. function EffectFallbacks() {
  22827. this._defines = {};
  22828. this._currentRank = 32;
  22829. this._maxRank = -1;
  22830. }
  22831. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22832. if (!this._defines[rank]) {
  22833. if (rank < this._currentRank) {
  22834. this._currentRank = rank;
  22835. }
  22836. if (rank > this._maxRank) {
  22837. this._maxRank = rank;
  22838. }
  22839. this._defines[rank] = new Array();
  22840. }
  22841. this._defines[rank].push(define);
  22842. };
  22843. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22844. this._meshRank = rank;
  22845. this._mesh = mesh;
  22846. if (rank > this._maxRank) {
  22847. this._maxRank = rank;
  22848. }
  22849. };
  22850. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22851. get: function () {
  22852. return this._currentRank <= this._maxRank;
  22853. },
  22854. enumerable: true,
  22855. configurable: true
  22856. });
  22857. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22858. var currentFallbacks = this._defines[this._currentRank];
  22859. for (var index = 0; index < currentFallbacks.length; index++) {
  22860. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22861. }
  22862. if (this._mesh && this._currentRank === this._meshRank) {
  22863. this._mesh.computeBonesUsingShaders = false;
  22864. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22865. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22866. }
  22867. this._currentRank++;
  22868. return currentDefines;
  22869. };
  22870. return EffectFallbacks;
  22871. })();
  22872. BABYLON.EffectFallbacks = EffectFallbacks;
  22873. var Effect = (function () {
  22874. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22875. var _this = this;
  22876. this._isReady = false;
  22877. this._compilationError = "";
  22878. this._valueCache = {};
  22879. this._engine = engine;
  22880. this.name = baseName;
  22881. this.defines = defines;
  22882. this._uniformsNames = uniformsNames.concat(samplers);
  22883. this._samplers = samplers;
  22884. this._attributesNames = attributesNames;
  22885. this.onError = onError;
  22886. this.onCompiled = onCompiled;
  22887. this._indexParameters = indexParameters;
  22888. var vertexSource;
  22889. var fragmentSource;
  22890. if (baseName.vertexElement) {
  22891. vertexSource = document.getElementById(baseName.vertexElement);
  22892. if (!vertexSource) {
  22893. vertexSource = baseName.vertexElement;
  22894. }
  22895. }
  22896. else {
  22897. vertexSource = baseName.vertex || baseName;
  22898. }
  22899. if (baseName.fragmentElement) {
  22900. fragmentSource = document.getElementById(baseName.fragmentElement);
  22901. if (!fragmentSource) {
  22902. fragmentSource = baseName.fragmentElement;
  22903. }
  22904. }
  22905. else {
  22906. fragmentSource = baseName.fragment || baseName;
  22907. }
  22908. this._loadVertexShader(vertexSource, function (vertexCode) {
  22909. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22910. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22911. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22912. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22913. });
  22914. });
  22915. });
  22916. });
  22917. }
  22918. // Properties
  22919. Effect.prototype.isReady = function () {
  22920. return this._isReady;
  22921. };
  22922. Effect.prototype.getProgram = function () {
  22923. return this._program;
  22924. };
  22925. Effect.prototype.getAttributesNames = function () {
  22926. return this._attributesNames;
  22927. };
  22928. Effect.prototype.getAttributeLocation = function (index) {
  22929. return this._attributes[index];
  22930. };
  22931. Effect.prototype.getAttributeLocationByName = function (name) {
  22932. var index = this._attributesNames.indexOf(name);
  22933. return this._attributes[index];
  22934. };
  22935. Effect.prototype.getAttributesCount = function () {
  22936. return this._attributes.length;
  22937. };
  22938. Effect.prototype.getUniformIndex = function (uniformName) {
  22939. return this._uniformsNames.indexOf(uniformName);
  22940. };
  22941. Effect.prototype.getUniform = function (uniformName) {
  22942. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22943. };
  22944. Effect.prototype.getSamplers = function () {
  22945. return this._samplers;
  22946. };
  22947. Effect.prototype.getCompilationError = function () {
  22948. return this._compilationError;
  22949. };
  22950. // Methods
  22951. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22952. // DOM element ?
  22953. if (vertex instanceof HTMLElement) {
  22954. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22955. callback(vertexCode);
  22956. return;
  22957. }
  22958. // Is in local store ?
  22959. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22960. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22961. return;
  22962. }
  22963. var vertexShaderUrl;
  22964. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22965. vertexShaderUrl = vertex;
  22966. }
  22967. else {
  22968. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22969. }
  22970. // Vertex shader
  22971. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22972. };
  22973. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22974. // DOM element ?
  22975. if (fragment instanceof HTMLElement) {
  22976. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22977. callback(fragmentCode);
  22978. return;
  22979. }
  22980. // Is in local store ?
  22981. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22982. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22983. return;
  22984. }
  22985. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22986. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22987. return;
  22988. }
  22989. var fragmentShaderUrl;
  22990. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22991. fragmentShaderUrl = fragment;
  22992. }
  22993. else {
  22994. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22995. }
  22996. // Fragment shader
  22997. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22998. };
  22999. Effect.prototype._dumpShadersName = function () {
  23000. if (this.name.vertexElement) {
  23001. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23002. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23003. }
  23004. else if (this.name.vertex) {
  23005. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23006. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23007. }
  23008. else {
  23009. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23010. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23011. }
  23012. };
  23013. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23014. var _this = this;
  23015. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23016. var match = regex.exec(sourceCode);
  23017. var returnValue = new String(sourceCode);
  23018. while (match != null) {
  23019. var includeFile = match[1];
  23020. if (Effect.IncludesShadersStore[includeFile]) {
  23021. // Substitution
  23022. var includeContent = Effect.IncludesShadersStore[includeFile];
  23023. if (match[2]) {
  23024. var splits = match[3].split(",");
  23025. for (var index = 0; index < splits.length; index += 2) {
  23026. var source = new RegExp(splits[index], "g");
  23027. var dest = splits[index + 1];
  23028. includeContent = includeContent.replace(source, dest);
  23029. }
  23030. }
  23031. if (match[4]) {
  23032. var indexString = match[5];
  23033. if (indexString.indexOf("..") !== -1) {
  23034. var indexSplits = indexString.split("..");
  23035. var minIndex = parseInt(indexSplits[0]);
  23036. var maxIndex = parseInt(indexSplits[1]);
  23037. var sourceIncludeContent = includeContent.slice(0);
  23038. includeContent = "";
  23039. if (isNaN(maxIndex)) {
  23040. maxIndex = this._indexParameters[indexSplits[1]];
  23041. }
  23042. for (var i = minIndex; i <= maxIndex; i++) {
  23043. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23044. }
  23045. }
  23046. else {
  23047. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23048. }
  23049. }
  23050. // Replace
  23051. returnValue = returnValue.replace(match[0], includeContent);
  23052. }
  23053. else {
  23054. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23055. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23056. Effect.IncludesShadersStore[includeFile] = fileContent;
  23057. _this._processIncludes(returnValue, callback);
  23058. });
  23059. return;
  23060. }
  23061. match = regex.exec(sourceCode);
  23062. }
  23063. callback(returnValue);
  23064. };
  23065. Effect.prototype._processPrecision = function (source) {
  23066. if (source.indexOf("precision highp float") === -1) {
  23067. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23068. source = "precision mediump float;\n" + source;
  23069. }
  23070. else {
  23071. source = "precision highp float;\n" + source;
  23072. }
  23073. }
  23074. else {
  23075. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23076. source = source.replace("precision highp float", "precision mediump float");
  23077. }
  23078. }
  23079. return source;
  23080. };
  23081. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23082. try {
  23083. var engine = this._engine;
  23084. // Precision
  23085. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23086. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23087. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23088. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23089. this._attributes = engine.getAttributes(this._program, attributesNames);
  23090. var index;
  23091. for (index = 0; index < this._samplers.length; index++) {
  23092. var sampler = this.getUniform(this._samplers[index]);
  23093. if (sampler == null) {
  23094. this._samplers.splice(index, 1);
  23095. index--;
  23096. }
  23097. }
  23098. engine.bindSamplers(this);
  23099. this._isReady = true;
  23100. if (this.onCompiled) {
  23101. this.onCompiled(this);
  23102. }
  23103. }
  23104. catch (e) {
  23105. // Let's go through fallbacks then
  23106. if (fallbacks && fallbacks.isMoreFallbacks) {
  23107. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23108. this._dumpShadersName();
  23109. defines = fallbacks.reduce(defines);
  23110. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23111. }
  23112. else {
  23113. BABYLON.Tools.Error("Unable to compile effect: ");
  23114. this._dumpShadersName();
  23115. BABYLON.Tools.Error("Defines: " + defines);
  23116. BABYLON.Tools.Error("Error: " + e.message);
  23117. this._compilationError = e.message;
  23118. if (this.onError) {
  23119. this.onError(this, this._compilationError);
  23120. }
  23121. }
  23122. }
  23123. };
  23124. Object.defineProperty(Effect.prototype, "isSupported", {
  23125. get: function () {
  23126. return this._compilationError === "";
  23127. },
  23128. enumerable: true,
  23129. configurable: true
  23130. });
  23131. Effect.prototype._bindTexture = function (channel, texture) {
  23132. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23133. };
  23134. Effect.prototype.setTexture = function (channel, texture) {
  23135. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23136. };
  23137. Effect.prototype.setTextureArray = function (channel, textures) {
  23138. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23139. var initialPos = this._samplers.indexOf(channel);
  23140. for (var index = 1; index < textures.length; index++) {
  23141. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23142. }
  23143. }
  23144. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23145. };
  23146. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23147. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23148. };
  23149. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23150. var changed = false;
  23151. var cache = this._valueCache[uniformName];
  23152. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23153. changed = true;
  23154. cache = new BABYLON.Matrix();
  23155. }
  23156. var tm = cache.m;
  23157. var om = matrix.m;
  23158. for (var index = 0; index < 16; index++) {
  23159. if (tm[index] !== om[index]) {
  23160. tm[index] = om[index];
  23161. changed = true;
  23162. }
  23163. }
  23164. this._valueCache[uniformName] = cache;
  23165. return changed;
  23166. };
  23167. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23168. var cache = this._valueCache[uniformName];
  23169. if (!cache) {
  23170. cache = [x, y];
  23171. this._valueCache[uniformName] = cache;
  23172. return true;
  23173. }
  23174. var changed = false;
  23175. if (cache[0] !== x) {
  23176. cache[0] = x;
  23177. changed = true;
  23178. }
  23179. if (cache[1] !== y) {
  23180. cache[1] = y;
  23181. changed = true;
  23182. }
  23183. return changed;
  23184. };
  23185. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23186. var cache = this._valueCache[uniformName];
  23187. if (!cache) {
  23188. cache = [x, y, z];
  23189. this._valueCache[uniformName] = cache;
  23190. return true;
  23191. }
  23192. var changed = false;
  23193. if (cache[0] !== x) {
  23194. cache[0] = x;
  23195. changed = true;
  23196. }
  23197. if (cache[1] !== y) {
  23198. cache[1] = y;
  23199. changed = true;
  23200. }
  23201. if (cache[2] !== z) {
  23202. cache[2] = z;
  23203. changed = true;
  23204. }
  23205. return changed;
  23206. };
  23207. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23208. var cache = this._valueCache[uniformName];
  23209. if (!cache) {
  23210. cache = [x, y, z, w];
  23211. this._valueCache[uniformName] = cache;
  23212. return true;
  23213. }
  23214. var changed = false;
  23215. if (cache[0] !== x) {
  23216. cache[0] = x;
  23217. changed = true;
  23218. }
  23219. if (cache[1] !== y) {
  23220. cache[1] = y;
  23221. changed = true;
  23222. }
  23223. if (cache[2] !== z) {
  23224. cache[2] = z;
  23225. changed = true;
  23226. }
  23227. if (cache[3] !== w) {
  23228. cache[3] = w;
  23229. changed = true;
  23230. }
  23231. return changed;
  23232. };
  23233. Effect.prototype.setArray = function (uniformName, array) {
  23234. this._valueCache[uniformName] = null;
  23235. this._engine.setArray(this.getUniform(uniformName), array);
  23236. return this;
  23237. };
  23238. Effect.prototype.setArray2 = function (uniformName, array) {
  23239. this._valueCache[uniformName] = null;
  23240. this._engine.setArray2(this.getUniform(uniformName), array);
  23241. return this;
  23242. };
  23243. Effect.prototype.setArray3 = function (uniformName, array) {
  23244. this._valueCache[uniformName] = null;
  23245. this._engine.setArray3(this.getUniform(uniformName), array);
  23246. return this;
  23247. };
  23248. Effect.prototype.setArray4 = function (uniformName, array) {
  23249. this._valueCache[uniformName] = null;
  23250. this._engine.setArray4(this.getUniform(uniformName), array);
  23251. return this;
  23252. };
  23253. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23254. this._valueCache[uniformName] = null;
  23255. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23256. return this;
  23257. };
  23258. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23259. if (this._cacheMatrix(uniformName, matrix)) {
  23260. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23261. }
  23262. return this;
  23263. };
  23264. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23265. this._valueCache[uniformName] = null;
  23266. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23267. return this;
  23268. };
  23269. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23270. this._valueCache[uniformName] = null;
  23271. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23272. return this;
  23273. };
  23274. Effect.prototype.setFloat = function (uniformName, value) {
  23275. var cache = this._valueCache[uniformName];
  23276. if (cache !== undefined && cache === value)
  23277. return this;
  23278. this._valueCache[uniformName] = value;
  23279. this._engine.setFloat(this.getUniform(uniformName), value);
  23280. return this;
  23281. };
  23282. Effect.prototype.setBool = function (uniformName, bool) {
  23283. var cache = this._valueCache[uniformName];
  23284. if (cache !== undefined && cache === bool)
  23285. return this;
  23286. this._valueCache[uniformName] = bool;
  23287. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23288. return this;
  23289. };
  23290. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23291. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23292. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23293. }
  23294. return this;
  23295. };
  23296. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23297. if (this._cacheFloat2(uniformName, x, y)) {
  23298. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23299. }
  23300. return this;
  23301. };
  23302. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23303. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23304. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23305. }
  23306. return this;
  23307. };
  23308. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23309. if (this._cacheFloat3(uniformName, x, y, z)) {
  23310. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23311. }
  23312. return this;
  23313. };
  23314. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23315. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23316. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23317. }
  23318. return this;
  23319. };
  23320. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23321. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23322. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23323. }
  23324. return this;
  23325. };
  23326. Effect.prototype.setColor3 = function (uniformName, color3) {
  23327. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23328. this._engine.setColor3(this.getUniform(uniformName), color3);
  23329. }
  23330. return this;
  23331. };
  23332. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23333. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23334. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23335. }
  23336. return this;
  23337. };
  23338. // Statics
  23339. Effect.ShadersStore = {};
  23340. Effect.IncludesShadersStore = {};
  23341. return Effect;
  23342. })();
  23343. BABYLON.Effect = Effect;
  23344. })(BABYLON || (BABYLON = {}));
  23345. var BABYLON;
  23346. (function (BABYLON) {
  23347. var MaterialHelper = (function () {
  23348. function MaterialHelper() {
  23349. }
  23350. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23351. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23352. var lightIndex = 0;
  23353. var needNormals = false;
  23354. var needRebuild = false;
  23355. var needShadows = false;
  23356. for (var index = 0; index < scene.lights.length; index++) {
  23357. var light = scene.lights[index];
  23358. if (!light.isEnabled()) {
  23359. continue;
  23360. }
  23361. // Excluded check
  23362. if (light._excludedMeshesIds.length > 0) {
  23363. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23364. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23365. if (excludedMesh) {
  23366. light.excludedMeshes.push(excludedMesh);
  23367. }
  23368. }
  23369. light._excludedMeshesIds = [];
  23370. }
  23371. // Included check
  23372. if (light._includedOnlyMeshesIds.length > 0) {
  23373. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23374. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23375. if (includedOnlyMesh) {
  23376. light.includedOnlyMeshes.push(includedOnlyMesh);
  23377. }
  23378. }
  23379. light._includedOnlyMeshesIds = [];
  23380. }
  23381. if (!light.canAffectMesh(mesh)) {
  23382. continue;
  23383. }
  23384. needNormals = true;
  23385. if (defines["LIGHT" + lightIndex] === undefined) {
  23386. needRebuild = true;
  23387. }
  23388. defines["LIGHT" + lightIndex] = true;
  23389. var type;
  23390. if (light instanceof BABYLON.SpotLight) {
  23391. type = "SPOTLIGHT" + lightIndex;
  23392. }
  23393. else if (light instanceof BABYLON.HemisphericLight) {
  23394. type = "HEMILIGHT" + lightIndex;
  23395. }
  23396. else if (light instanceof BABYLON.PointLight) {
  23397. type = "POINTLIGHT" + lightIndex;
  23398. }
  23399. else {
  23400. type = "DIRLIGHT" + lightIndex;
  23401. }
  23402. if (defines[type] === undefined) {
  23403. needRebuild = true;
  23404. }
  23405. defines[type] = true;
  23406. // Specular
  23407. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23408. defines["SPECULARTERM"] = true;
  23409. }
  23410. // Shadows
  23411. if (scene.shadowsEnabled) {
  23412. var shadowGenerator = light.getShadowGenerator();
  23413. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23414. if (defines["SHADOW" + lightIndex] === undefined) {
  23415. needRebuild = true;
  23416. }
  23417. defines["SHADOW" + lightIndex] = true;
  23418. defines["SHADOWS"] = true;
  23419. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23420. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23421. needRebuild = true;
  23422. }
  23423. defines["SHADOWVSM" + lightIndex] = true;
  23424. }
  23425. if (shadowGenerator.usePoissonSampling) {
  23426. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23427. needRebuild = true;
  23428. }
  23429. defines["SHADOWPCF" + lightIndex] = true;
  23430. }
  23431. needShadows = true;
  23432. }
  23433. }
  23434. lightIndex++;
  23435. if (lightIndex === maxSimultaneousLights)
  23436. break;
  23437. }
  23438. if (needShadows && scene.getEngine().getCaps().textureFloat) {
  23439. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23440. needRebuild = true;
  23441. }
  23442. defines["SHADOWFULLFLOAT"] = true;
  23443. }
  23444. if (needRebuild) {
  23445. defines.rebuild();
  23446. }
  23447. return needNormals;
  23448. };
  23449. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23450. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23451. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23452. if (!defines["LIGHT" + lightIndex]) {
  23453. break;
  23454. }
  23455. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23456. samplersList.push("shadowSampler" + lightIndex);
  23457. }
  23458. };
  23459. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23460. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23461. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23462. if (!defines["LIGHT" + lightIndex]) {
  23463. break;
  23464. }
  23465. if (lightIndex > 0) {
  23466. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23467. }
  23468. if (defines["SHADOW" + lightIndex]) {
  23469. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23470. }
  23471. if (defines["SHADOWPCF" + lightIndex]) {
  23472. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23473. }
  23474. if (defines["SHADOWVSM" + lightIndex]) {
  23475. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23476. }
  23477. }
  23478. };
  23479. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23480. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23481. fallbacks.addCPUSkinningFallback(0, mesh);
  23482. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23483. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23484. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23487. }
  23488. }
  23489. };
  23490. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23491. if (defines["INSTANCES"]) {
  23492. attribs.push("world0");
  23493. attribs.push("world1");
  23494. attribs.push("world2");
  23495. attribs.push("world3");
  23496. }
  23497. };
  23498. // Bindings
  23499. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23500. var shadowGenerator = light.getShadowGenerator();
  23501. if (mesh.receiveShadows && shadowGenerator) {
  23502. if (!light.needCube()) {
  23503. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23504. }
  23505. else {
  23506. if (!depthValuesAlreadySet) {
  23507. depthValuesAlreadySet = true;
  23508. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23509. }
  23510. }
  23511. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23512. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23513. }
  23514. return depthValuesAlreadySet;
  23515. };
  23516. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23517. if (light instanceof BABYLON.PointLight) {
  23518. // Point Light
  23519. light.transferToEffect(effect, "vLightData" + lightIndex);
  23520. }
  23521. else if (light instanceof BABYLON.DirectionalLight) {
  23522. // Directional Light
  23523. light.transferToEffect(effect, "vLightData" + lightIndex);
  23524. }
  23525. else if (light instanceof BABYLON.SpotLight) {
  23526. // Spot Light
  23527. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23528. }
  23529. else if (light instanceof BABYLON.HemisphericLight) {
  23530. // Hemispheric Light
  23531. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23532. }
  23533. };
  23534. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23535. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23536. var lightIndex = 0;
  23537. var depthValuesAlreadySet = false;
  23538. for (var index = 0; index < scene.lights.length; index++) {
  23539. var light = scene.lights[index];
  23540. if (!light.isEnabled()) {
  23541. continue;
  23542. }
  23543. if (!light.canAffectMesh(mesh)) {
  23544. continue;
  23545. }
  23546. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23547. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23548. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23549. if (defines["SPECULARTERM"]) {
  23550. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23551. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23552. }
  23553. // Shadows
  23554. if (scene.shadowsEnabled) {
  23555. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23556. }
  23557. lightIndex++;
  23558. if (lightIndex === maxSimultaneousLights)
  23559. break;
  23560. }
  23561. };
  23562. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23563. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23564. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23565. effect.setColor3("vFogColor", scene.fogColor);
  23566. }
  23567. };
  23568. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23569. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23570. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23571. }
  23572. };
  23573. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23574. if (defines["LOGARITHMICDEPTH"]) {
  23575. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23576. }
  23577. };
  23578. MaterialHelper.BindClipPlane = function (effect, scene) {
  23579. if (scene.clipPlane) {
  23580. var clipPlane = scene.clipPlane;
  23581. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23582. }
  23583. };
  23584. return MaterialHelper;
  23585. })();
  23586. BABYLON.MaterialHelper = MaterialHelper;
  23587. })(BABYLON || (BABYLON = {}));
  23588. var BABYLON;
  23589. (function (BABYLON) {
  23590. var FresnelParameters = (function () {
  23591. function FresnelParameters() {
  23592. this.isEnabled = true;
  23593. this.leftColor = BABYLON.Color3.White();
  23594. this.rightColor = BABYLON.Color3.Black();
  23595. this.bias = 0;
  23596. this.power = 1;
  23597. }
  23598. FresnelParameters.prototype.clone = function () {
  23599. var newFresnelParameters = new FresnelParameters();
  23600. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23601. return new FresnelParameters;
  23602. };
  23603. FresnelParameters.prototype.serialize = function () {
  23604. var serializationObject = {};
  23605. serializationObject.isEnabled = this.isEnabled;
  23606. serializationObject.leftColor = this.leftColor;
  23607. serializationObject.rightColor = this.rightColor;
  23608. serializationObject.bias = this.bias;
  23609. serializationObject.power = this.power;
  23610. return serializationObject;
  23611. };
  23612. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23613. var fresnelParameters = new FresnelParameters();
  23614. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23615. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23616. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23617. fresnelParameters.bias = parsedFresnelParameters.bias;
  23618. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23619. return fresnelParameters;
  23620. };
  23621. return FresnelParameters;
  23622. })();
  23623. BABYLON.FresnelParameters = FresnelParameters;
  23624. })(BABYLON || (BABYLON = {}));
  23625. var BABYLON;
  23626. (function (BABYLON) {
  23627. var MaterialDefines = (function () {
  23628. function MaterialDefines() {
  23629. }
  23630. MaterialDefines.prototype.rebuild = function () {
  23631. if (this._keys) {
  23632. delete this._keys;
  23633. }
  23634. this._keys = Object.keys(this);
  23635. };
  23636. MaterialDefines.prototype.isEqual = function (other) {
  23637. if (this._keys.length !== other._keys.length) {
  23638. return false;
  23639. }
  23640. for (var index = 0; index < this._keys.length; index++) {
  23641. var prop = this._keys[index];
  23642. if (this[prop] !== other[prop]) {
  23643. return false;
  23644. }
  23645. }
  23646. return true;
  23647. };
  23648. MaterialDefines.prototype.cloneTo = function (other) {
  23649. if (this._keys.length !== other._keys.length) {
  23650. other._keys = this._keys.slice(0);
  23651. }
  23652. for (var index = 0; index < this._keys.length; index++) {
  23653. var prop = this._keys[index];
  23654. other[prop] = this[prop];
  23655. }
  23656. };
  23657. MaterialDefines.prototype.reset = function () {
  23658. for (var index = 0; index < this._keys.length; index++) {
  23659. var prop = this._keys[index];
  23660. if (typeof (this[prop]) === "number") {
  23661. this[prop] = 0;
  23662. }
  23663. else {
  23664. this[prop] = false;
  23665. }
  23666. }
  23667. };
  23668. MaterialDefines.prototype.toString = function () {
  23669. var result = "";
  23670. for (var index = 0; index < this._keys.length; index++) {
  23671. var prop = this._keys[index];
  23672. if (typeof (this[prop]) === "number") {
  23673. result += "#define " + prop + " " + this[prop] + "\n";
  23674. }
  23675. else if (this[prop]) {
  23676. result += "#define " + prop + "\n";
  23677. }
  23678. }
  23679. return result;
  23680. };
  23681. return MaterialDefines;
  23682. })();
  23683. BABYLON.MaterialDefines = MaterialDefines;
  23684. var Material = (function () {
  23685. function Material(name, scene, doNotAdd) {
  23686. this.name = name;
  23687. this.checkReadyOnEveryCall = false;
  23688. this.checkReadyOnlyOnce = false;
  23689. this.state = "";
  23690. this.alpha = 1.0;
  23691. this.backFaceCulling = true;
  23692. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23693. /**
  23694. * An event triggered when the material is disposed.
  23695. * @type {BABYLON.Observable}
  23696. */
  23697. this.onDisposeObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered when the material is compiled.
  23700. * @type {BABYLON.Observable}
  23701. */
  23702. this.onBindObservable = new BABYLON.Observable();
  23703. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23704. this.disableDepthWrite = false;
  23705. this.fogEnabled = true;
  23706. this.pointSize = 1.0;
  23707. this.zOffset = 0;
  23708. this._wasPreviouslyReady = false;
  23709. this._fillMode = Material.TriangleFillMode;
  23710. this.id = name;
  23711. this._scene = scene;
  23712. if (!doNotAdd) {
  23713. scene.materials.push(this);
  23714. }
  23715. }
  23716. Object.defineProperty(Material, "TriangleFillMode", {
  23717. get: function () {
  23718. return Material._TriangleFillMode;
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. Object.defineProperty(Material, "WireFrameFillMode", {
  23724. get: function () {
  23725. return Material._WireFrameFillMode;
  23726. },
  23727. enumerable: true,
  23728. configurable: true
  23729. });
  23730. Object.defineProperty(Material, "PointFillMode", {
  23731. get: function () {
  23732. return Material._PointFillMode;
  23733. },
  23734. enumerable: true,
  23735. configurable: true
  23736. });
  23737. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23738. get: function () {
  23739. return Material._ClockWiseSideOrientation;
  23740. },
  23741. enumerable: true,
  23742. configurable: true
  23743. });
  23744. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23745. get: function () {
  23746. return Material._CounterClockWiseSideOrientation;
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. Object.defineProperty(Material.prototype, "onDispose", {
  23752. set: function (callback) {
  23753. if (this._onDisposeObserver) {
  23754. this.onDisposeObservable.remove(this._onDisposeObserver);
  23755. }
  23756. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. Object.defineProperty(Material.prototype, "onBind", {
  23762. set: function (callback) {
  23763. if (this._onBindObserver) {
  23764. this.onBindObservable.remove(this._onBindObserver);
  23765. }
  23766. this._onBindObserver = this.onBindObservable.add(callback);
  23767. },
  23768. enumerable: true,
  23769. configurable: true
  23770. });
  23771. Object.defineProperty(Material.prototype, "wireframe", {
  23772. get: function () {
  23773. return this._fillMode === Material.WireFrameFillMode;
  23774. },
  23775. set: function (value) {
  23776. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23777. },
  23778. enumerable: true,
  23779. configurable: true
  23780. });
  23781. Object.defineProperty(Material.prototype, "pointsCloud", {
  23782. get: function () {
  23783. return this._fillMode === Material.PointFillMode;
  23784. },
  23785. set: function (value) {
  23786. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23787. },
  23788. enumerable: true,
  23789. configurable: true
  23790. });
  23791. Object.defineProperty(Material.prototype, "fillMode", {
  23792. get: function () {
  23793. return this._fillMode;
  23794. },
  23795. set: function (value) {
  23796. this._fillMode = value;
  23797. },
  23798. enumerable: true,
  23799. configurable: true
  23800. });
  23801. /**
  23802. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23803. * subclasses should override adding information pertainent to themselves
  23804. */
  23805. Material.prototype.toString = function (fullDetails) {
  23806. var ret = "Name: " + this.name;
  23807. if (fullDetails) {
  23808. }
  23809. return ret;
  23810. };
  23811. Object.defineProperty(Material.prototype, "isFrozen", {
  23812. get: function () {
  23813. return this.checkReadyOnlyOnce;
  23814. },
  23815. enumerable: true,
  23816. configurable: true
  23817. });
  23818. Material.prototype.freeze = function () {
  23819. this.checkReadyOnlyOnce = true;
  23820. };
  23821. Material.prototype.unfreeze = function () {
  23822. this.checkReadyOnlyOnce = false;
  23823. };
  23824. Material.prototype.isReady = function (mesh, useInstances) {
  23825. return true;
  23826. };
  23827. Material.prototype.getEffect = function () {
  23828. return this._effect;
  23829. };
  23830. Material.prototype.getScene = function () {
  23831. return this._scene;
  23832. };
  23833. Material.prototype.needAlphaBlending = function () {
  23834. return (this.alpha < 1.0);
  23835. };
  23836. Material.prototype.needAlphaTesting = function () {
  23837. return false;
  23838. };
  23839. Material.prototype.getAlphaTestTexture = function () {
  23840. return null;
  23841. };
  23842. Material.prototype.markDirty = function () {
  23843. this._wasPreviouslyReady = false;
  23844. };
  23845. Material.prototype._preBind = function () {
  23846. var engine = this._scene.getEngine();
  23847. engine.enableEffect(this._effect);
  23848. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23849. };
  23850. Material.prototype.bind = function (world, mesh) {
  23851. this._scene._cachedMaterial = this;
  23852. this.onBindObservable.notifyObservers(mesh);
  23853. if (this.disableDepthWrite) {
  23854. var engine = this._scene.getEngine();
  23855. this._cachedDepthWriteState = engine.getDepthWrite();
  23856. engine.setDepthWrite(false);
  23857. }
  23858. };
  23859. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23860. };
  23861. Material.prototype.unbind = function () {
  23862. if (this.disableDepthWrite) {
  23863. var engine = this._scene.getEngine();
  23864. engine.setDepthWrite(this._cachedDepthWriteState);
  23865. }
  23866. };
  23867. Material.prototype.clone = function (name) {
  23868. return null;
  23869. };
  23870. Material.prototype.getBindedMeshes = function () {
  23871. var result = new Array();
  23872. for (var index = 0; index < this._scene.meshes.length; index++) {
  23873. var mesh = this._scene.meshes[index];
  23874. if (mesh.material === this) {
  23875. result.push(mesh);
  23876. }
  23877. }
  23878. return result;
  23879. };
  23880. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23881. // Animations
  23882. this.getScene().stopAnimation(this);
  23883. // Remove from scene
  23884. var index = this._scene.materials.indexOf(this);
  23885. if (index >= 0) {
  23886. this._scene.materials.splice(index, 1);
  23887. }
  23888. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23889. if (forceDisposeEffect && this._effect) {
  23890. this._scene.getEngine()._releaseEffect(this._effect);
  23891. this._effect = null;
  23892. }
  23893. // Remove from meshes
  23894. for (index = 0; index < this._scene.meshes.length; index++) {
  23895. var mesh = this._scene.meshes[index];
  23896. if (mesh.material === this) {
  23897. mesh.material = null;
  23898. }
  23899. }
  23900. // Callback
  23901. this.onDisposeObservable.notifyObservers(this);
  23902. this.onDisposeObservable.clear();
  23903. this.onBindObservable.clear();
  23904. };
  23905. Material.prototype.serialize = function () {
  23906. return BABYLON.SerializationHelper.Serialize(this);
  23907. };
  23908. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23909. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23910. multiMaterial.id = parsedMultiMaterial.id;
  23911. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23912. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23913. var subMatId = parsedMultiMaterial.materials[matIndex];
  23914. if (subMatId) {
  23915. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23916. }
  23917. else {
  23918. multiMaterial.subMaterials.push(null);
  23919. }
  23920. }
  23921. return multiMaterial;
  23922. };
  23923. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23924. if (!parsedMaterial.customType) {
  23925. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23926. }
  23927. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23928. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23929. ;
  23930. };
  23931. Material._TriangleFillMode = 0;
  23932. Material._WireFrameFillMode = 1;
  23933. Material._PointFillMode = 2;
  23934. Material._ClockWiseSideOrientation = 0;
  23935. Material._CounterClockWiseSideOrientation = 1;
  23936. __decorate([
  23937. BABYLON.serialize()
  23938. ], Material.prototype, "id", void 0);
  23939. __decorate([
  23940. BABYLON.serialize()
  23941. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23942. __decorate([
  23943. BABYLON.serialize()
  23944. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23945. __decorate([
  23946. BABYLON.serialize()
  23947. ], Material.prototype, "state", void 0);
  23948. __decorate([
  23949. BABYLON.serialize()
  23950. ], Material.prototype, "alpha", void 0);
  23951. __decorate([
  23952. BABYLON.serialize()
  23953. ], Material.prototype, "backFaceCulling", void 0);
  23954. __decorate([
  23955. BABYLON.serialize()
  23956. ], Material.prototype, "sideOrientation", void 0);
  23957. __decorate([
  23958. BABYLON.serialize()
  23959. ], Material.prototype, "alphaMode", void 0);
  23960. __decorate([
  23961. BABYLON.serialize()
  23962. ], Material.prototype, "disableDepthWrite", void 0);
  23963. __decorate([
  23964. BABYLON.serialize()
  23965. ], Material.prototype, "fogEnabled", void 0);
  23966. __decorate([
  23967. BABYLON.serialize()
  23968. ], Material.prototype, "pointSize", void 0);
  23969. __decorate([
  23970. BABYLON.serialize()
  23971. ], Material.prototype, "zOffset", void 0);
  23972. __decorate([
  23973. BABYLON.serialize()
  23974. ], Material.prototype, "wireframe", null);
  23975. __decorate([
  23976. BABYLON.serialize()
  23977. ], Material.prototype, "pointsCloud", null);
  23978. __decorate([
  23979. BABYLON.serialize()
  23980. ], Material.prototype, "fillMode", null);
  23981. return Material;
  23982. })();
  23983. BABYLON.Material = Material;
  23984. })(BABYLON || (BABYLON = {}));
  23985. var BABYLON;
  23986. (function (BABYLON) {
  23987. var StandardMaterialDefines = (function (_super) {
  23988. __extends(StandardMaterialDefines, _super);
  23989. function StandardMaterialDefines() {
  23990. _super.call(this);
  23991. this.DIFFUSE = false;
  23992. this.AMBIENT = false;
  23993. this.OPACITY = false;
  23994. this.OPACITYRGB = false;
  23995. this.REFLECTION = false;
  23996. this.EMISSIVE = false;
  23997. this.SPECULAR = false;
  23998. this.BUMP = false;
  23999. this.PARALLAX = false;
  24000. this.PARALLAXOCCLUSION = false;
  24001. this.SPECULAROVERALPHA = false;
  24002. this.CLIPPLANE = false;
  24003. this.ALPHATEST = false;
  24004. this.ALPHAFROMDIFFUSE = false;
  24005. this.POINTSIZE = false;
  24006. this.FOG = false;
  24007. this.SPECULARTERM = false;
  24008. this.DIFFUSEFRESNEL = false;
  24009. this.OPACITYFRESNEL = false;
  24010. this.REFLECTIONFRESNEL = false;
  24011. this.REFRACTIONFRESNEL = false;
  24012. this.EMISSIVEFRESNEL = false;
  24013. this.FRESNEL = false;
  24014. this.NORMAL = false;
  24015. this.UV1 = false;
  24016. this.UV2 = false;
  24017. this.VERTEXCOLOR = false;
  24018. this.VERTEXALPHA = false;
  24019. this.NUM_BONE_INFLUENCERS = 0;
  24020. this.BonesPerMesh = 0;
  24021. this.INSTANCES = false;
  24022. this.GLOSSINESS = false;
  24023. this.ROUGHNESS = false;
  24024. this.EMISSIVEASILLUMINATION = false;
  24025. this.LINKEMISSIVEWITHDIFFUSE = false;
  24026. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24027. this.LIGHTMAP = false;
  24028. this.USELIGHTMAPASSHADOWMAP = false;
  24029. this.REFLECTIONMAP_3D = false;
  24030. this.REFLECTIONMAP_SPHERICAL = false;
  24031. this.REFLECTIONMAP_PLANAR = false;
  24032. this.REFLECTIONMAP_CUBIC = false;
  24033. this.REFLECTIONMAP_PROJECTION = false;
  24034. this.REFLECTIONMAP_SKYBOX = false;
  24035. this.REFLECTIONMAP_EXPLICIT = false;
  24036. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24037. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24038. this.INVERTCUBICMAP = false;
  24039. this.LOGARITHMICDEPTH = false;
  24040. this.REFRACTION = false;
  24041. this.REFRACTIONMAP_3D = false;
  24042. this.REFLECTIONOVERALPHA = false;
  24043. this.INVERTNORMALMAPX = false;
  24044. this.INVERTNORMALMAPY = false;
  24045. this.SHADOWFULLFLOAT = false;
  24046. this.rebuild();
  24047. }
  24048. return StandardMaterialDefines;
  24049. })(BABYLON.MaterialDefines);
  24050. var StandardMaterial = (function (_super) {
  24051. __extends(StandardMaterial, _super);
  24052. function StandardMaterial(name, scene) {
  24053. var _this = this;
  24054. _super.call(this, name, scene);
  24055. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24056. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24057. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24058. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24059. this.specularPower = 64;
  24060. this.useAlphaFromDiffuseTexture = false;
  24061. this.useEmissiveAsIllumination = false;
  24062. this.linkEmissiveWithDiffuse = false;
  24063. this.useReflectionFresnelFromSpecular = false;
  24064. this.useSpecularOverAlpha = false;
  24065. this.useReflectionOverAlpha = false;
  24066. this.disableLighting = false;
  24067. this.useParallax = false;
  24068. this.useParallaxOcclusion = false;
  24069. this.parallaxScaleBias = 0.05;
  24070. this.roughness = 0;
  24071. this.indexOfRefraction = 0.98;
  24072. this.invertRefractionY = true;
  24073. this.useLightmapAsShadowmap = false;
  24074. this.useGlossinessFromSpecularMapAlpha = false;
  24075. this.maxSimultaneousLights = 4;
  24076. /**
  24077. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24078. */
  24079. this.invertNormalMapX = false;
  24080. /**
  24081. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24082. */
  24083. this.invertNormalMapY = false;
  24084. this._renderTargets = new BABYLON.SmartArray(16);
  24085. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24086. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24087. this._defines = new StandardMaterialDefines();
  24088. this._cachedDefines = new StandardMaterialDefines();
  24089. this._cachedDefines.BonesPerMesh = -1;
  24090. this.getRenderTargetTextures = function () {
  24091. _this._renderTargets.reset();
  24092. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24093. _this._renderTargets.push(_this.reflectionTexture);
  24094. }
  24095. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24096. _this._renderTargets.push(_this.refractionTexture);
  24097. }
  24098. return _this._renderTargets;
  24099. };
  24100. }
  24101. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24102. get: function () {
  24103. return this._useLogarithmicDepth;
  24104. },
  24105. set: function (value) {
  24106. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24107. },
  24108. enumerable: true,
  24109. configurable: true
  24110. });
  24111. StandardMaterial.prototype.needAlphaBlending = function () {
  24112. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24113. };
  24114. StandardMaterial.prototype.needAlphaTesting = function () {
  24115. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24116. };
  24117. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24118. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24119. };
  24120. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24121. return this.diffuseTexture;
  24122. };
  24123. // Methods
  24124. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24125. if (!mesh) {
  24126. return true;
  24127. }
  24128. if (this._defines.INSTANCES !== useInstances) {
  24129. return false;
  24130. }
  24131. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24132. return true;
  24133. }
  24134. return false;
  24135. };
  24136. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24137. if (this.isFrozen) {
  24138. if (this._wasPreviouslyReady) {
  24139. return true;
  24140. }
  24141. }
  24142. var scene = this.getScene();
  24143. if (!this.checkReadyOnEveryCall) {
  24144. if (this._renderId === scene.getRenderId()) {
  24145. if (this._checkCache(scene, mesh, useInstances)) {
  24146. return true;
  24147. }
  24148. }
  24149. }
  24150. var engine = scene.getEngine();
  24151. var needNormals = false;
  24152. var needUVs = false;
  24153. this._defines.reset();
  24154. // Textures
  24155. if (scene.texturesEnabled) {
  24156. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24157. if (!this.diffuseTexture.isReady()) {
  24158. return false;
  24159. }
  24160. else {
  24161. needUVs = true;
  24162. this._defines.DIFFUSE = true;
  24163. }
  24164. }
  24165. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24166. if (!this.ambientTexture.isReady()) {
  24167. return false;
  24168. }
  24169. else {
  24170. needUVs = true;
  24171. this._defines.AMBIENT = true;
  24172. }
  24173. }
  24174. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24175. if (!this.opacityTexture.isReady()) {
  24176. return false;
  24177. }
  24178. else {
  24179. needUVs = true;
  24180. this._defines.OPACITY = true;
  24181. if (this.opacityTexture.getAlphaFromRGB) {
  24182. this._defines.OPACITYRGB = true;
  24183. }
  24184. }
  24185. }
  24186. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24187. if (!this.reflectionTexture.isReady()) {
  24188. return false;
  24189. }
  24190. else {
  24191. needNormals = true;
  24192. this._defines.REFLECTION = true;
  24193. if (this.roughness > 0) {
  24194. this._defines.ROUGHNESS = true;
  24195. }
  24196. if (this.useReflectionOverAlpha) {
  24197. this._defines.REFLECTIONOVERALPHA = true;
  24198. }
  24199. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24200. this._defines.INVERTCUBICMAP = true;
  24201. }
  24202. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24203. switch (this.reflectionTexture.coordinatesMode) {
  24204. case BABYLON.Texture.CUBIC_MODE:
  24205. case BABYLON.Texture.INVCUBIC_MODE:
  24206. this._defines.REFLECTIONMAP_CUBIC = true;
  24207. break;
  24208. case BABYLON.Texture.EXPLICIT_MODE:
  24209. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24210. break;
  24211. case BABYLON.Texture.PLANAR_MODE:
  24212. this._defines.REFLECTIONMAP_PLANAR = true;
  24213. break;
  24214. case BABYLON.Texture.PROJECTION_MODE:
  24215. this._defines.REFLECTIONMAP_PROJECTION = true;
  24216. break;
  24217. case BABYLON.Texture.SKYBOX_MODE:
  24218. this._defines.REFLECTIONMAP_SKYBOX = true;
  24219. break;
  24220. case BABYLON.Texture.SPHERICAL_MODE:
  24221. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24222. break;
  24223. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24224. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24225. break;
  24226. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24227. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24228. break;
  24229. }
  24230. }
  24231. }
  24232. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24233. if (!this.emissiveTexture.isReady()) {
  24234. return false;
  24235. }
  24236. else {
  24237. needUVs = true;
  24238. this._defines.EMISSIVE = true;
  24239. }
  24240. }
  24241. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24242. if (!this.lightmapTexture.isReady()) {
  24243. return false;
  24244. }
  24245. else {
  24246. needUVs = true;
  24247. this._defines.LIGHTMAP = true;
  24248. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24249. }
  24250. }
  24251. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24252. if (!this.specularTexture.isReady()) {
  24253. return false;
  24254. }
  24255. else {
  24256. needUVs = true;
  24257. this._defines.SPECULAR = true;
  24258. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24259. }
  24260. }
  24261. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24262. if (!this.bumpTexture.isReady()) {
  24263. return false;
  24264. }
  24265. else {
  24266. needUVs = true;
  24267. this._defines.BUMP = true;
  24268. if (this.useParallax) {
  24269. this._defines.PARALLAX = true;
  24270. if (this.useParallaxOcclusion) {
  24271. this._defines.PARALLAXOCCLUSION = true;
  24272. }
  24273. }
  24274. if (this.invertNormalMapX) {
  24275. this._defines.INVERTNORMALMAPX = true;
  24276. }
  24277. if (this.invertNormalMapY) {
  24278. this._defines.INVERTNORMALMAPY = true;
  24279. }
  24280. }
  24281. }
  24282. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24283. if (!this.refractionTexture.isReady()) {
  24284. return false;
  24285. }
  24286. else {
  24287. needUVs = true;
  24288. this._defines.REFRACTION = true;
  24289. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24290. }
  24291. }
  24292. }
  24293. // Effect
  24294. if (scene.clipPlane) {
  24295. this._defines.CLIPPLANE = true;
  24296. }
  24297. if (engine.getAlphaTesting()) {
  24298. this._defines.ALPHATEST = true;
  24299. }
  24300. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24301. this._defines.ALPHAFROMDIFFUSE = true;
  24302. }
  24303. if (this.useEmissiveAsIllumination) {
  24304. this._defines.EMISSIVEASILLUMINATION = true;
  24305. }
  24306. if (this.linkEmissiveWithDiffuse) {
  24307. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24308. }
  24309. if (this.useLogarithmicDepth) {
  24310. this._defines.LOGARITHMICDEPTH = true;
  24311. }
  24312. // Point size
  24313. if (this.pointsCloud || scene.forcePointsCloud) {
  24314. this._defines.POINTSIZE = true;
  24315. }
  24316. // Fog
  24317. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24318. this._defines.FOG = true;
  24319. }
  24320. if (scene.lightsEnabled && !this.disableLighting) {
  24321. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24322. }
  24323. if (StandardMaterial.FresnelEnabled) {
  24324. // Fresnel
  24325. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24326. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24327. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24328. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24329. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24330. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24331. this._defines.DIFFUSEFRESNEL = true;
  24332. }
  24333. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24334. this._defines.OPACITYFRESNEL = true;
  24335. }
  24336. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24337. this._defines.REFLECTIONFRESNEL = true;
  24338. if (this.useReflectionFresnelFromSpecular) {
  24339. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24340. }
  24341. }
  24342. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24343. this._defines.REFRACTIONFRESNEL = true;
  24344. }
  24345. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24346. this._defines.EMISSIVEFRESNEL = true;
  24347. }
  24348. needNormals = true;
  24349. this._defines.FRESNEL = true;
  24350. }
  24351. }
  24352. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24353. this._defines.SPECULAROVERALPHA = true;
  24354. }
  24355. // Attribs
  24356. if (mesh) {
  24357. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24358. this._defines.NORMAL = true;
  24359. }
  24360. if (needUVs) {
  24361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24362. this._defines.UV1 = true;
  24363. }
  24364. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24365. this._defines.UV2 = true;
  24366. }
  24367. }
  24368. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24369. this._defines.VERTEXCOLOR = true;
  24370. if (mesh.hasVertexAlpha) {
  24371. this._defines.VERTEXALPHA = true;
  24372. }
  24373. }
  24374. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24375. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24376. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24377. }
  24378. // Instances
  24379. if (useInstances) {
  24380. this._defines.INSTANCES = true;
  24381. }
  24382. }
  24383. // Get correct effect
  24384. if (!this._defines.isEqual(this._cachedDefines)) {
  24385. this._defines.cloneTo(this._cachedDefines);
  24386. scene.resetCachedMaterial();
  24387. // Fallbacks
  24388. var fallbacks = new BABYLON.EffectFallbacks();
  24389. if (this._defines.REFLECTION) {
  24390. fallbacks.addFallback(0, "REFLECTION");
  24391. }
  24392. if (this._defines.SPECULAR) {
  24393. fallbacks.addFallback(0, "SPECULAR");
  24394. }
  24395. if (this._defines.BUMP) {
  24396. fallbacks.addFallback(0, "BUMP");
  24397. }
  24398. if (this._defines.PARALLAX) {
  24399. fallbacks.addFallback(1, "PARALLAX");
  24400. }
  24401. if (this._defines.PARALLAXOCCLUSION) {
  24402. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24403. }
  24404. if (this._defines.SPECULAROVERALPHA) {
  24405. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24406. }
  24407. if (this._defines.FOG) {
  24408. fallbacks.addFallback(1, "FOG");
  24409. }
  24410. if (this._defines.POINTSIZE) {
  24411. fallbacks.addFallback(0, "POINTSIZE");
  24412. }
  24413. if (this._defines.LOGARITHMICDEPTH) {
  24414. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24415. }
  24416. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24417. if (this._defines.SPECULARTERM) {
  24418. fallbacks.addFallback(0, "SPECULARTERM");
  24419. }
  24420. if (this._defines.DIFFUSEFRESNEL) {
  24421. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24422. }
  24423. if (this._defines.OPACITYFRESNEL) {
  24424. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24425. }
  24426. if (this._defines.REFLECTIONFRESNEL) {
  24427. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24428. }
  24429. if (this._defines.EMISSIVEFRESNEL) {
  24430. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24431. }
  24432. if (this._defines.FRESNEL) {
  24433. fallbacks.addFallback(4, "FRESNEL");
  24434. }
  24435. //Attributes
  24436. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24437. if (this._defines.NORMAL) {
  24438. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24439. }
  24440. if (this._defines.UV1) {
  24441. attribs.push(BABYLON.VertexBuffer.UVKind);
  24442. }
  24443. if (this._defines.UV2) {
  24444. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24445. }
  24446. if (this._defines.VERTEXCOLOR) {
  24447. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24448. }
  24449. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24450. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24451. // Legacy browser patch
  24452. var shaderName = "default";
  24453. if (!scene.getEngine().getCaps().standardDerivatives) {
  24454. shaderName = "legacydefault";
  24455. }
  24456. var join = this._defines.toString();
  24457. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24458. "vFogInfos", "vFogColor", "pointSize",
  24459. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24460. "mBones",
  24461. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24462. "depthValues",
  24463. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24464. "logarithmicDepthConstant"
  24465. ];
  24466. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24467. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24468. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24469. }
  24470. if (!this._effect.isReady()) {
  24471. return false;
  24472. }
  24473. this._renderId = scene.getRenderId();
  24474. this._wasPreviouslyReady = true;
  24475. if (mesh) {
  24476. if (!mesh._materialDefines) {
  24477. mesh._materialDefines = new StandardMaterialDefines();
  24478. }
  24479. this._defines.cloneTo(mesh._materialDefines);
  24480. }
  24481. return true;
  24482. };
  24483. StandardMaterial.prototype.unbind = function () {
  24484. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24485. this._effect.setTexture("reflection2DSampler", null);
  24486. }
  24487. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24488. this._effect.setTexture("refraction2DSampler", null);
  24489. }
  24490. _super.prototype.unbind.call(this);
  24491. };
  24492. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24493. this._effect.setMatrix("world", world);
  24494. };
  24495. StandardMaterial.prototype.bind = function (world, mesh) {
  24496. var scene = this.getScene();
  24497. // Matrices
  24498. this.bindOnlyWorldMatrix(world);
  24499. // Bones
  24500. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24501. if (scene.getCachedMaterial() !== this) {
  24502. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24503. if (StandardMaterial.FresnelEnabled) {
  24504. // Fresnel
  24505. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24506. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24507. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24508. }
  24509. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24510. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24511. }
  24512. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24513. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24514. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24515. }
  24516. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24517. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24518. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24519. }
  24520. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24521. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24522. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24523. }
  24524. }
  24525. // Textures
  24526. if (scene.texturesEnabled) {
  24527. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24528. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24529. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24530. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24531. }
  24532. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24533. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24534. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24535. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24536. }
  24537. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24538. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24539. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24540. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24541. }
  24542. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24543. if (this.reflectionTexture.isCube) {
  24544. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24545. }
  24546. else {
  24547. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24548. }
  24549. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24550. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24551. }
  24552. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24553. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24554. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24555. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24556. }
  24557. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24558. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24559. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24560. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24561. }
  24562. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24563. this._effect.setTexture("specularSampler", this.specularTexture);
  24564. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24565. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24566. }
  24567. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24568. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24569. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24570. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24571. }
  24572. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24573. var depth = 1.0;
  24574. if (this.refractionTexture.isCube) {
  24575. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24576. }
  24577. else {
  24578. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24579. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24580. if (this.refractionTexture.depth) {
  24581. depth = this.refractionTexture.depth;
  24582. }
  24583. }
  24584. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24585. }
  24586. }
  24587. // Clip plane
  24588. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24589. // Point size
  24590. if (this.pointsCloud) {
  24591. this._effect.setFloat("pointSize", this.pointSize);
  24592. }
  24593. // Colors
  24594. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24595. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24596. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24597. if (this._defines.SPECULARTERM) {
  24598. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24599. }
  24600. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24601. }
  24602. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24603. // Diffuse
  24604. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24605. // Lights
  24606. if (scene.lightsEnabled && !this.disableLighting) {
  24607. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24608. }
  24609. // View
  24610. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24611. this._effect.setMatrix("view", scene.getViewMatrix());
  24612. }
  24613. // Fog
  24614. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24615. // Log. depth
  24616. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24617. }
  24618. _super.prototype.bind.call(this, world, mesh);
  24619. };
  24620. StandardMaterial.prototype.getAnimatables = function () {
  24621. var results = [];
  24622. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24623. results.push(this.diffuseTexture);
  24624. }
  24625. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24626. results.push(this.ambientTexture);
  24627. }
  24628. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24629. results.push(this.opacityTexture);
  24630. }
  24631. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24632. results.push(this.reflectionTexture);
  24633. }
  24634. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24635. results.push(this.emissiveTexture);
  24636. }
  24637. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24638. results.push(this.specularTexture);
  24639. }
  24640. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24641. results.push(this.bumpTexture);
  24642. }
  24643. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24644. results.push(this.lightmapTexture);
  24645. }
  24646. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24647. results.push(this.refractionTexture);
  24648. }
  24649. return results;
  24650. };
  24651. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24652. if (forceDisposeTextures) {
  24653. if (this.diffuseTexture) {
  24654. this.diffuseTexture.dispose();
  24655. }
  24656. if (this.ambientTexture) {
  24657. this.ambientTexture.dispose();
  24658. }
  24659. if (this.opacityTexture) {
  24660. this.opacityTexture.dispose();
  24661. }
  24662. if (this.reflectionTexture) {
  24663. this.reflectionTexture.dispose();
  24664. }
  24665. if (this.emissiveTexture) {
  24666. this.emissiveTexture.dispose();
  24667. }
  24668. if (this.specularTexture) {
  24669. this.specularTexture.dispose();
  24670. }
  24671. if (this.bumpTexture) {
  24672. this.bumpTexture.dispose();
  24673. }
  24674. if (this.lightmapTexture) {
  24675. this.lightmapTexture.dispose();
  24676. }
  24677. if (this.refractionTexture) {
  24678. this.refractionTexture.dispose();
  24679. }
  24680. }
  24681. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24682. };
  24683. StandardMaterial.prototype.clone = function (name) {
  24684. var _this = this;
  24685. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24686. };
  24687. StandardMaterial.prototype.serialize = function () {
  24688. return BABYLON.SerializationHelper.Serialize(this);
  24689. };
  24690. // Statics
  24691. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24692. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24693. };
  24694. // Flags used to enable or disable a type of texture for all Standard Materials
  24695. StandardMaterial.DiffuseTextureEnabled = true;
  24696. StandardMaterial.AmbientTextureEnabled = true;
  24697. StandardMaterial.OpacityTextureEnabled = true;
  24698. StandardMaterial.ReflectionTextureEnabled = true;
  24699. StandardMaterial.EmissiveTextureEnabled = true;
  24700. StandardMaterial.SpecularTextureEnabled = true;
  24701. StandardMaterial.BumpTextureEnabled = true;
  24702. StandardMaterial.FresnelEnabled = true;
  24703. StandardMaterial.LightmapTextureEnabled = true;
  24704. StandardMaterial.RefractionTextureEnabled = true;
  24705. __decorate([
  24706. BABYLON.serializeAsTexture()
  24707. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24708. __decorate([
  24709. BABYLON.serializeAsTexture()
  24710. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24711. __decorate([
  24712. BABYLON.serializeAsTexture()
  24713. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24714. __decorate([
  24715. BABYLON.serializeAsTexture()
  24716. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24717. __decorate([
  24718. BABYLON.serializeAsTexture()
  24719. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24720. __decorate([
  24721. BABYLON.serializeAsTexture()
  24722. ], StandardMaterial.prototype, "specularTexture", void 0);
  24723. __decorate([
  24724. BABYLON.serializeAsTexture()
  24725. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24726. __decorate([
  24727. BABYLON.serializeAsTexture()
  24728. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24729. __decorate([
  24730. BABYLON.serializeAsTexture()
  24731. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24732. __decorate([
  24733. BABYLON.serializeAsColor3("ambient")
  24734. ], StandardMaterial.prototype, "ambientColor", void 0);
  24735. __decorate([
  24736. BABYLON.serializeAsColor3("diffuse")
  24737. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24738. __decorate([
  24739. BABYLON.serializeAsColor3("specular")
  24740. ], StandardMaterial.prototype, "specularColor", void 0);
  24741. __decorate([
  24742. BABYLON.serializeAsColor3("emissive")
  24743. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24744. __decorate([
  24745. BABYLON.serialize()
  24746. ], StandardMaterial.prototype, "specularPower", void 0);
  24747. __decorate([
  24748. BABYLON.serialize()
  24749. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24750. __decorate([
  24751. BABYLON.serialize()
  24752. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24753. __decorate([
  24754. BABYLON.serialize()
  24755. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24756. __decorate([
  24757. BABYLON.serialize()
  24758. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24759. __decorate([
  24760. BABYLON.serialize()
  24761. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24762. __decorate([
  24763. BABYLON.serialize()
  24764. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24765. __decorate([
  24766. BABYLON.serialize()
  24767. ], StandardMaterial.prototype, "disableLighting", void 0);
  24768. __decorate([
  24769. BABYLON.serialize()
  24770. ], StandardMaterial.prototype, "useParallax", void 0);
  24771. __decorate([
  24772. BABYLON.serialize()
  24773. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24774. __decorate([
  24775. BABYLON.serialize()
  24776. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24777. __decorate([
  24778. BABYLON.serialize()
  24779. ], StandardMaterial.prototype, "roughness", void 0);
  24780. __decorate([
  24781. BABYLON.serialize()
  24782. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24783. __decorate([
  24784. BABYLON.serialize()
  24785. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24786. __decorate([
  24787. BABYLON.serialize()
  24788. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24789. __decorate([
  24790. BABYLON.serializeAsFresnelParameters()
  24791. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24792. __decorate([
  24793. BABYLON.serializeAsFresnelParameters()
  24794. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24795. __decorate([
  24796. BABYLON.serializeAsFresnelParameters()
  24797. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24798. __decorate([
  24799. BABYLON.serializeAsFresnelParameters()
  24800. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24801. __decorate([
  24802. BABYLON.serializeAsFresnelParameters()
  24803. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24804. __decorate([
  24805. BABYLON.serialize()
  24806. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24807. __decorate([
  24808. BABYLON.serialize()
  24809. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24810. __decorate([
  24811. BABYLON.serialize()
  24812. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24813. __decorate([
  24814. BABYLON.serialize()
  24815. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24816. __decorate([
  24817. BABYLON.serialize()
  24818. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24819. return StandardMaterial;
  24820. })(BABYLON.Material);
  24821. BABYLON.StandardMaterial = StandardMaterial;
  24822. })(BABYLON || (BABYLON = {}));
  24823. var BABYLON;
  24824. (function (BABYLON) {
  24825. var MultiMaterial = (function (_super) {
  24826. __extends(MultiMaterial, _super);
  24827. function MultiMaterial(name, scene) {
  24828. _super.call(this, name, scene, true);
  24829. this.subMaterials = new Array();
  24830. scene.multiMaterials.push(this);
  24831. }
  24832. // Properties
  24833. MultiMaterial.prototype.getSubMaterial = function (index) {
  24834. if (index < 0 || index >= this.subMaterials.length) {
  24835. return this.getScene().defaultMaterial;
  24836. }
  24837. return this.subMaterials[index];
  24838. };
  24839. // Methods
  24840. MultiMaterial.prototype.isReady = function (mesh) {
  24841. for (var index = 0; index < this.subMaterials.length; index++) {
  24842. var subMaterial = this.subMaterials[index];
  24843. if (subMaterial) {
  24844. if (!this.subMaterials[index].isReady(mesh)) {
  24845. return false;
  24846. }
  24847. }
  24848. }
  24849. return true;
  24850. };
  24851. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24852. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24853. for (var index = 0; index < this.subMaterials.length; index++) {
  24854. var subMaterial = null;
  24855. if (cloneChildren) {
  24856. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24857. }
  24858. else {
  24859. subMaterial = this.subMaterials[index];
  24860. }
  24861. newMultiMaterial.subMaterials.push(subMaterial);
  24862. }
  24863. return newMultiMaterial;
  24864. };
  24865. MultiMaterial.prototype.serialize = function () {
  24866. var serializationObject = {};
  24867. serializationObject.name = this.name;
  24868. serializationObject.id = this.id;
  24869. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24870. serializationObject.materials = [];
  24871. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24872. var subMat = this.subMaterials[matIndex];
  24873. if (subMat) {
  24874. serializationObject.materials.push(subMat.id);
  24875. }
  24876. else {
  24877. serializationObject.materials.push(null);
  24878. }
  24879. }
  24880. return serializationObject;
  24881. };
  24882. return MultiMaterial;
  24883. })(BABYLON.Material);
  24884. BABYLON.MultiMaterial = MultiMaterial;
  24885. })(BABYLON || (BABYLON = {}));
  24886. var BABYLON;
  24887. (function (BABYLON) {
  24888. var SceneLoader = (function () {
  24889. function SceneLoader() {
  24890. }
  24891. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24892. get: function () {
  24893. return 0;
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24899. get: function () {
  24900. return 1;
  24901. },
  24902. enumerable: true,
  24903. configurable: true
  24904. });
  24905. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24906. get: function () {
  24907. return 2;
  24908. },
  24909. enumerable: true,
  24910. configurable: true
  24911. });
  24912. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24913. get: function () {
  24914. return 3;
  24915. },
  24916. enumerable: true,
  24917. configurable: true
  24918. });
  24919. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24920. get: function () {
  24921. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24922. },
  24923. set: function (value) {
  24924. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24930. get: function () {
  24931. return SceneLoader._ShowLoadingScreen;
  24932. },
  24933. set: function (value) {
  24934. SceneLoader._ShowLoadingScreen = value;
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(SceneLoader, "loggingLevel", {
  24940. get: function () {
  24941. return SceneLoader._loggingLevel;
  24942. },
  24943. set: function (value) {
  24944. SceneLoader._loggingLevel = value;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24950. var dotPosition = sceneFilename.lastIndexOf(".");
  24951. var queryStringPosition = sceneFilename.indexOf("?");
  24952. if (queryStringPosition === -1) {
  24953. queryStringPosition = sceneFilename.length;
  24954. }
  24955. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24956. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24957. var plugin = this._registeredPlugins[index];
  24958. if (plugin.extensions.indexOf(extension) !== -1) {
  24959. return plugin;
  24960. }
  24961. }
  24962. return this._registeredPlugins[0];
  24963. };
  24964. // Public functions
  24965. SceneLoader.GetPluginForExtension = function (extension) {
  24966. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24967. var plugin = this._registeredPlugins[index];
  24968. if (plugin.extensions.indexOf(extension) !== -1) {
  24969. return plugin;
  24970. }
  24971. }
  24972. return null;
  24973. };
  24974. SceneLoader.RegisterPlugin = function (plugin) {
  24975. plugin.extensions = plugin.extensions.toLowerCase();
  24976. SceneLoader._registeredPlugins.push(plugin);
  24977. };
  24978. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24979. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24980. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24981. return;
  24982. }
  24983. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24984. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24985. return;
  24986. }
  24987. var loadingToken = {};
  24988. scene._addPendingData(loadingToken);
  24989. var manifestChecked = function (success) {
  24990. scene.database = database;
  24991. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24992. var importMeshFromData = function (data) {
  24993. var meshes = [];
  24994. var particleSystems = [];
  24995. var skeletons = [];
  24996. try {
  24997. if (plugin.importMesh) {
  24998. var syncedPlugin = plugin;
  24999. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25000. if (onerror) {
  25001. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25002. }
  25003. scene._removePendingData(loadingToken);
  25004. return;
  25005. }
  25006. if (onsuccess) {
  25007. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25008. onsuccess(meshes, particleSystems, skeletons);
  25009. scene._removePendingData(loadingToken);
  25010. }
  25011. }
  25012. else {
  25013. var asyncedPlugin = plugin;
  25014. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25015. if (onsuccess) {
  25016. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25017. onsuccess(meshes, particleSystems, skeletons);
  25018. scene._removePendingData(loadingToken);
  25019. }
  25020. }, function () {
  25021. if (onerror) {
  25022. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25023. }
  25024. scene._removePendingData(loadingToken);
  25025. });
  25026. }
  25027. }
  25028. catch (e) {
  25029. if (onerror) {
  25030. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25031. }
  25032. scene._removePendingData(loadingToken);
  25033. }
  25034. };
  25035. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25036. // Direct load
  25037. importMeshFromData(sceneFilename.substr(5));
  25038. return;
  25039. }
  25040. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25041. importMeshFromData(data);
  25042. }, progressCallBack, database);
  25043. };
  25044. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25045. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25046. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25047. }
  25048. else {
  25049. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25050. manifestChecked(true);
  25051. }
  25052. };
  25053. /**
  25054. * Load a scene
  25055. * @param rootUrl a string that defines the root url for scene and resources
  25056. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25057. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25058. */
  25059. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25060. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25061. };
  25062. /**
  25063. * Append a scene
  25064. * @param rootUrl a string that defines the root url for scene and resources
  25065. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25066. * @param scene is the instance of BABYLON.Scene to append to
  25067. */
  25068. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25069. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25070. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25071. return;
  25072. }
  25073. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25074. var database;
  25075. var loadingToken = {};
  25076. scene._addPendingData(loadingToken);
  25077. if (SceneLoader.ShowLoadingScreen) {
  25078. scene.getEngine().displayLoadingUI();
  25079. }
  25080. var loadSceneFromData = function (data) {
  25081. scene.database = database;
  25082. if (plugin.load) {
  25083. var syncedPlugin = plugin;
  25084. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25085. if (onerror) {
  25086. onerror(scene);
  25087. }
  25088. scene._removePendingData(loadingToken);
  25089. scene.getEngine().hideLoadingUI();
  25090. return;
  25091. }
  25092. if (onsuccess) {
  25093. onsuccess(scene);
  25094. }
  25095. scene._removePendingData(loadingToken);
  25096. }
  25097. else {
  25098. var asyncedPlugin = plugin;
  25099. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25100. if (onsuccess) {
  25101. onsuccess(scene);
  25102. }
  25103. }, function () {
  25104. if (onerror) {
  25105. onerror(scene);
  25106. }
  25107. scene._removePendingData(loadingToken);
  25108. scene.getEngine().hideLoadingUI();
  25109. });
  25110. }
  25111. if (SceneLoader.ShowLoadingScreen) {
  25112. scene.executeWhenReady(function () {
  25113. scene.getEngine().hideLoadingUI();
  25114. });
  25115. }
  25116. };
  25117. var manifestChecked = function (success) {
  25118. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25119. };
  25120. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25121. // Direct load
  25122. loadSceneFromData(sceneFilename.substr(5));
  25123. return;
  25124. }
  25125. if (rootUrl.indexOf("file:") === -1) {
  25126. if (scene.getEngine().enableOfflineSupport) {
  25127. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25128. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25129. }
  25130. else {
  25131. manifestChecked(true);
  25132. }
  25133. }
  25134. else {
  25135. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25136. }
  25137. };
  25138. // Flags
  25139. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25140. SceneLoader._ShowLoadingScreen = true;
  25141. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25142. // Members
  25143. SceneLoader._registeredPlugins = new Array();
  25144. return SceneLoader;
  25145. })();
  25146. BABYLON.SceneLoader = SceneLoader;
  25147. ;
  25148. })(BABYLON || (BABYLON = {}));
  25149. var BABYLON;
  25150. (function (BABYLON) {
  25151. var Internals;
  25152. (function (Internals) {
  25153. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25154. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25155. var parsedMaterial = parsedData.materials[index];
  25156. if (parsedMaterial.id === id) {
  25157. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25158. }
  25159. }
  25160. return null;
  25161. };
  25162. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25163. names = (names instanceof Array) ? names : [names];
  25164. for (var i in names) {
  25165. if (mesh.name === names[i]) {
  25166. hierarchyIds.push(mesh.id);
  25167. return true;
  25168. }
  25169. }
  25170. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25171. hierarchyIds.push(mesh.id);
  25172. return true;
  25173. }
  25174. return false;
  25175. };
  25176. var logOperation = function (operation, producer) {
  25177. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25178. };
  25179. BABYLON.SceneLoader.RegisterPlugin({
  25180. extensions: ".babylon",
  25181. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25182. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25183. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25184. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25185. // and avoid problems with multiple concurrent .babylon loads.
  25186. var log = "importMesh has failed JSON parse";
  25187. try {
  25188. var parsedData = JSON.parse(data);
  25189. log = "";
  25190. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25191. var loadedSkeletonsIds = [];
  25192. var loadedMaterialsIds = [];
  25193. var hierarchyIds = [];
  25194. var index;
  25195. var cache;
  25196. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25197. var parsedMesh = parsedData.meshes[index];
  25198. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25199. if (meshesNames instanceof Array) {
  25200. // Remove found mesh name from list.
  25201. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25202. }
  25203. //Geometry?
  25204. if (parsedMesh.geometryId) {
  25205. //does the file contain geometries?
  25206. if (parsedData.geometries) {
  25207. //find the correct geometry and add it to the scene
  25208. var found = false;
  25209. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25210. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25211. return;
  25212. }
  25213. else {
  25214. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25215. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25216. switch (geometryType) {
  25217. case "boxes":
  25218. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25219. break;
  25220. case "spheres":
  25221. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25222. break;
  25223. case "cylinders":
  25224. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25225. break;
  25226. case "toruses":
  25227. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25228. break;
  25229. case "grounds":
  25230. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25231. break;
  25232. case "planes":
  25233. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25234. break;
  25235. case "torusKnots":
  25236. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25237. break;
  25238. case "vertexData":
  25239. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25240. break;
  25241. }
  25242. found = true;
  25243. }
  25244. });
  25245. }
  25246. });
  25247. if (!found) {
  25248. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25249. }
  25250. }
  25251. }
  25252. // Material ?
  25253. if (parsedMesh.materialId) {
  25254. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25255. if (!materialFound && parsedData.multiMaterials) {
  25256. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25257. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25258. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25259. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25260. var subMatId = parsedMultiMaterial.materials[matIndex];
  25261. loadedMaterialsIds.push(subMatId);
  25262. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25263. log += "\n\tMaterial " + mat.toString(fullDetails);
  25264. }
  25265. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25266. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25267. materialFound = true;
  25268. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25269. break;
  25270. }
  25271. }
  25272. }
  25273. if (!materialFound) {
  25274. loadedMaterialsIds.push(parsedMesh.materialId);
  25275. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25276. if (!mat) {
  25277. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25278. }
  25279. else {
  25280. log += "\n\tMaterial " + mat.toString(fullDetails);
  25281. }
  25282. }
  25283. }
  25284. // Skeleton ?
  25285. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25286. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25287. if (!skeletonAlreadyLoaded) {
  25288. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25289. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25290. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25291. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25292. skeletons.push(skeleton);
  25293. loadedSkeletonsIds.push(parsedSkeleton.id);
  25294. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25295. }
  25296. }
  25297. }
  25298. }
  25299. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25300. meshes.push(mesh);
  25301. log += "\n\tMesh " + mesh.toString(fullDetails);
  25302. }
  25303. }
  25304. // Connecting parents
  25305. var currentMesh;
  25306. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25307. currentMesh = scene.meshes[index];
  25308. if (currentMesh._waitingParentId) {
  25309. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25310. currentMesh._waitingParentId = undefined;
  25311. }
  25312. }
  25313. // freeze and compute world matrix application
  25314. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25315. currentMesh = scene.meshes[index];
  25316. if (currentMesh._waitingFreezeWorldMatrix) {
  25317. currentMesh.freezeWorldMatrix();
  25318. currentMesh._waitingFreezeWorldMatrix = undefined;
  25319. }
  25320. else {
  25321. currentMesh.computeWorldMatrix(true);
  25322. }
  25323. }
  25324. // Particles
  25325. if (parsedData.particleSystems) {
  25326. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25327. var parsedParticleSystem = parsedData.particleSystems[index];
  25328. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25329. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25330. }
  25331. }
  25332. }
  25333. return true;
  25334. }
  25335. catch (err) {
  25336. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25337. log = null;
  25338. throw err;
  25339. }
  25340. finally {
  25341. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25342. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25343. }
  25344. }
  25345. },
  25346. load: function (scene, data, rootUrl) {
  25347. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25348. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25349. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25350. // and avoid problems with multiple concurrent .babylon loads.
  25351. var log = "importScene has failed JSON parse";
  25352. try {
  25353. var parsedData = JSON.parse(data);
  25354. log = "";
  25355. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25356. // Scene
  25357. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25358. scene.autoClear = parsedData.autoClear;
  25359. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25360. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25361. if (parsedData.gravity) {
  25362. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25363. }
  25364. // Fog
  25365. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25366. scene.fogMode = parsedData.fogMode;
  25367. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25368. scene.fogStart = parsedData.fogStart;
  25369. scene.fogEnd = parsedData.fogEnd;
  25370. scene.fogDensity = parsedData.fogDensity;
  25371. log += "\tFog mode for scene: ";
  25372. switch (scene.fogMode) {
  25373. // getters not compiling, so using hardcoded
  25374. case 1:
  25375. log += "exp\n";
  25376. break;
  25377. case 2:
  25378. log += "exp2\n";
  25379. break;
  25380. case 3:
  25381. log += "linear\n";
  25382. break;
  25383. }
  25384. }
  25385. //Physics
  25386. if (parsedData.physicsEnabled) {
  25387. var physicsPlugin;
  25388. if (parsedData.physicsEngine === "cannon") {
  25389. physicsPlugin = new BABYLON.CannonJSPlugin();
  25390. }
  25391. else if (parsedData.physicsEngine === "oimo") {
  25392. physicsPlugin = new BABYLON.OimoJSPlugin();
  25393. }
  25394. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25395. //else - default engine, which is currently oimo
  25396. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25397. scene.enablePhysics(physicsGravity, physicsPlugin);
  25398. }
  25399. //collisions, if defined. otherwise, default is true
  25400. if (parsedData.collisionsEnabled != undefined) {
  25401. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25402. }
  25403. scene.workerCollisions = !!parsedData.workerCollisions;
  25404. var index;
  25405. var cache;
  25406. // Lights
  25407. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25408. var parsedLight = parsedData.lights[index];
  25409. var light = BABYLON.Light.Parse(parsedLight, scene);
  25410. log += (index === 0 ? "\n\tLights:" : "");
  25411. log += "\n\t\t" + light.toString(fullDetails);
  25412. }
  25413. // Animations
  25414. if (parsedData.animations) {
  25415. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25416. var parsedAnimation = parsedData.animations[index];
  25417. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25418. scene.animations.push(animation);
  25419. log += (index === 0 ? "\n\tAnimations:" : "");
  25420. log += "\n\t\t" + animation.toString(fullDetails);
  25421. }
  25422. }
  25423. if (parsedData.autoAnimate) {
  25424. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25425. }
  25426. // Materials
  25427. if (parsedData.materials) {
  25428. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25429. var parsedMaterial = parsedData.materials[index];
  25430. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25431. log += (index === 0 ? "\n\tMaterials:" : "");
  25432. log += "\n\t\t" + mat.toString(fullDetails);
  25433. }
  25434. }
  25435. if (parsedData.multiMaterials) {
  25436. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25437. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25438. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25439. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25440. log += "\n\t\t" + mmat.toString(fullDetails);
  25441. }
  25442. }
  25443. // Skeletons
  25444. if (parsedData.skeletons) {
  25445. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25446. var parsedSkeleton = parsedData.skeletons[index];
  25447. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25448. log += (index === 0 ? "\n\tSkeletons:" : "");
  25449. log += "\n\t\t" + skeleton.toString(fullDetails);
  25450. }
  25451. }
  25452. // Geometries
  25453. var geometries = parsedData.geometries;
  25454. if (geometries) {
  25455. // Boxes
  25456. var boxes = geometries.boxes;
  25457. if (boxes) {
  25458. for (index = 0, cache = boxes.length; index < cache; index++) {
  25459. var parsedBox = boxes[index];
  25460. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25461. }
  25462. }
  25463. // Spheres
  25464. var spheres = geometries.spheres;
  25465. if (spheres) {
  25466. for (index = 0, cache = spheres.length; index < cache; index++) {
  25467. var parsedSphere = spheres[index];
  25468. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25469. }
  25470. }
  25471. // Cylinders
  25472. var cylinders = geometries.cylinders;
  25473. if (cylinders) {
  25474. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25475. var parsedCylinder = cylinders[index];
  25476. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25477. }
  25478. }
  25479. // Toruses
  25480. var toruses = geometries.toruses;
  25481. if (toruses) {
  25482. for (index = 0, cache = toruses.length; index < cache; index++) {
  25483. var parsedTorus = toruses[index];
  25484. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25485. }
  25486. }
  25487. // Grounds
  25488. var grounds = geometries.grounds;
  25489. if (grounds) {
  25490. for (index = 0, cache = grounds.length; index < cache; index++) {
  25491. var parsedGround = grounds[index];
  25492. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25493. }
  25494. }
  25495. // Planes
  25496. var planes = geometries.planes;
  25497. if (planes) {
  25498. for (index = 0, cache = planes.length; index < cache; index++) {
  25499. var parsedPlane = planes[index];
  25500. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25501. }
  25502. }
  25503. // TorusKnots
  25504. var torusKnots = geometries.torusKnots;
  25505. if (torusKnots) {
  25506. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25507. var parsedTorusKnot = torusKnots[index];
  25508. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25509. }
  25510. }
  25511. // VertexData
  25512. var vertexData = geometries.vertexData;
  25513. if (vertexData) {
  25514. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25515. var parsedVertexData = vertexData[index];
  25516. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25517. }
  25518. }
  25519. }
  25520. // Meshes
  25521. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25522. var parsedMesh = parsedData.meshes[index];
  25523. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25524. log += (index === 0 ? "\n\tMeshes:" : "");
  25525. log += "\n\t\t" + mesh.toString(fullDetails);
  25526. }
  25527. // Cameras
  25528. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25529. var parsedCamera = parsedData.cameras[index];
  25530. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25531. log += (index === 0 ? "\n\tCameras:" : "");
  25532. log += "\n\t\t" + camera.toString(fullDetails);
  25533. }
  25534. if (parsedData.activeCameraID) {
  25535. scene.setActiveCameraByID(parsedData.activeCameraID);
  25536. }
  25537. // Browsing all the graph to connect the dots
  25538. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25539. var camera = scene.cameras[index];
  25540. if (camera._waitingParentId) {
  25541. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25542. camera._waitingParentId = undefined;
  25543. }
  25544. }
  25545. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25546. var light = scene.lights[index];
  25547. if (light._waitingParentId) {
  25548. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25549. light._waitingParentId = undefined;
  25550. }
  25551. }
  25552. // Sounds
  25553. var loadedSounds = [];
  25554. var loadedSound;
  25555. if (BABYLON.AudioEngine && parsedData.sounds) {
  25556. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25557. var parsedSound = parsedData.sounds[index];
  25558. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25559. if (!parsedSound.url)
  25560. parsedSound.url = parsedSound.name;
  25561. if (!loadedSounds[parsedSound.url]) {
  25562. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25563. loadedSounds[parsedSound.url] = loadedSound;
  25564. }
  25565. else {
  25566. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25567. }
  25568. }
  25569. else {
  25570. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25571. }
  25572. }
  25573. }
  25574. loadedSounds = [];
  25575. // Connect parents & children and parse actions
  25576. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25577. var mesh = scene.meshes[index];
  25578. if (mesh._waitingParentId) {
  25579. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25580. mesh._waitingParentId = undefined;
  25581. }
  25582. if (mesh._waitingActions) {
  25583. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25584. mesh._waitingActions = undefined;
  25585. }
  25586. }
  25587. // freeze world matrix application
  25588. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25589. var currentMesh = scene.meshes[index];
  25590. if (currentMesh._waitingFreezeWorldMatrix) {
  25591. currentMesh.freezeWorldMatrix();
  25592. currentMesh._waitingFreezeWorldMatrix = undefined;
  25593. }
  25594. else {
  25595. currentMesh.computeWorldMatrix(true);
  25596. }
  25597. }
  25598. // Particles Systems
  25599. if (parsedData.particleSystems) {
  25600. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25601. var parsedParticleSystem = parsedData.particleSystems[index];
  25602. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25603. }
  25604. }
  25605. // Lens flares
  25606. if (parsedData.lensFlareSystems) {
  25607. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25608. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25609. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25610. }
  25611. }
  25612. // Shadows
  25613. if (parsedData.shadowGenerators) {
  25614. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25615. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25616. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25617. }
  25618. }
  25619. // Actions (scene)
  25620. if (parsedData.actions) {
  25621. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25622. }
  25623. // Finish
  25624. return true;
  25625. }
  25626. catch (err) {
  25627. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25628. log = null;
  25629. throw err;
  25630. }
  25631. finally {
  25632. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25633. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25634. }
  25635. }
  25636. }
  25637. });
  25638. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25639. })(BABYLON || (BABYLON = {}));
  25640. var BABYLON;
  25641. (function (BABYLON) {
  25642. var SpriteManager = (function () {
  25643. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25645. this.name = name;
  25646. this.cellSize = cellSize;
  25647. this.sprites = new Array();
  25648. this.renderingGroupId = 0;
  25649. this.layerMask = 0x0FFFFFFF;
  25650. this.fogEnabled = true;
  25651. this.isPickable = false;
  25652. /**
  25653. * An event triggered when the manager is disposed.
  25654. * @type {BABYLON.Observable}
  25655. */
  25656. this.onDisposeObservable = new BABYLON.Observable();
  25657. this._vertexBuffers = {};
  25658. this._capacity = capacity;
  25659. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25660. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25661. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25662. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25663. this._scene = scene;
  25664. this._scene.spriteManagers.push(this);
  25665. var indices = [];
  25666. var index = 0;
  25667. for (var count = 0; count < capacity; count++) {
  25668. indices.push(index);
  25669. indices.push(index + 1);
  25670. indices.push(index + 2);
  25671. indices.push(index);
  25672. indices.push(index + 2);
  25673. indices.push(index + 3);
  25674. index += 4;
  25675. }
  25676. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25677. // VBO
  25678. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25679. this._vertexData = new Float32Array(capacity * 16 * 4);
  25680. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25681. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25682. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25683. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25684. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25686. this._vertexBuffers["options"] = options;
  25687. this._vertexBuffers["cellInfo"] = cellInfo;
  25688. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25689. // Effects
  25690. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25691. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25692. }
  25693. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25694. set: function (callback) {
  25695. if (this._onDisposeObserver) {
  25696. this.onDisposeObservable.remove(this._onDisposeObserver);
  25697. }
  25698. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25699. },
  25700. enumerable: true,
  25701. configurable: true
  25702. });
  25703. Object.defineProperty(SpriteManager.prototype, "texture", {
  25704. get: function () {
  25705. return this._spriteTexture;
  25706. },
  25707. set: function (value) {
  25708. this._spriteTexture = value;
  25709. },
  25710. enumerable: true,
  25711. configurable: true
  25712. });
  25713. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25714. var arrayOffset = index * 16;
  25715. if (offsetX === 0)
  25716. offsetX = this._epsilon;
  25717. else if (offsetX === 1)
  25718. offsetX = 1 - this._epsilon;
  25719. if (offsetY === 0)
  25720. offsetY = this._epsilon;
  25721. else if (offsetY === 1)
  25722. offsetY = 1 - this._epsilon;
  25723. this._vertexData[arrayOffset] = sprite.position.x;
  25724. this._vertexData[arrayOffset + 1] = sprite.position.y;
  25725. this._vertexData[arrayOffset + 2] = sprite.position.z;
  25726. this._vertexData[arrayOffset + 3] = sprite.angle;
  25727. this._vertexData[arrayOffset + 4] = sprite.width;
  25728. this._vertexData[arrayOffset + 5] = sprite.height;
  25729. this._vertexData[arrayOffset + 6] = offsetX;
  25730. this._vertexData[arrayOffset + 7] = offsetY;
  25731. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25732. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25733. var offset = (sprite.cellIndex / rowSize) >> 0;
  25734. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25735. this._vertexData[arrayOffset + 11] = offset;
  25736. // Color
  25737. this._vertexData[arrayOffset + 12] = sprite.color.r;
  25738. this._vertexData[arrayOffset + 13] = sprite.color.g;
  25739. this._vertexData[arrayOffset + 14] = sprite.color.b;
  25740. this._vertexData[arrayOffset + 15] = sprite.color.a;
  25741. };
  25742. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25743. var count = Math.min(this._capacity, this.sprites.length);
  25744. var min = BABYLON.Vector3.Zero();
  25745. var max = BABYLON.Vector3.Zero();
  25746. var distance = Number.MAX_VALUE;
  25747. var currentSprite;
  25748. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25749. var cameraView = camera.getViewMatrix();
  25750. for (var index = 0; index < count; index++) {
  25751. var sprite = this.sprites[index];
  25752. if (!sprite) {
  25753. continue;
  25754. }
  25755. if (predicate) {
  25756. if (!predicate(sprite)) {
  25757. continue;
  25758. }
  25759. }
  25760. else if (!sprite.isPickable) {
  25761. continue;
  25762. }
  25763. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25764. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25765. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25766. if (ray.intersectsBoxMinMax(min, max)) {
  25767. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25768. if (distance > currentDistance) {
  25769. distance = currentDistance;
  25770. currentSprite = sprite;
  25771. if (fastCheck) {
  25772. break;
  25773. }
  25774. }
  25775. }
  25776. }
  25777. if (currentSprite) {
  25778. var result = new BABYLON.PickingInfo();
  25779. result.hit = true;
  25780. result.pickedSprite = currentSprite;
  25781. result.distance = distance;
  25782. return result;
  25783. }
  25784. return null;
  25785. };
  25786. SpriteManager.prototype.render = function () {
  25787. // Check
  25788. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25789. return;
  25790. var engine = this._scene.getEngine();
  25791. var baseSize = this._spriteTexture.getBaseSize();
  25792. // Sprites
  25793. var deltaTime = engine.getDeltaTime();
  25794. var max = Math.min(this._capacity, this.sprites.length);
  25795. var rowSize = baseSize.width / this.cellSize;
  25796. var offset = 0;
  25797. for (var index = 0; index < max; index++) {
  25798. var sprite = this.sprites[index];
  25799. if (!sprite) {
  25800. continue;
  25801. }
  25802. sprite._animate(deltaTime);
  25803. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25804. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25805. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25806. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25807. }
  25808. this._buffer.update(this._vertexData);
  25809. // Render
  25810. var effect = this._effectBase;
  25811. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25812. effect = this._effectFog;
  25813. }
  25814. engine.enableEffect(effect);
  25815. var viewMatrix = this._scene.getViewMatrix();
  25816. effect.setTexture("diffuseSampler", this._spriteTexture);
  25817. effect.setMatrix("view", viewMatrix);
  25818. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25819. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25820. // Fog
  25821. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25822. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25823. effect.setColor3("vFogColor", this._scene.fogColor);
  25824. }
  25825. // VBOs
  25826. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  25827. // Draw order
  25828. engine.setDepthFunctionToLessOrEqual();
  25829. effect.setBool("alphaTest", true);
  25830. engine.setColorWrite(false);
  25831. engine.draw(true, 0, max * 6);
  25832. engine.setColorWrite(true);
  25833. effect.setBool("alphaTest", false);
  25834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25835. engine.draw(true, 0, max * 6);
  25836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25837. };
  25838. SpriteManager.prototype.dispose = function () {
  25839. if (this._buffer) {
  25840. this._buffer.dispose();
  25841. this._buffer = null;
  25842. }
  25843. if (this._indexBuffer) {
  25844. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25845. this._indexBuffer = null;
  25846. }
  25847. if (this._spriteTexture) {
  25848. this._spriteTexture.dispose();
  25849. this._spriteTexture = null;
  25850. }
  25851. // Remove from scene
  25852. var index = this._scene.spriteManagers.indexOf(this);
  25853. this._scene.spriteManagers.splice(index, 1);
  25854. // Callback
  25855. this.onDisposeObservable.notifyObservers(this);
  25856. this.onDisposeObservable.clear();
  25857. };
  25858. return SpriteManager;
  25859. })();
  25860. BABYLON.SpriteManager = SpriteManager;
  25861. })(BABYLON || (BABYLON = {}));
  25862. var BABYLON;
  25863. (function (BABYLON) {
  25864. var Sprite = (function () {
  25865. function Sprite(name, manager) {
  25866. this.name = name;
  25867. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25868. this.width = 1.0;
  25869. this.height = 1.0;
  25870. this.angle = 0;
  25871. this.cellIndex = 0;
  25872. this.invertU = 0;
  25873. this.invertV = 0;
  25874. this.animations = new Array();
  25875. this.isPickable = false;
  25876. this._animationStarted = false;
  25877. this._loopAnimation = false;
  25878. this._fromIndex = 0;
  25879. this._toIndex = 0;
  25880. this._delay = 0;
  25881. this._direction = 1;
  25882. this._frameCount = 0;
  25883. this._time = 0;
  25884. this._manager = manager;
  25885. this._manager.sprites.push(this);
  25886. this.position = BABYLON.Vector3.Zero();
  25887. }
  25888. Object.defineProperty(Sprite.prototype, "size", {
  25889. get: function () {
  25890. return this.width;
  25891. },
  25892. set: function (value) {
  25893. this.width = value;
  25894. this.height = value;
  25895. },
  25896. enumerable: true,
  25897. configurable: true
  25898. });
  25899. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25900. this._fromIndex = from;
  25901. this._toIndex = to;
  25902. this._loopAnimation = loop;
  25903. this._delay = delay;
  25904. this._animationStarted = true;
  25905. this._direction = from < to ? 1 : -1;
  25906. this.cellIndex = from;
  25907. this._time = 0;
  25908. };
  25909. Sprite.prototype.stopAnimation = function () {
  25910. this._animationStarted = false;
  25911. };
  25912. Sprite.prototype._animate = function (deltaTime) {
  25913. if (!this._animationStarted)
  25914. return;
  25915. this._time += deltaTime;
  25916. if (this._time > this._delay) {
  25917. this._time = this._time % this._delay;
  25918. this.cellIndex += this._direction;
  25919. if (this.cellIndex == this._toIndex) {
  25920. if (this._loopAnimation) {
  25921. this.cellIndex = this._fromIndex;
  25922. }
  25923. else {
  25924. this._animationStarted = false;
  25925. if (this.disposeWhenFinishedAnimating) {
  25926. this.dispose();
  25927. }
  25928. }
  25929. }
  25930. }
  25931. };
  25932. Sprite.prototype.dispose = function () {
  25933. for (var i = 0; i < this._manager.sprites.length; i++) {
  25934. if (this._manager.sprites[i] == this) {
  25935. this._manager.sprites.splice(i, 1);
  25936. }
  25937. }
  25938. };
  25939. return Sprite;
  25940. })();
  25941. BABYLON.Sprite = Sprite;
  25942. })(BABYLON || (BABYLON = {}));
  25943. var BABYLON;
  25944. (function (BABYLON) {
  25945. var Layer = (function () {
  25946. function Layer(name, imgUrl, scene, isBackground, color) {
  25947. this.name = name;
  25948. this.scale = new BABYLON.Vector2(1, 1);
  25949. this.offset = new BABYLON.Vector2(0, 0);
  25950. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25951. this._vertexBuffers = {};
  25952. // Events
  25953. /**
  25954. * An event triggered when the layer is disposed.
  25955. * @type {BABYLON.Observable}
  25956. */
  25957. this.onDisposeObservable = new BABYLON.Observable();
  25958. /**
  25959. * An event triggered before rendering the scene
  25960. * @type {BABYLON.Observable}
  25961. */
  25962. this.onBeforeRenderObservable = new BABYLON.Observable();
  25963. /**
  25964. * An event triggered after rendering the scene
  25965. * @type {BABYLON.Observable}
  25966. */
  25967. this.onAfterRenderObservable = new BABYLON.Observable();
  25968. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25969. this.isBackground = isBackground === undefined ? true : isBackground;
  25970. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25971. this._scene = scene;
  25972. this._scene.layers.push(this);
  25973. var engine = scene.getEngine();
  25974. // VBO
  25975. var vertices = [];
  25976. vertices.push(1, 1);
  25977. vertices.push(-1, 1);
  25978. vertices.push(-1, -1);
  25979. vertices.push(1, -1);
  25980. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  25982. // Indices
  25983. var indices = [];
  25984. indices.push(0);
  25985. indices.push(1);
  25986. indices.push(2);
  25987. indices.push(0);
  25988. indices.push(2);
  25989. indices.push(3);
  25990. this._indexBuffer = engine.createIndexBuffer(indices);
  25991. // Effects
  25992. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25993. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25994. }
  25995. Object.defineProperty(Layer.prototype, "onDispose", {
  25996. set: function (callback) {
  25997. if (this._onDisposeObserver) {
  25998. this.onDisposeObservable.remove(this._onDisposeObserver);
  25999. }
  26000. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26006. set: function (callback) {
  26007. if (this._onBeforeRenderObserver) {
  26008. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26009. }
  26010. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26016. set: function (callback) {
  26017. if (this._onAfterRenderObserver) {
  26018. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26019. }
  26020. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26021. },
  26022. enumerable: true,
  26023. configurable: true
  26024. });
  26025. Layer.prototype.render = function () {
  26026. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26027. // Check
  26028. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26029. return;
  26030. var engine = this._scene.getEngine();
  26031. this.onBeforeRenderObservable.notifyObservers(this);
  26032. // Render
  26033. engine.enableEffect(currentEffect);
  26034. engine.setState(false);
  26035. // Texture
  26036. currentEffect.setTexture("textureSampler", this.texture);
  26037. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26038. // Color
  26039. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26040. // Scale / offset
  26041. currentEffect.setVector2("offset", this.offset);
  26042. currentEffect.setVector2("scale", this.scale);
  26043. // VBOs
  26044. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26045. // Draw order
  26046. if (!this._alphaTestEffect) {
  26047. engine.setAlphaMode(this.alphaBlendingMode);
  26048. engine.draw(true, 0, 6);
  26049. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26050. }
  26051. else {
  26052. engine.draw(true, 0, 6);
  26053. }
  26054. this.onAfterRenderObservable.notifyObservers(this);
  26055. };
  26056. Layer.prototype.dispose = function () {
  26057. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26058. if (vertexBuffer) {
  26059. vertexBuffer.dispose();
  26060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26061. }
  26062. if (this._indexBuffer) {
  26063. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26064. this._indexBuffer = null;
  26065. }
  26066. if (this.texture) {
  26067. this.texture.dispose();
  26068. this.texture = null;
  26069. }
  26070. // Remove from scene
  26071. var index = this._scene.layers.indexOf(this);
  26072. this._scene.layers.splice(index, 1);
  26073. // Callback
  26074. this.onDisposeObservable.notifyObservers(this);
  26075. this.onDisposeObservable.clear();
  26076. this.onAfterRenderObservable.clear();
  26077. this.onBeforeRenderObservable.clear();
  26078. };
  26079. return Layer;
  26080. })();
  26081. BABYLON.Layer = Layer;
  26082. })(BABYLON || (BABYLON = {}));
  26083. var BABYLON;
  26084. (function (BABYLON) {
  26085. var Particle = (function () {
  26086. function Particle() {
  26087. this.position = BABYLON.Vector3.Zero();
  26088. this.direction = BABYLON.Vector3.Zero();
  26089. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26090. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26091. this.lifeTime = 1.0;
  26092. this.age = 0;
  26093. this.size = 0;
  26094. this.angle = 0;
  26095. this.angularSpeed = 0;
  26096. }
  26097. Particle.prototype.copyTo = function (other) {
  26098. other.position.copyFrom(this.position);
  26099. other.direction.copyFrom(this.direction);
  26100. other.color.copyFrom(this.color);
  26101. other.colorStep.copyFrom(this.colorStep);
  26102. other.lifeTime = this.lifeTime;
  26103. other.age = this.age;
  26104. other.size = this.size;
  26105. other.angle = this.angle;
  26106. other.angularSpeed = this.angularSpeed;
  26107. };
  26108. return Particle;
  26109. })();
  26110. BABYLON.Particle = Particle;
  26111. })(BABYLON || (BABYLON = {}));
  26112. var BABYLON;
  26113. (function (BABYLON) {
  26114. var randomNumber = function (min, max) {
  26115. if (min === max) {
  26116. return (min);
  26117. }
  26118. var random = Math.random();
  26119. return ((random * (max - min)) + min);
  26120. };
  26121. var ParticleSystem = (function () {
  26122. function ParticleSystem(name, capacity, scene, customEffect) {
  26123. var _this = this;
  26124. this.name = name;
  26125. // Members
  26126. this.animations = [];
  26127. this.renderingGroupId = 0;
  26128. this.emitter = null;
  26129. this.emitRate = 10;
  26130. this.manualEmitCount = -1;
  26131. this.updateSpeed = 0.01;
  26132. this.targetStopDuration = 0;
  26133. this.disposeOnStop = false;
  26134. this.minEmitPower = 1;
  26135. this.maxEmitPower = 1;
  26136. this.minLifeTime = 1;
  26137. this.maxLifeTime = 1;
  26138. this.minSize = 1;
  26139. this.maxSize = 1;
  26140. this.minAngularSpeed = 0;
  26141. this.maxAngularSpeed = 0;
  26142. this.layerMask = 0x0FFFFFFF;
  26143. /**
  26144. * An event triggered when the system is disposed.
  26145. * @type {BABYLON.Observable}
  26146. */
  26147. this.onDisposeObservable = new BABYLON.Observable();
  26148. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26149. this.forceDepthWrite = false;
  26150. this.gravity = BABYLON.Vector3.Zero();
  26151. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26152. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26153. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26154. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26155. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26156. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26157. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26158. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26159. this.particles = new Array();
  26160. this._stockParticles = new Array();
  26161. this._newPartsExcess = 0;
  26162. this._vertexBuffers = {};
  26163. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26164. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26165. this._scaledDirection = BABYLON.Vector3.Zero();
  26166. this._scaledGravity = BABYLON.Vector3.Zero();
  26167. this._currentRenderId = -1;
  26168. this._started = false;
  26169. this._stopped = false;
  26170. this._actualFrame = 0;
  26171. this.id = name;
  26172. this._capacity = capacity;
  26173. this._scene = scene;
  26174. this._customEffect = customEffect;
  26175. scene.particleSystems.push(this);
  26176. var indices = [];
  26177. var index = 0;
  26178. for (var count = 0; count < capacity; count++) {
  26179. indices.push(index);
  26180. indices.push(index + 1);
  26181. indices.push(index + 2);
  26182. indices.push(index);
  26183. indices.push(index + 2);
  26184. indices.push(index + 3);
  26185. index += 4;
  26186. }
  26187. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26188. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26189. this._vertexData = new Float32Array(capacity * 11 * 4);
  26190. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26191. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26192. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26193. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26195. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26196. this._vertexBuffers["options"] = options;
  26197. // Default behaviors
  26198. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26199. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26200. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26201. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26202. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26203. };
  26204. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26205. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26206. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26207. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26209. };
  26210. this.updateFunction = function (particles) {
  26211. for (var index = 0; index < particles.length; index++) {
  26212. var particle = particles[index];
  26213. particle.age += _this._scaledUpdateSpeed;
  26214. if (particle.age >= particle.lifeTime) {
  26215. _this.recycleParticle(particle);
  26216. index--;
  26217. continue;
  26218. }
  26219. else {
  26220. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26221. particle.color.addInPlace(_this._scaledColorStep);
  26222. if (particle.color.a < 0)
  26223. particle.color.a = 0;
  26224. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26225. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26226. particle.position.addInPlace(_this._scaledDirection);
  26227. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26228. particle.direction.addInPlace(_this._scaledGravity);
  26229. }
  26230. }
  26231. };
  26232. }
  26233. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26234. set: function (callback) {
  26235. if (this._onDisposeObserver) {
  26236. this.onDisposeObservable.remove(this._onDisposeObserver);
  26237. }
  26238. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26239. },
  26240. enumerable: true,
  26241. configurable: true
  26242. });
  26243. ParticleSystem.prototype.recycleParticle = function (particle) {
  26244. var lastParticle = this.particles.pop();
  26245. if (lastParticle !== particle) {
  26246. lastParticle.copyTo(particle);
  26247. this._stockParticles.push(lastParticle);
  26248. }
  26249. };
  26250. ParticleSystem.prototype.getCapacity = function () {
  26251. return this._capacity;
  26252. };
  26253. ParticleSystem.prototype.isAlive = function () {
  26254. return this._alive;
  26255. };
  26256. ParticleSystem.prototype.isStarted = function () {
  26257. return this._started;
  26258. };
  26259. ParticleSystem.prototype.start = function () {
  26260. this._started = true;
  26261. this._stopped = false;
  26262. this._actualFrame = 0;
  26263. };
  26264. ParticleSystem.prototype.stop = function () {
  26265. this._stopped = true;
  26266. };
  26267. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26268. var offset = index * 11;
  26269. this._vertexData[offset] = particle.position.x;
  26270. this._vertexData[offset + 1] = particle.position.y;
  26271. this._vertexData[offset + 2] = particle.position.z;
  26272. this._vertexData[offset + 3] = particle.color.r;
  26273. this._vertexData[offset + 4] = particle.color.g;
  26274. this._vertexData[offset + 5] = particle.color.b;
  26275. this._vertexData[offset + 6] = particle.color.a;
  26276. this._vertexData[offset + 7] = particle.angle;
  26277. this._vertexData[offset + 8] = particle.size;
  26278. this._vertexData[offset + 9] = offsetX;
  26279. this._vertexData[offset + 10] = offsetY;
  26280. };
  26281. ParticleSystem.prototype._update = function (newParticles) {
  26282. // Update current
  26283. this._alive = this.particles.length > 0;
  26284. this.updateFunction(this.particles);
  26285. // Add new ones
  26286. var worldMatrix;
  26287. if (this.emitter.position) {
  26288. worldMatrix = this.emitter.getWorldMatrix();
  26289. }
  26290. else {
  26291. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26292. }
  26293. var particle;
  26294. for (var index = 0; index < newParticles; index++) {
  26295. if (this.particles.length === this._capacity) {
  26296. break;
  26297. }
  26298. if (this._stockParticles.length !== 0) {
  26299. particle = this._stockParticles.pop();
  26300. particle.age = 0;
  26301. }
  26302. else {
  26303. particle = new BABYLON.Particle();
  26304. }
  26305. this.particles.push(particle);
  26306. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26307. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26308. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26309. particle.size = randomNumber(this.minSize, this.maxSize);
  26310. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26311. this.startPositionFunction(worldMatrix, particle.position, particle);
  26312. var step = randomNumber(0, 1.0);
  26313. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26314. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26315. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26316. }
  26317. };
  26318. ParticleSystem.prototype._getEffect = function () {
  26319. if (this._customEffect) {
  26320. return this._customEffect;
  26321. }
  26322. ;
  26323. var defines = [];
  26324. if (this._scene.clipPlane) {
  26325. defines.push("#define CLIPPLANE");
  26326. }
  26327. // Effect
  26328. var join = defines.join("\n");
  26329. if (this._cachedDefines !== join) {
  26330. this._cachedDefines = join;
  26331. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26332. }
  26333. return this._effect;
  26334. };
  26335. ParticleSystem.prototype.animate = function () {
  26336. if (!this._started)
  26337. return;
  26338. var effect = this._getEffect();
  26339. // Check
  26340. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26341. return;
  26342. if (this._currentRenderId === this._scene.getRenderId()) {
  26343. return;
  26344. }
  26345. this._currentRenderId = this._scene.getRenderId();
  26346. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26347. // determine the number of particles we need to create
  26348. var newParticles;
  26349. if (this.manualEmitCount > -1) {
  26350. newParticles = this.manualEmitCount;
  26351. this._newPartsExcess = 0;
  26352. this.manualEmitCount = 0;
  26353. }
  26354. else {
  26355. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26356. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26357. }
  26358. if (this._newPartsExcess > 1.0) {
  26359. newParticles += this._newPartsExcess >> 0;
  26360. this._newPartsExcess -= this._newPartsExcess >> 0;
  26361. }
  26362. this._alive = false;
  26363. if (!this._stopped) {
  26364. this._actualFrame += this._scaledUpdateSpeed;
  26365. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26366. this.stop();
  26367. }
  26368. else {
  26369. newParticles = 0;
  26370. }
  26371. this._update(newParticles);
  26372. // Stopped?
  26373. if (this._stopped) {
  26374. if (!this._alive) {
  26375. this._started = false;
  26376. if (this.disposeOnStop) {
  26377. this._scene._toBeDisposed.push(this);
  26378. }
  26379. }
  26380. }
  26381. // Update VBO
  26382. var offset = 0;
  26383. for (var index = 0; index < this.particles.length; index++) {
  26384. var particle = this.particles[index];
  26385. this._appendParticleVertex(offset++, particle, 0, 0);
  26386. this._appendParticleVertex(offset++, particle, 1, 0);
  26387. this._appendParticleVertex(offset++, particle, 1, 1);
  26388. this._appendParticleVertex(offset++, particle, 0, 1);
  26389. }
  26390. this._vertexBuffer.update(this._vertexData);
  26391. };
  26392. ParticleSystem.prototype.render = function () {
  26393. var effect = this._getEffect();
  26394. // Check
  26395. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26396. return 0;
  26397. var engine = this._scene.getEngine();
  26398. // Render
  26399. engine.enableEffect(effect);
  26400. engine.setState(false);
  26401. var viewMatrix = this._scene.getViewMatrix();
  26402. effect.setTexture("diffuseSampler", this.particleTexture);
  26403. effect.setMatrix("view", viewMatrix);
  26404. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26405. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26406. if (this._scene.clipPlane) {
  26407. var clipPlane = this._scene.clipPlane;
  26408. var invView = viewMatrix.clone();
  26409. invView.invert();
  26410. effect.setMatrix("invView", invView);
  26411. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26412. }
  26413. // VBOs
  26414. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26415. // Draw order
  26416. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26417. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26418. }
  26419. else {
  26420. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26421. }
  26422. if (this.forceDepthWrite) {
  26423. engine.setDepthWrite(true);
  26424. }
  26425. engine.draw(true, 0, this.particles.length * 6);
  26426. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26427. return this.particles.length;
  26428. };
  26429. ParticleSystem.prototype.dispose = function () {
  26430. if (this._vertexBuffer) {
  26431. this._vertexBuffer.dispose();
  26432. this._vertexBuffer = null;
  26433. }
  26434. if (this._indexBuffer) {
  26435. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26436. this._indexBuffer = null;
  26437. }
  26438. if (this.particleTexture) {
  26439. this.particleTexture.dispose();
  26440. this.particleTexture = null;
  26441. }
  26442. // Remove from scene
  26443. var index = this._scene.particleSystems.indexOf(this);
  26444. this._scene.particleSystems.splice(index, 1);
  26445. // Callback
  26446. this.onDisposeObservable.notifyObservers(this);
  26447. this.onDisposeObservable.clear();
  26448. };
  26449. // Clone
  26450. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26451. var result = new ParticleSystem(name, this._capacity, this._scene);
  26452. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26453. if (newEmitter === undefined) {
  26454. newEmitter = this.emitter;
  26455. }
  26456. result.emitter = newEmitter;
  26457. if (this.particleTexture) {
  26458. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26459. }
  26460. result.start();
  26461. return result;
  26462. };
  26463. ParticleSystem.prototype.serialize = function () {
  26464. var serializationObject = {};
  26465. serializationObject.name = this.name;
  26466. serializationObject.id = this.id;
  26467. // Emitter
  26468. if (this.emitter.position) {
  26469. serializationObject.emitterId = this.emitter.id;
  26470. }
  26471. else {
  26472. serializationObject.emitter = this.emitter.asArray();
  26473. }
  26474. serializationObject.capacity = this.getCapacity();
  26475. if (this.particleTexture) {
  26476. serializationObject.textureName = this.particleTexture.name;
  26477. }
  26478. // Animations
  26479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26480. // Particle system
  26481. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26482. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26483. serializationObject.minSize = this.minSize;
  26484. serializationObject.maxSize = this.maxSize;
  26485. serializationObject.minEmitPower = this.minEmitPower;
  26486. serializationObject.maxEmitPower = this.maxEmitPower;
  26487. serializationObject.minLifeTime = this.minLifeTime;
  26488. serializationObject.maxLifeTime = this.maxLifeTime;
  26489. serializationObject.emitRate = this.emitRate;
  26490. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26491. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26492. serializationObject.gravity = this.gravity.asArray();
  26493. serializationObject.direction1 = this.direction1.asArray();
  26494. serializationObject.direction2 = this.direction2.asArray();
  26495. serializationObject.color1 = this.color1.asArray();
  26496. serializationObject.color2 = this.color2.asArray();
  26497. serializationObject.colorDead = this.colorDead.asArray();
  26498. serializationObject.updateSpeed = this.updateSpeed;
  26499. serializationObject.targetStopDuration = this.targetStopDuration;
  26500. serializationObject.textureMask = this.textureMask.asArray();
  26501. serializationObject.blendMode = this.blendMode;
  26502. return serializationObject;
  26503. };
  26504. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26505. var name = parsedParticleSystem.name;
  26506. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26507. if (parsedParticleSystem.id) {
  26508. particleSystem.id = parsedParticleSystem.id;
  26509. }
  26510. // Texture
  26511. if (parsedParticleSystem.textureName) {
  26512. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26513. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26514. }
  26515. // Emitter
  26516. if (parsedParticleSystem.emitterId) {
  26517. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26518. }
  26519. else {
  26520. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26521. }
  26522. // Animations
  26523. if (parsedParticleSystem.animations) {
  26524. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26525. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26526. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26527. }
  26528. }
  26529. if (parsedParticleSystem.autoAnimate) {
  26530. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26531. }
  26532. // Particle system
  26533. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26534. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26535. particleSystem.minSize = parsedParticleSystem.minSize;
  26536. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26537. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26538. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26539. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26540. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26541. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26542. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26543. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26544. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26545. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26546. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26547. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26548. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26549. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26550. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26551. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26552. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26553. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26554. if (!parsedParticleSystem.preventAutoStart) {
  26555. particleSystem.start();
  26556. }
  26557. return particleSystem;
  26558. };
  26559. // Statics
  26560. ParticleSystem.BLENDMODE_ONEONE = 0;
  26561. ParticleSystem.BLENDMODE_STANDARD = 1;
  26562. return ParticleSystem;
  26563. })();
  26564. BABYLON.ParticleSystem = ParticleSystem;
  26565. })(BABYLON || (BABYLON = {}));
  26566. var BABYLON;
  26567. (function (BABYLON) {
  26568. var AnimationRange = (function () {
  26569. function AnimationRange(name, from, to) {
  26570. this.name = name;
  26571. this.from = from;
  26572. this.to = to;
  26573. }
  26574. AnimationRange.prototype.clone = function () {
  26575. return new AnimationRange(this.name, this.from, this.to);
  26576. };
  26577. return AnimationRange;
  26578. })();
  26579. BABYLON.AnimationRange = AnimationRange;
  26580. /**
  26581. * Composed of a frame, and an action function
  26582. */
  26583. var AnimationEvent = (function () {
  26584. function AnimationEvent(frame, action, onlyOnce) {
  26585. this.frame = frame;
  26586. this.action = action;
  26587. this.onlyOnce = onlyOnce;
  26588. this.isDone = false;
  26589. }
  26590. return AnimationEvent;
  26591. })();
  26592. BABYLON.AnimationEvent = AnimationEvent;
  26593. var PathCursor = (function () {
  26594. function PathCursor(path) {
  26595. this.path = path;
  26596. this._onchange = new Array();
  26597. this.value = 0;
  26598. this.animations = new Array();
  26599. }
  26600. PathCursor.prototype.getPoint = function () {
  26601. var point = this.path.getPointAtLengthPosition(this.value);
  26602. return new BABYLON.Vector3(point.x, 0, point.y);
  26603. };
  26604. PathCursor.prototype.moveAhead = function (step) {
  26605. if (step === void 0) { step = 0.002; }
  26606. this.move(step);
  26607. return this;
  26608. };
  26609. PathCursor.prototype.moveBack = function (step) {
  26610. if (step === void 0) { step = 0.002; }
  26611. this.move(-step);
  26612. return this;
  26613. };
  26614. PathCursor.prototype.move = function (step) {
  26615. if (Math.abs(step) > 1) {
  26616. throw "step size should be less than 1.";
  26617. }
  26618. this.value += step;
  26619. this.ensureLimits();
  26620. this.raiseOnChange();
  26621. return this;
  26622. };
  26623. PathCursor.prototype.ensureLimits = function () {
  26624. while (this.value > 1) {
  26625. this.value -= 1;
  26626. }
  26627. while (this.value < 0) {
  26628. this.value += 1;
  26629. }
  26630. return this;
  26631. };
  26632. // used by animation engine
  26633. PathCursor.prototype.markAsDirty = function (propertyName) {
  26634. this.ensureLimits();
  26635. this.raiseOnChange();
  26636. return this;
  26637. };
  26638. PathCursor.prototype.raiseOnChange = function () {
  26639. var _this = this;
  26640. this._onchange.forEach(function (f) { return f(_this); });
  26641. return this;
  26642. };
  26643. PathCursor.prototype.onchange = function (f) {
  26644. this._onchange.push(f);
  26645. return this;
  26646. };
  26647. return PathCursor;
  26648. })();
  26649. BABYLON.PathCursor = PathCursor;
  26650. var Animation = (function () {
  26651. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26652. this.name = name;
  26653. this.targetProperty = targetProperty;
  26654. this.framePerSecond = framePerSecond;
  26655. this.dataType = dataType;
  26656. this.loopMode = loopMode;
  26657. this.enableBlending = enableBlending;
  26658. this._offsetsCache = {};
  26659. this._highLimitsCache = {};
  26660. this._stopped = false;
  26661. this._blendingFactor = 0;
  26662. // The set of event that will be linked to this animation
  26663. this._events = new Array();
  26664. this.allowMatricesInterpolation = false;
  26665. this.blendingSpeed = 0.01;
  26666. this._ranges = {};
  26667. this.targetPropertyPath = targetProperty.split(".");
  26668. this.dataType = dataType;
  26669. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26670. }
  26671. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26672. var dataType = undefined;
  26673. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26674. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26675. }
  26676. else if (from instanceof BABYLON.Quaternion) {
  26677. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26678. }
  26679. else if (from instanceof BABYLON.Vector3) {
  26680. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26681. }
  26682. else if (from instanceof BABYLON.Vector2) {
  26683. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26684. }
  26685. else if (from instanceof BABYLON.Color3) {
  26686. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26687. }
  26688. else if (from instanceof BABYLON.Size) {
  26689. dataType = Animation.ANIMATIONTYPE_SIZE;
  26690. }
  26691. if (dataType == undefined) {
  26692. return null;
  26693. }
  26694. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26695. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26696. animation.setKeys(keys);
  26697. if (easingFunction !== undefined) {
  26698. animation.setEasingFunction(easingFunction);
  26699. }
  26700. return animation;
  26701. };
  26702. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26703. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26704. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26705. };
  26706. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26707. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26708. node.animations.push(animation);
  26709. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26710. };
  26711. // Methods
  26712. /**
  26713. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26714. */
  26715. Animation.prototype.toString = function (fullDetails) {
  26716. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26717. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26718. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26719. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26720. if (fullDetails) {
  26721. ret += ", Ranges: {";
  26722. var first = true;
  26723. for (var name in this._ranges) {
  26724. if (first) {
  26725. ret += ", ";
  26726. first = false;
  26727. }
  26728. ret += name;
  26729. }
  26730. ret += "}";
  26731. }
  26732. return ret;
  26733. };
  26734. /**
  26735. * Add an event to this animation.
  26736. */
  26737. Animation.prototype.addEvent = function (event) {
  26738. this._events.push(event);
  26739. };
  26740. /**
  26741. * Remove all events found at the given frame
  26742. * @param frame
  26743. */
  26744. Animation.prototype.removeEvents = function (frame) {
  26745. for (var index = 0; index < this._events.length; index++) {
  26746. if (this._events[index].frame === frame) {
  26747. this._events.splice(index, 1);
  26748. index--;
  26749. }
  26750. }
  26751. };
  26752. Animation.prototype.createRange = function (name, from, to) {
  26753. // check name not already in use; could happen for bones after serialized
  26754. if (!this._ranges[name]) {
  26755. this._ranges[name] = new AnimationRange(name, from, to);
  26756. }
  26757. };
  26758. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26759. if (deleteFrames === void 0) { deleteFrames = true; }
  26760. if (this._ranges[name]) {
  26761. if (deleteFrames) {
  26762. var from = this._ranges[name].from;
  26763. var to = this._ranges[name].to;
  26764. // this loop MUST go high to low for multiple splices to work
  26765. for (var key = this._keys.length - 1; key >= 0; key--) {
  26766. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26767. this._keys.splice(key, 1);
  26768. }
  26769. }
  26770. }
  26771. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26772. }
  26773. };
  26774. Animation.prototype.getRange = function (name) {
  26775. return this._ranges[name];
  26776. };
  26777. Animation.prototype.reset = function () {
  26778. this._offsetsCache = {};
  26779. this._highLimitsCache = {};
  26780. this.currentFrame = 0;
  26781. this._blendingFactor = 0;
  26782. this._originalBlendValue = null;
  26783. };
  26784. Animation.prototype.isStopped = function () {
  26785. return this._stopped;
  26786. };
  26787. Animation.prototype.getKeys = function () {
  26788. return this._keys;
  26789. };
  26790. Animation.prototype.getHighestFrame = function () {
  26791. var ret = 0;
  26792. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26793. if (ret < this._keys[key].frame) {
  26794. ret = this._keys[key].frame;
  26795. }
  26796. }
  26797. return ret;
  26798. };
  26799. Animation.prototype.getEasingFunction = function () {
  26800. return this._easingFunction;
  26801. };
  26802. Animation.prototype.setEasingFunction = function (easingFunction) {
  26803. this._easingFunction = easingFunction;
  26804. };
  26805. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26806. return startValue + (endValue - startValue) * gradient;
  26807. };
  26808. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26809. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26810. };
  26811. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26812. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26813. };
  26814. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26815. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26816. };
  26817. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26818. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26819. };
  26820. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26821. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26822. };
  26823. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26824. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26825. };
  26826. Animation.prototype.clone = function () {
  26827. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26828. if (this._keys) {
  26829. clone.setKeys(this._keys);
  26830. }
  26831. if (this._ranges) {
  26832. clone._ranges = {};
  26833. for (var name in this._ranges) {
  26834. clone._ranges[name] = this._ranges[name].clone();
  26835. }
  26836. }
  26837. return clone;
  26838. };
  26839. Animation.prototype.setKeys = function (values) {
  26840. this._keys = values.slice(0);
  26841. this._offsetsCache = {};
  26842. this._highLimitsCache = {};
  26843. };
  26844. Animation.prototype._getKeyValue = function (value) {
  26845. if (typeof value === "function") {
  26846. return value();
  26847. }
  26848. return value;
  26849. };
  26850. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26851. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26852. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26853. }
  26854. this.currentFrame = currentFrame;
  26855. // Try to get a hash to find the right key
  26856. 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));
  26857. if (this._keys[startKey].frame >= currentFrame) {
  26858. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26859. startKey--;
  26860. }
  26861. }
  26862. for (var key = startKey; key < this._keys.length; key++) {
  26863. if (this._keys[key + 1].frame >= currentFrame) {
  26864. var startValue = this._getKeyValue(this._keys[key].value);
  26865. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26866. // gradient : percent of currentFrame between the frame inf and the frame sup
  26867. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26868. // check for easingFunction and correction of gradient
  26869. if (this._easingFunction != null) {
  26870. gradient = this._easingFunction.ease(gradient);
  26871. }
  26872. switch (this.dataType) {
  26873. // Float
  26874. case Animation.ANIMATIONTYPE_FLOAT:
  26875. switch (loopMode) {
  26876. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26877. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26878. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26879. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26880. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26881. }
  26882. break;
  26883. // Quaternion
  26884. case Animation.ANIMATIONTYPE_QUATERNION:
  26885. var quaternion = null;
  26886. switch (loopMode) {
  26887. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26888. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26889. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26890. break;
  26891. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26892. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26893. break;
  26894. }
  26895. return quaternion;
  26896. // Vector3
  26897. case Animation.ANIMATIONTYPE_VECTOR3:
  26898. switch (loopMode) {
  26899. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26900. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26901. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26902. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26903. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26904. }
  26905. // Vector2
  26906. case Animation.ANIMATIONTYPE_VECTOR2:
  26907. switch (loopMode) {
  26908. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26909. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26910. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26911. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26912. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26913. }
  26914. // Size
  26915. case Animation.ANIMATIONTYPE_SIZE:
  26916. switch (loopMode) {
  26917. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26918. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26919. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26920. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26921. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26922. }
  26923. // Color3
  26924. case Animation.ANIMATIONTYPE_COLOR3:
  26925. switch (loopMode) {
  26926. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26927. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26928. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26929. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26930. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26931. }
  26932. // Matrix
  26933. case Animation.ANIMATIONTYPE_MATRIX:
  26934. switch (loopMode) {
  26935. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26936. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26937. if (this.allowMatricesInterpolation) {
  26938. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26939. }
  26940. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26941. return startValue;
  26942. }
  26943. default:
  26944. break;
  26945. }
  26946. break;
  26947. }
  26948. }
  26949. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26950. };
  26951. Animation.prototype.setValue = function (currentValue, blend) {
  26952. if (blend === void 0) { blend = false; }
  26953. // Set value
  26954. var path;
  26955. var destination;
  26956. if (this.targetPropertyPath.length > 1) {
  26957. var property = this._target[this.targetPropertyPath[0]];
  26958. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26959. property = property[this.targetPropertyPath[index]];
  26960. }
  26961. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26962. destination = property;
  26963. }
  26964. else {
  26965. path = this.targetPropertyPath[0];
  26966. destination = this._target;
  26967. }
  26968. // Blending
  26969. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26970. if (!this._originalBlendValue) {
  26971. if (destination[path].clone) {
  26972. this._originalBlendValue = destination[path].clone();
  26973. }
  26974. else {
  26975. this._originalBlendValue = destination[path];
  26976. }
  26977. }
  26978. if (this._originalBlendValue.prototype) {
  26979. if (this._originalBlendValue.prototype.Lerp) {
  26980. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26981. }
  26982. else {
  26983. destination[path] = currentValue;
  26984. }
  26985. }
  26986. else if (this._originalBlendValue.m) {
  26987. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26988. }
  26989. else {
  26990. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26991. }
  26992. this._blendingFactor += this.blendingSpeed;
  26993. }
  26994. else {
  26995. destination[path] = currentValue;
  26996. }
  26997. if (this._target.markAsDirty) {
  26998. this._target.markAsDirty(this.targetProperty);
  26999. }
  27000. };
  27001. Animation.prototype.goToFrame = function (frame) {
  27002. if (frame < this._keys[0].frame) {
  27003. frame = this._keys[0].frame;
  27004. }
  27005. else if (frame > this._keys[this._keys.length - 1].frame) {
  27006. frame = this._keys[this._keys.length - 1].frame;
  27007. }
  27008. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27009. this.setValue(currentValue);
  27010. };
  27011. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27012. if (blend === void 0) { blend = false; }
  27013. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27014. this._stopped = true;
  27015. return false;
  27016. }
  27017. var returnValue = true;
  27018. // Adding a start key at frame 0 if missing
  27019. if (this._keys[0].frame !== 0) {
  27020. var newKey = { frame: 0, value: this._keys[0].value };
  27021. this._keys.splice(0, 0, newKey);
  27022. }
  27023. // Check limits
  27024. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27025. from = this._keys[0].frame;
  27026. }
  27027. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27028. to = this._keys[this._keys.length - 1].frame;
  27029. }
  27030. // Compute ratio
  27031. var range = to - from;
  27032. var offsetValue;
  27033. // ratio represents the frame delta between from and to
  27034. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27035. var highLimitValue = 0;
  27036. if (ratio > range && !loop) {
  27037. returnValue = false;
  27038. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27039. }
  27040. else {
  27041. // Get max value if required
  27042. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27043. var keyOffset = to.toString() + from.toString();
  27044. if (!this._offsetsCache[keyOffset]) {
  27045. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27046. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27047. switch (this.dataType) {
  27048. // Float
  27049. case Animation.ANIMATIONTYPE_FLOAT:
  27050. this._offsetsCache[keyOffset] = toValue - fromValue;
  27051. break;
  27052. // Quaternion
  27053. case Animation.ANIMATIONTYPE_QUATERNION:
  27054. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27055. break;
  27056. // Vector3
  27057. case Animation.ANIMATIONTYPE_VECTOR3:
  27058. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27059. // Vector2
  27060. case Animation.ANIMATIONTYPE_VECTOR2:
  27061. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27062. // Size
  27063. case Animation.ANIMATIONTYPE_SIZE:
  27064. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27065. // Color3
  27066. case Animation.ANIMATIONTYPE_COLOR3:
  27067. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27068. default:
  27069. break;
  27070. }
  27071. this._highLimitsCache[keyOffset] = toValue;
  27072. }
  27073. highLimitValue = this._highLimitsCache[keyOffset];
  27074. offsetValue = this._offsetsCache[keyOffset];
  27075. }
  27076. }
  27077. if (offsetValue === undefined) {
  27078. switch (this.dataType) {
  27079. // Float
  27080. case Animation.ANIMATIONTYPE_FLOAT:
  27081. offsetValue = 0;
  27082. break;
  27083. // Quaternion
  27084. case Animation.ANIMATIONTYPE_QUATERNION:
  27085. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27086. break;
  27087. // Vector3
  27088. case Animation.ANIMATIONTYPE_VECTOR3:
  27089. offsetValue = BABYLON.Vector3.Zero();
  27090. break;
  27091. // Vector2
  27092. case Animation.ANIMATIONTYPE_VECTOR2:
  27093. offsetValue = BABYLON.Vector2.Zero();
  27094. break;
  27095. // Size
  27096. case Animation.ANIMATIONTYPE_SIZE:
  27097. offsetValue = BABYLON.Size.Zero();
  27098. break;
  27099. // Color3
  27100. case Animation.ANIMATIONTYPE_COLOR3:
  27101. offsetValue = BABYLON.Color3.Black();
  27102. }
  27103. }
  27104. // Compute value
  27105. var repeatCount = (ratio / range) >> 0;
  27106. var currentFrame = returnValue ? from + ratio % range : to;
  27107. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27108. // Set value
  27109. this.setValue(currentValue);
  27110. // Check events
  27111. for (var index = 0; index < this._events.length; index++) {
  27112. if (currentFrame >= this._events[index].frame) {
  27113. var event = this._events[index];
  27114. if (!event.isDone) {
  27115. // If event should be done only once, remove it.
  27116. if (event.onlyOnce) {
  27117. this._events.splice(index, 1);
  27118. index--;
  27119. }
  27120. event.isDone = true;
  27121. event.action();
  27122. } // Don't do anything if the event has already be done.
  27123. }
  27124. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27125. // reset event, the animation is looping
  27126. this._events[index].isDone = false;
  27127. }
  27128. }
  27129. if (!returnValue) {
  27130. this._stopped = true;
  27131. }
  27132. return returnValue;
  27133. };
  27134. Animation.prototype.serialize = function () {
  27135. var serializationObject = {};
  27136. serializationObject.name = this.name;
  27137. serializationObject.property = this.targetProperty;
  27138. serializationObject.framePerSecond = this.framePerSecond;
  27139. serializationObject.dataType = this.dataType;
  27140. serializationObject.loopBehavior = this.loopMode;
  27141. var dataType = this.dataType;
  27142. serializationObject.keys = [];
  27143. var keys = this.getKeys();
  27144. for (var index = 0; index < keys.length; index++) {
  27145. var animationKey = keys[index];
  27146. var key = {};
  27147. key.frame = animationKey.frame;
  27148. switch (dataType) {
  27149. case Animation.ANIMATIONTYPE_FLOAT:
  27150. key.values = [animationKey.value];
  27151. break;
  27152. case Animation.ANIMATIONTYPE_QUATERNION:
  27153. case Animation.ANIMATIONTYPE_MATRIX:
  27154. case Animation.ANIMATIONTYPE_VECTOR3:
  27155. case Animation.ANIMATIONTYPE_COLOR3:
  27156. key.values = animationKey.value.asArray();
  27157. break;
  27158. }
  27159. serializationObject.keys.push(key);
  27160. }
  27161. serializationObject.ranges = [];
  27162. for (var name in this._ranges) {
  27163. var range = {};
  27164. range.name = name;
  27165. range.from = this._ranges[name].from;
  27166. range.to = this._ranges[name].to;
  27167. serializationObject.ranges.push(range);
  27168. }
  27169. return serializationObject;
  27170. };
  27171. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27172. get: function () {
  27173. return Animation._ANIMATIONTYPE_FLOAT;
  27174. },
  27175. enumerable: true,
  27176. configurable: true
  27177. });
  27178. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27179. get: function () {
  27180. return Animation._ANIMATIONTYPE_VECTOR3;
  27181. },
  27182. enumerable: true,
  27183. configurable: true
  27184. });
  27185. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27186. get: function () {
  27187. return Animation._ANIMATIONTYPE_VECTOR2;
  27188. },
  27189. enumerable: true,
  27190. configurable: true
  27191. });
  27192. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27193. get: function () {
  27194. return Animation._ANIMATIONTYPE_SIZE;
  27195. },
  27196. enumerable: true,
  27197. configurable: true
  27198. });
  27199. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27200. get: function () {
  27201. return Animation._ANIMATIONTYPE_QUATERNION;
  27202. },
  27203. enumerable: true,
  27204. configurable: true
  27205. });
  27206. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27207. get: function () {
  27208. return Animation._ANIMATIONTYPE_MATRIX;
  27209. },
  27210. enumerable: true,
  27211. configurable: true
  27212. });
  27213. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27214. get: function () {
  27215. return Animation._ANIMATIONTYPE_COLOR3;
  27216. },
  27217. enumerable: true,
  27218. configurable: true
  27219. });
  27220. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27221. get: function () {
  27222. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27223. },
  27224. enumerable: true,
  27225. configurable: true
  27226. });
  27227. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27228. get: function () {
  27229. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27230. },
  27231. enumerable: true,
  27232. configurable: true
  27233. });
  27234. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27235. get: function () {
  27236. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27237. },
  27238. enumerable: true,
  27239. configurable: true
  27240. });
  27241. Animation.Parse = function (parsedAnimation) {
  27242. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27243. var dataType = parsedAnimation.dataType;
  27244. var keys = [];
  27245. var data;
  27246. var index;
  27247. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27248. var key = parsedAnimation.keys[index];
  27249. switch (dataType) {
  27250. case Animation.ANIMATIONTYPE_FLOAT:
  27251. data = key.values[0];
  27252. break;
  27253. case Animation.ANIMATIONTYPE_QUATERNION:
  27254. data = BABYLON.Quaternion.FromArray(key.values);
  27255. break;
  27256. case Animation.ANIMATIONTYPE_MATRIX:
  27257. data = BABYLON.Matrix.FromArray(key.values);
  27258. break;
  27259. case Animation.ANIMATIONTYPE_COLOR3:
  27260. data = BABYLON.Color3.FromArray(key.values);
  27261. break;
  27262. case Animation.ANIMATIONTYPE_VECTOR3:
  27263. default:
  27264. data = BABYLON.Vector3.FromArray(key.values);
  27265. break;
  27266. }
  27267. keys.push({
  27268. frame: key.frame,
  27269. value: data
  27270. });
  27271. }
  27272. animation.setKeys(keys);
  27273. if (parsedAnimation.ranges) {
  27274. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27275. data = parsedAnimation.ranges[index];
  27276. animation.createRange(data.name, data.from, data.to);
  27277. }
  27278. }
  27279. return animation;
  27280. };
  27281. Animation.AppendSerializedAnimations = function (source, destination) {
  27282. if (source.animations) {
  27283. destination.animations = [];
  27284. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27285. var animation = source.animations[animationIndex];
  27286. destination.animations.push(animation.serialize());
  27287. }
  27288. }
  27289. };
  27290. // Statics
  27291. Animation._ANIMATIONTYPE_FLOAT = 0;
  27292. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27293. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27294. Animation._ANIMATIONTYPE_MATRIX = 3;
  27295. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27296. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27297. Animation._ANIMATIONTYPE_SIZE = 6;
  27298. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27299. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27300. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27301. return Animation;
  27302. })();
  27303. BABYLON.Animation = Animation;
  27304. })(BABYLON || (BABYLON = {}));
  27305. var BABYLON;
  27306. (function (BABYLON) {
  27307. var Animatable = (function () {
  27308. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27309. if (fromFrame === void 0) { fromFrame = 0; }
  27310. if (toFrame === void 0) { toFrame = 100; }
  27311. if (loopAnimation === void 0) { loopAnimation = false; }
  27312. if (speedRatio === void 0) { speedRatio = 1.0; }
  27313. this.target = target;
  27314. this.fromFrame = fromFrame;
  27315. this.toFrame = toFrame;
  27316. this.loopAnimation = loopAnimation;
  27317. this.speedRatio = speedRatio;
  27318. this.onAnimationEnd = onAnimationEnd;
  27319. this._animations = new Array();
  27320. this._paused = false;
  27321. this.animationStarted = false;
  27322. if (animations) {
  27323. this.appendAnimations(target, animations);
  27324. }
  27325. this._scene = scene;
  27326. scene._activeAnimatables.push(this);
  27327. }
  27328. // Methods
  27329. Animatable.prototype.getAnimations = function () {
  27330. return this._animations;
  27331. };
  27332. Animatable.prototype.appendAnimations = function (target, animations) {
  27333. for (var index = 0; index < animations.length; index++) {
  27334. var animation = animations[index];
  27335. animation._target = target;
  27336. this._animations.push(animation);
  27337. }
  27338. };
  27339. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27340. var animations = this._animations;
  27341. for (var index = 0; index < animations.length; index++) {
  27342. if (animations[index].targetProperty === property) {
  27343. return animations[index];
  27344. }
  27345. }
  27346. return null;
  27347. };
  27348. Animatable.prototype.reset = function () {
  27349. var animations = this._animations;
  27350. for (var index = 0; index < animations.length; index++) {
  27351. animations[index].reset();
  27352. }
  27353. this._localDelayOffset = null;
  27354. this._pausedDelay = null;
  27355. };
  27356. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27357. var animations = this._animations;
  27358. for (var index = 0; index < animations.length; index++) {
  27359. animations[index].enableBlending = true;
  27360. animations[index].blendingSpeed = blendingSpeed;
  27361. }
  27362. };
  27363. Animatable.prototype.disableBlending = function () {
  27364. var animations = this._animations;
  27365. for (var index = 0; index < animations.length; index++) {
  27366. animations[index].enableBlending = false;
  27367. }
  27368. };
  27369. Animatable.prototype.goToFrame = function (frame) {
  27370. var animations = this._animations;
  27371. for (var index = 0; index < animations.length; index++) {
  27372. animations[index].goToFrame(frame);
  27373. }
  27374. };
  27375. Animatable.prototype.pause = function () {
  27376. if (this._paused) {
  27377. return;
  27378. }
  27379. this._paused = true;
  27380. };
  27381. Animatable.prototype.restart = function () {
  27382. this._paused = false;
  27383. };
  27384. Animatable.prototype.stop = function () {
  27385. var index = this._scene._activeAnimatables.indexOf(this);
  27386. if (index > -1) {
  27387. this._scene._activeAnimatables.splice(index, 1);
  27388. var animations = this._animations;
  27389. for (var index = 0; index < animations.length; index++) {
  27390. animations[index].reset();
  27391. }
  27392. if (this.onAnimationEnd) {
  27393. this.onAnimationEnd();
  27394. }
  27395. }
  27396. };
  27397. Animatable.prototype._animate = function (delay) {
  27398. if (this._paused) {
  27399. this.animationStarted = false;
  27400. if (!this._pausedDelay) {
  27401. this._pausedDelay = delay;
  27402. }
  27403. return true;
  27404. }
  27405. if (!this._localDelayOffset) {
  27406. this._localDelayOffset = delay;
  27407. }
  27408. else if (this._pausedDelay) {
  27409. this._localDelayOffset += delay - this._pausedDelay;
  27410. this._pausedDelay = null;
  27411. }
  27412. // Animating
  27413. var running = false;
  27414. var animations = this._animations;
  27415. var index;
  27416. for (index = 0; index < animations.length; index++) {
  27417. var animation = animations[index];
  27418. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27419. running = running || isRunning;
  27420. }
  27421. this.animationStarted = running;
  27422. if (!running) {
  27423. // Remove from active animatables
  27424. index = this._scene._activeAnimatables.indexOf(this);
  27425. this._scene._activeAnimatables.splice(index, 1);
  27426. }
  27427. if (!running && this.onAnimationEnd) {
  27428. this.onAnimationEnd();
  27429. this.onAnimationEnd = null;
  27430. }
  27431. return running;
  27432. };
  27433. return Animatable;
  27434. })();
  27435. BABYLON.Animatable = Animatable;
  27436. })(BABYLON || (BABYLON = {}));
  27437. var BABYLON;
  27438. (function (BABYLON) {
  27439. var EasingFunction = (function () {
  27440. function EasingFunction() {
  27441. // Properties
  27442. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27443. }
  27444. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27445. get: function () {
  27446. return EasingFunction._EASINGMODE_EASEIN;
  27447. },
  27448. enumerable: true,
  27449. configurable: true
  27450. });
  27451. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27452. get: function () {
  27453. return EasingFunction._EASINGMODE_EASEOUT;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27459. get: function () {
  27460. return EasingFunction._EASINGMODE_EASEINOUT;
  27461. },
  27462. enumerable: true,
  27463. configurable: true
  27464. });
  27465. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27466. var n = Math.min(Math.max(easingMode, 0), 2);
  27467. this._easingMode = n;
  27468. };
  27469. EasingFunction.prototype.getEasingMode = function () {
  27470. return this._easingMode;
  27471. };
  27472. EasingFunction.prototype.easeInCore = function (gradient) {
  27473. throw new Error('You must implement this method');
  27474. };
  27475. EasingFunction.prototype.ease = function (gradient) {
  27476. switch (this._easingMode) {
  27477. case EasingFunction.EASINGMODE_EASEIN:
  27478. return this.easeInCore(gradient);
  27479. case EasingFunction.EASINGMODE_EASEOUT:
  27480. return (1 - this.easeInCore(1 - gradient));
  27481. }
  27482. if (gradient >= 0.5) {
  27483. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27484. }
  27485. return (this.easeInCore(gradient * 2) * 0.5);
  27486. };
  27487. //Statics
  27488. EasingFunction._EASINGMODE_EASEIN = 0;
  27489. EasingFunction._EASINGMODE_EASEOUT = 1;
  27490. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27491. return EasingFunction;
  27492. })();
  27493. BABYLON.EasingFunction = EasingFunction;
  27494. var CircleEase = (function (_super) {
  27495. __extends(CircleEase, _super);
  27496. function CircleEase() {
  27497. _super.apply(this, arguments);
  27498. }
  27499. CircleEase.prototype.easeInCore = function (gradient) {
  27500. gradient = Math.max(0, Math.min(1, gradient));
  27501. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27502. };
  27503. return CircleEase;
  27504. })(EasingFunction);
  27505. BABYLON.CircleEase = CircleEase;
  27506. var BackEase = (function (_super) {
  27507. __extends(BackEase, _super);
  27508. function BackEase(amplitude) {
  27509. if (amplitude === void 0) { amplitude = 1; }
  27510. _super.call(this);
  27511. this.amplitude = amplitude;
  27512. }
  27513. BackEase.prototype.easeInCore = function (gradient) {
  27514. var num = Math.max(0, this.amplitude);
  27515. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27516. };
  27517. return BackEase;
  27518. })(EasingFunction);
  27519. BABYLON.BackEase = BackEase;
  27520. var BounceEase = (function (_super) {
  27521. __extends(BounceEase, _super);
  27522. function BounceEase(bounces, bounciness) {
  27523. if (bounces === void 0) { bounces = 3; }
  27524. if (bounciness === void 0) { bounciness = 2; }
  27525. _super.call(this);
  27526. this.bounces = bounces;
  27527. this.bounciness = bounciness;
  27528. }
  27529. BounceEase.prototype.easeInCore = function (gradient) {
  27530. var y = Math.max(0.0, this.bounces);
  27531. var bounciness = this.bounciness;
  27532. if (bounciness <= 1.0) {
  27533. bounciness = 1.001;
  27534. }
  27535. var num9 = Math.pow(bounciness, y);
  27536. var num5 = 1.0 - bounciness;
  27537. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27538. var num15 = gradient * num4;
  27539. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27540. var num3 = Math.floor(num65);
  27541. var num13 = num3 + 1.0;
  27542. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27543. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27544. var num7 = (num8 + num12) * 0.5;
  27545. var num6 = gradient - num7;
  27546. var num2 = num7 - num8;
  27547. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27548. };
  27549. return BounceEase;
  27550. })(EasingFunction);
  27551. BABYLON.BounceEase = BounceEase;
  27552. var CubicEase = (function (_super) {
  27553. __extends(CubicEase, _super);
  27554. function CubicEase() {
  27555. _super.apply(this, arguments);
  27556. }
  27557. CubicEase.prototype.easeInCore = function (gradient) {
  27558. return (gradient * gradient * gradient);
  27559. };
  27560. return CubicEase;
  27561. })(EasingFunction);
  27562. BABYLON.CubicEase = CubicEase;
  27563. var ElasticEase = (function (_super) {
  27564. __extends(ElasticEase, _super);
  27565. function ElasticEase(oscillations, springiness) {
  27566. if (oscillations === void 0) { oscillations = 3; }
  27567. if (springiness === void 0) { springiness = 3; }
  27568. _super.call(this);
  27569. this.oscillations = oscillations;
  27570. this.springiness = springiness;
  27571. }
  27572. ElasticEase.prototype.easeInCore = function (gradient) {
  27573. var num2;
  27574. var num3 = Math.max(0.0, this.oscillations);
  27575. var num = Math.max(0.0, this.springiness);
  27576. if (num == 0) {
  27577. num2 = gradient;
  27578. }
  27579. else {
  27580. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27581. }
  27582. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27583. };
  27584. return ElasticEase;
  27585. })(EasingFunction);
  27586. BABYLON.ElasticEase = ElasticEase;
  27587. var ExponentialEase = (function (_super) {
  27588. __extends(ExponentialEase, _super);
  27589. function ExponentialEase(exponent) {
  27590. if (exponent === void 0) { exponent = 2; }
  27591. _super.call(this);
  27592. this.exponent = exponent;
  27593. }
  27594. ExponentialEase.prototype.easeInCore = function (gradient) {
  27595. if (this.exponent <= 0) {
  27596. return gradient;
  27597. }
  27598. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27599. };
  27600. return ExponentialEase;
  27601. })(EasingFunction);
  27602. BABYLON.ExponentialEase = ExponentialEase;
  27603. var PowerEase = (function (_super) {
  27604. __extends(PowerEase, _super);
  27605. function PowerEase(power) {
  27606. if (power === void 0) { power = 2; }
  27607. _super.call(this);
  27608. this.power = power;
  27609. }
  27610. PowerEase.prototype.easeInCore = function (gradient) {
  27611. var y = Math.max(0.0, this.power);
  27612. return Math.pow(gradient, y);
  27613. };
  27614. return PowerEase;
  27615. })(EasingFunction);
  27616. BABYLON.PowerEase = PowerEase;
  27617. var QuadraticEase = (function (_super) {
  27618. __extends(QuadraticEase, _super);
  27619. function QuadraticEase() {
  27620. _super.apply(this, arguments);
  27621. }
  27622. QuadraticEase.prototype.easeInCore = function (gradient) {
  27623. return (gradient * gradient);
  27624. };
  27625. return QuadraticEase;
  27626. })(EasingFunction);
  27627. BABYLON.QuadraticEase = QuadraticEase;
  27628. var QuarticEase = (function (_super) {
  27629. __extends(QuarticEase, _super);
  27630. function QuarticEase() {
  27631. _super.apply(this, arguments);
  27632. }
  27633. QuarticEase.prototype.easeInCore = function (gradient) {
  27634. return (gradient * gradient * gradient * gradient);
  27635. };
  27636. return QuarticEase;
  27637. })(EasingFunction);
  27638. BABYLON.QuarticEase = QuarticEase;
  27639. var QuinticEase = (function (_super) {
  27640. __extends(QuinticEase, _super);
  27641. function QuinticEase() {
  27642. _super.apply(this, arguments);
  27643. }
  27644. QuinticEase.prototype.easeInCore = function (gradient) {
  27645. return (gradient * gradient * gradient * gradient * gradient);
  27646. };
  27647. return QuinticEase;
  27648. })(EasingFunction);
  27649. BABYLON.QuinticEase = QuinticEase;
  27650. var SineEase = (function (_super) {
  27651. __extends(SineEase, _super);
  27652. function SineEase() {
  27653. _super.apply(this, arguments);
  27654. }
  27655. SineEase.prototype.easeInCore = function (gradient) {
  27656. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27657. };
  27658. return SineEase;
  27659. })(EasingFunction);
  27660. BABYLON.SineEase = SineEase;
  27661. var BezierCurveEase = (function (_super) {
  27662. __extends(BezierCurveEase, _super);
  27663. function BezierCurveEase(x1, y1, x2, y2) {
  27664. if (x1 === void 0) { x1 = 0; }
  27665. if (y1 === void 0) { y1 = 0; }
  27666. if (x2 === void 0) { x2 = 1; }
  27667. if (y2 === void 0) { y2 = 1; }
  27668. _super.call(this);
  27669. this.x1 = x1;
  27670. this.y1 = y1;
  27671. this.x2 = x2;
  27672. this.y2 = y2;
  27673. }
  27674. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27675. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27676. };
  27677. return BezierCurveEase;
  27678. })(EasingFunction);
  27679. BABYLON.BezierCurveEase = BezierCurveEase;
  27680. })(BABYLON || (BABYLON = {}));
  27681. var BABYLON;
  27682. (function (BABYLON) {
  27683. var Bone = (function (_super) {
  27684. __extends(Bone, _super);
  27685. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27686. _super.call(this, name, skeleton.getScene());
  27687. this.name = name;
  27688. this.children = new Array();
  27689. this.animations = new Array();
  27690. this._worldTransform = new BABYLON.Matrix();
  27691. this._absoluteTransform = new BABYLON.Matrix();
  27692. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27693. this._skeleton = skeleton;
  27694. this._matrix = matrix;
  27695. this._baseMatrix = matrix;
  27696. this._restPose = restPose ? restPose : matrix.clone();
  27697. skeleton.bones.push(this);
  27698. if (parentBone) {
  27699. this._parent = parentBone;
  27700. parentBone.children.push(this);
  27701. }
  27702. else {
  27703. this._parent = null;
  27704. }
  27705. this._updateDifferenceMatrix();
  27706. }
  27707. // Members
  27708. Bone.prototype.getParent = function () {
  27709. return this._parent;
  27710. };
  27711. Bone.prototype.getLocalMatrix = function () {
  27712. return this._matrix;
  27713. };
  27714. Bone.prototype.getBaseMatrix = function () {
  27715. return this._baseMatrix;
  27716. };
  27717. Bone.prototype.getRestPose = function () {
  27718. return this._restPose;
  27719. };
  27720. Bone.prototype.returnToRest = function () {
  27721. this.updateMatrix(this._restPose.clone());
  27722. };
  27723. Bone.prototype.getWorldMatrix = function () {
  27724. return this._worldTransform;
  27725. };
  27726. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27727. return this._invertedAbsoluteTransform;
  27728. };
  27729. Bone.prototype.getAbsoluteTransform = function () {
  27730. return this._absoluteTransform;
  27731. };
  27732. // Methods
  27733. Bone.prototype.updateMatrix = function (matrix) {
  27734. this._baseMatrix = matrix.clone();
  27735. this._matrix = matrix.clone();
  27736. this._skeleton._markAsDirty();
  27737. this._updateDifferenceMatrix();
  27738. };
  27739. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27740. if (!rootMatrix) {
  27741. rootMatrix = this._baseMatrix;
  27742. }
  27743. if (this._parent) {
  27744. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27745. }
  27746. else {
  27747. this._absoluteTransform.copyFrom(rootMatrix);
  27748. }
  27749. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27750. for (var index = 0; index < this.children.length; index++) {
  27751. this.children[index]._updateDifferenceMatrix();
  27752. }
  27753. };
  27754. Bone.prototype.markAsDirty = function () {
  27755. this._currentRenderId++;
  27756. this._skeleton._markAsDirty();
  27757. };
  27758. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  27759. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27760. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  27761. // all animation may be coming from a library skeleton, so may need to create animation
  27762. if (this.animations.length === 0) {
  27763. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27764. this.animations[0].setKeys([]);
  27765. }
  27766. // get animation info / verify there is such a range from the source bone
  27767. var sourceRange = source.animations[0].getRange(rangeName);
  27768. if (!sourceRange) {
  27769. return false;
  27770. }
  27771. var from = sourceRange.from;
  27772. var to = sourceRange.to;
  27773. var sourceKeys = source.animations[0].getKeys();
  27774. // rescaling prep
  27775. var sourceBoneLength = source.length;
  27776. var sourceParent = source.getParent();
  27777. var parent = this.getParent();
  27778. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27779. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  27780. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  27781. var destKeys = this.animations[0].getKeys();
  27782. // loop vars declaration
  27783. var orig;
  27784. var origTranslation;
  27785. var mat;
  27786. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27787. orig = sourceKeys[key];
  27788. if (orig.frame >= from && orig.frame <= to) {
  27789. if (rescaleAsRequired) {
  27790. mat = orig.value.clone();
  27791. // scale based on parent ratio, when bone has parent
  27792. if (parentScalingReqd) {
  27793. origTranslation = mat.getTranslation();
  27794. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  27795. }
  27796. else if (dimensionsScalingReqd) {
  27797. origTranslation = mat.getTranslation();
  27798. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  27799. }
  27800. else {
  27801. mat = orig.value;
  27802. }
  27803. }
  27804. else {
  27805. mat = orig.value;
  27806. }
  27807. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27808. }
  27809. }
  27810. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27811. return true;
  27812. };
  27813. return Bone;
  27814. })(BABYLON.Node);
  27815. BABYLON.Bone = Bone;
  27816. })(BABYLON || (BABYLON = {}));
  27817. var BABYLON;
  27818. (function (BABYLON) {
  27819. var Skeleton = (function () {
  27820. function Skeleton(name, id, scene) {
  27821. this.name = name;
  27822. this.id = id;
  27823. this.bones = new Array();
  27824. this.needInitialSkinMatrix = false;
  27825. this._isDirty = true;
  27826. this._meshesWithPoseMatrix = new Array();
  27827. this._identity = BABYLON.Matrix.Identity();
  27828. this._ranges = {};
  27829. this.bones = [];
  27830. this._scene = scene;
  27831. scene.skeletons.push(this);
  27832. //make sure it will recalculate the matrix next time prepare is called.
  27833. this._isDirty = true;
  27834. }
  27835. // Members
  27836. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27837. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27838. return mesh._bonesTransformMatrices;
  27839. }
  27840. return this._transformMatrices;
  27841. };
  27842. Skeleton.prototype.getScene = function () {
  27843. return this._scene;
  27844. };
  27845. // Methods
  27846. /**
  27847. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27848. */
  27849. Skeleton.prototype.toString = function (fullDetails) {
  27850. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27851. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27852. if (fullDetails) {
  27853. ret += ", Ranges: {";
  27854. var first = true;
  27855. for (var name_1 in this._ranges) {
  27856. if (first) {
  27857. ret += ", ";
  27858. first = false;
  27859. }
  27860. ret += name_1;
  27861. }
  27862. ret += "}";
  27863. }
  27864. return ret;
  27865. };
  27866. /**
  27867. * Get bone's index searching by name
  27868. * @param {string} name is bone's name to search for
  27869. * @return {number} Indice of the bone. Returns -1 if not found
  27870. */
  27871. Skeleton.prototype.getBoneIndexByName = function (name) {
  27872. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27873. if (this.bones[boneIndex].name === name) {
  27874. return boneIndex;
  27875. }
  27876. }
  27877. return -1;
  27878. };
  27879. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27880. // check name not already in use
  27881. if (!this._ranges[name]) {
  27882. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27883. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27884. if (this.bones[i].animations[0]) {
  27885. this.bones[i].animations[0].createRange(name, from, to);
  27886. }
  27887. }
  27888. }
  27889. };
  27890. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27891. if (deleteFrames === void 0) { deleteFrames = true; }
  27892. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27893. if (this.bones[i].animations[0]) {
  27894. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27895. }
  27896. }
  27897. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27898. };
  27899. Skeleton.prototype.getAnimationRange = function (name) {
  27900. return this._ranges[name];
  27901. };
  27902. /**
  27903. * Returns as an Array, all AnimationRanges defined on this skeleton
  27904. */
  27905. Skeleton.prototype.getAnimationRanges = function () {
  27906. var animationRanges = [];
  27907. var name;
  27908. var i = 0;
  27909. for (name in this._ranges) {
  27910. animationRanges[i] = this._ranges[name];
  27911. i++;
  27912. }
  27913. return animationRanges;
  27914. };
  27915. /**
  27916. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27917. */
  27918. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27919. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27920. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27921. return false;
  27922. }
  27923. var ret = true;
  27924. var frameOffset = this._getHighestAnimationFrame() + 1;
  27925. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27926. var boneDict = {};
  27927. var sourceBones = source.bones;
  27928. var nBones;
  27929. var i;
  27930. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27931. boneDict[sourceBones[i].name] = sourceBones[i];
  27932. }
  27933. if (this.bones.length !== sourceBones.length) {
  27934. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27935. ret = false;
  27936. }
  27937. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  27938. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27939. var boneName = this.bones[i].name;
  27940. var sourceBone = boneDict[boneName];
  27941. if (sourceBone) {
  27942. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  27943. }
  27944. else {
  27945. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27946. ret = false;
  27947. }
  27948. }
  27949. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27950. var range = source.getAnimationRange(name);
  27951. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27952. return ret;
  27953. };
  27954. Skeleton.prototype.returnToRest = function () {
  27955. for (var index = 0; index < this.bones.length; index++) {
  27956. this.bones[index].returnToRest();
  27957. }
  27958. };
  27959. Skeleton.prototype._getHighestAnimationFrame = function () {
  27960. var ret = 0;
  27961. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27962. if (this.bones[i].animations[0]) {
  27963. var highest = this.bones[i].animations[0].getHighestFrame();
  27964. if (ret < highest) {
  27965. ret = highest;
  27966. }
  27967. }
  27968. }
  27969. return ret;
  27970. };
  27971. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27972. var range = this.getAnimationRange(name);
  27973. if (!range) {
  27974. return null;
  27975. }
  27976. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27977. };
  27978. Skeleton.prototype._markAsDirty = function () {
  27979. this._isDirty = true;
  27980. };
  27981. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27982. this._meshesWithPoseMatrix.push(mesh);
  27983. };
  27984. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27985. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27986. if (index > -1) {
  27987. this._meshesWithPoseMatrix.splice(index, 1);
  27988. }
  27989. };
  27990. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27991. for (var index = 0; index < this.bones.length; index++) {
  27992. var bone = this.bones[index];
  27993. var parentBone = bone.getParent();
  27994. if (parentBone) {
  27995. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27996. }
  27997. else {
  27998. if (initialSkinMatrix) {
  27999. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28000. }
  28001. else {
  28002. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28003. }
  28004. }
  28005. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28006. }
  28007. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28008. };
  28009. Skeleton.prototype.prepare = function () {
  28010. if (!this._isDirty) {
  28011. return;
  28012. }
  28013. if (this.needInitialSkinMatrix) {
  28014. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28015. var mesh = this._meshesWithPoseMatrix[index];
  28016. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28017. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28018. }
  28019. var poseMatrix = mesh.getPoseMatrix();
  28020. // Prepare bones
  28021. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28022. var bone = this.bones[boneIndex];
  28023. if (!bone.getParent()) {
  28024. var matrix = bone.getBaseMatrix();
  28025. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28026. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28027. }
  28028. }
  28029. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28030. }
  28031. }
  28032. else {
  28033. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28034. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28035. }
  28036. this._computeTransformMatrices(this._transformMatrices, null);
  28037. }
  28038. this._isDirty = false;
  28039. this._scene._activeBones.addCount(this.bones.length, false);
  28040. };
  28041. Skeleton.prototype.getAnimatables = function () {
  28042. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28043. this._animatables = [];
  28044. for (var index = 0; index < this.bones.length; index++) {
  28045. this._animatables.push(this.bones[index]);
  28046. }
  28047. }
  28048. return this._animatables;
  28049. };
  28050. Skeleton.prototype.clone = function (name, id) {
  28051. var result = new Skeleton(name, id || name, this._scene);
  28052. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28053. for (var index = 0; index < this.bones.length; index++) {
  28054. var source = this.bones[index];
  28055. var parentBone = null;
  28056. if (source.getParent()) {
  28057. var parentIndex = this.bones.indexOf(source.getParent());
  28058. parentBone = result.bones[parentIndex];
  28059. }
  28060. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28061. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28062. }
  28063. if (this._ranges) {
  28064. result._ranges = {};
  28065. for (var rangeName in this._ranges) {
  28066. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28067. }
  28068. }
  28069. this._isDirty = true;
  28070. return result;
  28071. };
  28072. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28073. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28074. this.bones.forEach(function (bone) {
  28075. bone.animations.forEach(function (animation) {
  28076. animation.enableBlending = true;
  28077. animation.blendingSpeed = blendingSpeed;
  28078. });
  28079. });
  28080. };
  28081. Skeleton.prototype.dispose = function () {
  28082. this._meshesWithPoseMatrix = [];
  28083. // Animations
  28084. this.getScene().stopAnimation(this);
  28085. // Remove from scene
  28086. this.getScene().removeSkeleton(this);
  28087. };
  28088. Skeleton.prototype.serialize = function () {
  28089. var serializationObject = {};
  28090. serializationObject.name = this.name;
  28091. serializationObject.id = this.id;
  28092. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28093. serializationObject.bones = [];
  28094. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28095. for (var index = 0; index < this.bones.length; index++) {
  28096. var bone = this.bones[index];
  28097. var serializedBone = {
  28098. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28099. name: bone.name,
  28100. matrix: bone.getLocalMatrix().toArray(),
  28101. rest: bone.getRestPose().toArray()
  28102. };
  28103. serializationObject.bones.push(serializedBone);
  28104. if (bone.length) {
  28105. serializedBone.length = bone.length;
  28106. }
  28107. if (bone.animations && bone.animations.length > 0) {
  28108. serializedBone.animation = bone.animations[0].serialize();
  28109. }
  28110. serializationObject.ranges = [];
  28111. for (var name in this._ranges) {
  28112. var range = {};
  28113. range.name = name;
  28114. range.from = this._ranges[name].from;
  28115. range.to = this._ranges[name].to;
  28116. serializationObject.ranges.push(range);
  28117. }
  28118. }
  28119. return serializationObject;
  28120. };
  28121. Skeleton.Parse = function (parsedSkeleton, scene) {
  28122. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28123. if (parsedSkeleton.dimensionsAtRest) {
  28124. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28125. }
  28126. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28127. var index;
  28128. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28129. var parsedBone = parsedSkeleton.bones[index];
  28130. var parentBone = null;
  28131. if (parsedBone.parentBoneIndex > -1) {
  28132. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28133. }
  28134. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28135. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28136. if (parsedBone.length) {
  28137. bone.length = parsedBone.length;
  28138. }
  28139. if (parsedBone.animation) {
  28140. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28141. }
  28142. }
  28143. // placed after bones, so createAnimationRange can cascade down
  28144. if (parsedSkeleton.ranges) {
  28145. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28146. var data = parsedSkeleton.ranges[index];
  28147. skeleton.createAnimationRange(data.name, data.from, data.to);
  28148. }
  28149. }
  28150. return skeleton;
  28151. };
  28152. return Skeleton;
  28153. })();
  28154. BABYLON.Skeleton = Skeleton;
  28155. })(BABYLON || (BABYLON = {}));
  28156. var BABYLON;
  28157. (function (BABYLON) {
  28158. var PostProcess = (function () {
  28159. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28162. this.name = name;
  28163. this.width = -1;
  28164. this.height = -1;
  28165. /*
  28166. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28167. Can only be used on a single postprocess or on the last one of a chain.
  28168. */
  28169. this.enablePixelPerfectMode = false;
  28170. this._reusable = false;
  28171. this._textures = new BABYLON.SmartArray(2);
  28172. this._currentRenderTextureInd = 0;
  28173. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28174. // Events
  28175. /**
  28176. * An event triggered when the postprocess is activated.
  28177. * @type {BABYLON.Observable}
  28178. */
  28179. this.onActivateObservable = new BABYLON.Observable();
  28180. /**
  28181. * An event triggered when the postprocess changes its size.
  28182. * @type {BABYLON.Observable}
  28183. */
  28184. this.onSizeChangedObservable = new BABYLON.Observable();
  28185. /**
  28186. * An event triggered when the postprocess applies its effect.
  28187. * @type {BABYLON.Observable}
  28188. */
  28189. this.onApplyObservable = new BABYLON.Observable();
  28190. /**
  28191. * An event triggered before rendering the postprocess
  28192. * @type {BABYLON.Observable}
  28193. */
  28194. this.onBeforeRenderObservable = new BABYLON.Observable();
  28195. /**
  28196. * An event triggered after rendering the postprocess
  28197. * @type {BABYLON.Observable}
  28198. */
  28199. this.onAfterRenderObservable = new BABYLON.Observable();
  28200. if (camera != null) {
  28201. this._camera = camera;
  28202. this._scene = camera.getScene();
  28203. camera.attachPostProcess(this);
  28204. this._engine = this._scene.getEngine();
  28205. }
  28206. else {
  28207. this._engine = engine;
  28208. }
  28209. this._options = options;
  28210. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28211. this._reusable = reusable || false;
  28212. this._textureType = textureType;
  28213. this._samplers = samplers || [];
  28214. this._samplers.push("textureSampler");
  28215. this._fragmentUrl = fragmentUrl;
  28216. this._parameters = parameters || [];
  28217. this._parameters.push("scale");
  28218. this.updateEffect(defines);
  28219. }
  28220. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28221. set: function (callback) {
  28222. if (this._onActivateObserver) {
  28223. this.onActivateObservable.remove(this._onActivateObserver);
  28224. }
  28225. this._onActivateObserver = this.onActivateObservable.add(callback);
  28226. },
  28227. enumerable: true,
  28228. configurable: true
  28229. });
  28230. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28231. set: function (callback) {
  28232. if (this._onSizeChangedObserver) {
  28233. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28234. }
  28235. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28236. },
  28237. enumerable: true,
  28238. configurable: true
  28239. });
  28240. Object.defineProperty(PostProcess.prototype, "onApply", {
  28241. set: function (callback) {
  28242. if (this._onApplyObserver) {
  28243. this.onApplyObservable.remove(this._onApplyObserver);
  28244. }
  28245. this._onApplyObserver = this.onApplyObservable.add(callback);
  28246. },
  28247. enumerable: true,
  28248. configurable: true
  28249. });
  28250. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28251. set: function (callback) {
  28252. if (this._onBeforeRenderObserver) {
  28253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28254. }
  28255. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28256. },
  28257. enumerable: true,
  28258. configurable: true
  28259. });
  28260. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28261. set: function (callback) {
  28262. if (this._onAfterRenderObserver) {
  28263. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28264. }
  28265. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28266. },
  28267. enumerable: true,
  28268. configurable: true
  28269. });
  28270. PostProcess.prototype.updateEffect = function (defines) {
  28271. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28272. };
  28273. PostProcess.prototype.isReusable = function () {
  28274. return this._reusable;
  28275. };
  28276. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28277. PostProcess.prototype.markTextureDirty = function () {
  28278. this.width = -1;
  28279. };
  28280. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28281. camera = camera || this._camera;
  28282. var scene = camera.getScene();
  28283. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28284. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28285. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28286. var desiredWidth = this._options.width || requiredWidth;
  28287. var desiredHeight = this._options.height || requiredHeight;
  28288. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28289. if (!this._options.width) {
  28290. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28291. }
  28292. if (!this._options.height) {
  28293. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28294. }
  28295. }
  28296. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28297. if (this._textures.length > 0) {
  28298. for (var i = 0; i < this._textures.length; i++) {
  28299. this._engine._releaseTexture(this._textures.data[i]);
  28300. }
  28301. this._textures.reset();
  28302. }
  28303. this.width = desiredWidth;
  28304. this.height = desiredHeight;
  28305. 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 }));
  28306. if (this._reusable) {
  28307. 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 }));
  28308. }
  28309. this.onSizeChangedObservable.notifyObservers(this);
  28310. }
  28311. if (this.enablePixelPerfectMode) {
  28312. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28313. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28314. }
  28315. else {
  28316. this._scaleRatio.copyFromFloats(1, 1);
  28317. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28318. }
  28319. this.onActivateObservable.notifyObservers(camera);
  28320. // Clear
  28321. if (this.clearColor) {
  28322. this._engine.clear(this.clearColor, true, true);
  28323. }
  28324. else {
  28325. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28326. }
  28327. if (this._reusable) {
  28328. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28329. }
  28330. };
  28331. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28332. get: function () {
  28333. return this._effect.isSupported;
  28334. },
  28335. enumerable: true,
  28336. configurable: true
  28337. });
  28338. PostProcess.prototype.apply = function () {
  28339. // Check
  28340. if (!this._effect.isReady())
  28341. return null;
  28342. // States
  28343. this._engine.enableEffect(this._effect);
  28344. this._engine.setState(false);
  28345. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28346. this._engine.setDepthBuffer(false);
  28347. this._engine.setDepthWrite(false);
  28348. // Texture
  28349. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28350. // Parameters
  28351. this._effect.setVector2("scale", this._scaleRatio);
  28352. this.onApplyObservable.notifyObservers(this._effect);
  28353. return this._effect;
  28354. };
  28355. PostProcess.prototype.dispose = function (camera) {
  28356. camera = camera || this._camera;
  28357. if (this._textures.length > 0) {
  28358. for (var i = 0; i < this._textures.length; i++) {
  28359. this._engine._releaseTexture(this._textures.data[i]);
  28360. }
  28361. this._textures.reset();
  28362. }
  28363. if (!camera) {
  28364. return;
  28365. }
  28366. camera.detachPostProcess(this);
  28367. var index = camera._postProcesses.indexOf(this);
  28368. if (index === 0 && camera._postProcesses.length > 0) {
  28369. this._camera._postProcesses[0].markTextureDirty();
  28370. }
  28371. this.onActivateObservable.clear();
  28372. this.onAfterRenderObservable.clear();
  28373. this.onApplyObservable.clear();
  28374. this.onBeforeRenderObservable.clear();
  28375. this.onSizeChangedObservable.clear();
  28376. };
  28377. return PostProcess;
  28378. })();
  28379. BABYLON.PostProcess = PostProcess;
  28380. })(BABYLON || (BABYLON = {}));
  28381. var BABYLON;
  28382. (function (BABYLON) {
  28383. var PostProcessManager = (function () {
  28384. function PostProcessManager(scene) {
  28385. this._vertexBuffers = {};
  28386. this._scene = scene;
  28387. }
  28388. PostProcessManager.prototype._prepareBuffers = function () {
  28389. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28390. return;
  28391. }
  28392. // VBO
  28393. var vertices = [];
  28394. vertices.push(1, 1);
  28395. vertices.push(-1, 1);
  28396. vertices.push(-1, -1);
  28397. vertices.push(1, -1);
  28398. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28399. // Indices
  28400. var indices = [];
  28401. indices.push(0);
  28402. indices.push(1);
  28403. indices.push(2);
  28404. indices.push(0);
  28405. indices.push(2);
  28406. indices.push(3);
  28407. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28408. };
  28409. // Methods
  28410. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28411. var postProcesses = this._scene.activeCamera._postProcesses;
  28412. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28413. return false;
  28414. }
  28415. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28416. return true;
  28417. };
  28418. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28419. var engine = this._scene.getEngine();
  28420. for (var index = 0; index < postProcesses.length; index++) {
  28421. if (index < postProcesses.length - 1) {
  28422. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28423. }
  28424. else {
  28425. if (targetTexture) {
  28426. engine.bindFramebuffer(targetTexture);
  28427. }
  28428. else {
  28429. engine.restoreDefaultFramebuffer();
  28430. }
  28431. }
  28432. var pp = postProcesses[index];
  28433. var effect = pp.apply();
  28434. if (effect) {
  28435. pp.onBeforeRenderObservable.notifyObservers(effect);
  28436. // VBOs
  28437. this._prepareBuffers();
  28438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28439. // Draw order
  28440. engine.draw(true, 0, 6);
  28441. pp.onAfterRenderObservable.notifyObservers(effect);
  28442. }
  28443. }
  28444. // Restore depth buffer
  28445. engine.setDepthBuffer(true);
  28446. engine.setDepthWrite(true);
  28447. };
  28448. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28449. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28450. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28451. return;
  28452. }
  28453. var engine = this._scene.getEngine();
  28454. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28455. if (index < len - 1) {
  28456. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28457. }
  28458. else {
  28459. if (targetTexture) {
  28460. engine.bindFramebuffer(targetTexture, faceIndex);
  28461. }
  28462. else {
  28463. engine.restoreDefaultFramebuffer();
  28464. }
  28465. }
  28466. if (doNotPresent) {
  28467. break;
  28468. }
  28469. var pp = postProcesses[index];
  28470. var effect = pp.apply();
  28471. if (effect) {
  28472. pp.onBeforeRenderObservable.notifyObservers(effect);
  28473. // VBOs
  28474. this._prepareBuffers();
  28475. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28476. // Draw order
  28477. engine.draw(true, 0, 6);
  28478. pp.onAfterRenderObservable.notifyObservers(effect);
  28479. }
  28480. }
  28481. // Restore depth buffer
  28482. engine.setDepthBuffer(true);
  28483. engine.setDepthWrite(true);
  28484. };
  28485. PostProcessManager.prototype.dispose = function () {
  28486. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28487. if (buffer) {
  28488. buffer.dispose();
  28489. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28490. }
  28491. if (this._indexBuffer) {
  28492. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28493. this._indexBuffer = null;
  28494. }
  28495. };
  28496. return PostProcessManager;
  28497. })();
  28498. BABYLON.PostProcessManager = PostProcessManager;
  28499. })(BABYLON || (BABYLON = {}));
  28500. var BABYLON;
  28501. (function (BABYLON) {
  28502. var PassPostProcess = (function (_super) {
  28503. __extends(PassPostProcess, _super);
  28504. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28505. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28506. }
  28507. return PassPostProcess;
  28508. })(BABYLON.PostProcess);
  28509. BABYLON.PassPostProcess = PassPostProcess;
  28510. })(BABYLON || (BABYLON = {}));
  28511. var BABYLON;
  28512. (function (BABYLON) {
  28513. /**
  28514. * This is a holder class for the physics joint created by the physics plugin.
  28515. * It holds a set of functions to control the underlying joint.
  28516. */
  28517. var PhysicsJoint = (function () {
  28518. function PhysicsJoint(type, jointData) {
  28519. this.type = type;
  28520. this.jointData = jointData;
  28521. jointData.nativeParams = jointData.nativeParams || {};
  28522. }
  28523. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28524. get: function () {
  28525. return this._physicsJoint;
  28526. },
  28527. set: function (newJoint) {
  28528. if (this._physicsJoint) {
  28529. }
  28530. this._physicsJoint = newJoint;
  28531. },
  28532. enumerable: true,
  28533. configurable: true
  28534. });
  28535. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28536. set: function (physicsPlugin) {
  28537. this._physicsPlugin = physicsPlugin;
  28538. },
  28539. enumerable: true,
  28540. configurable: true
  28541. });
  28542. /**
  28543. * Execute a function that is physics-plugin specific.
  28544. * @param {Function} func the function that will be executed.
  28545. * It accepts two parameters: the physics world and the physics joint.
  28546. */
  28547. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28548. func(this._physicsPlugin.world, this._physicsJoint);
  28549. };
  28550. //TODO check if the native joints are the same
  28551. //Joint Types
  28552. PhysicsJoint.DistanceJoint = 0;
  28553. PhysicsJoint.HingeJoint = 1;
  28554. PhysicsJoint.BallAndSocketJoint = 2;
  28555. PhysicsJoint.WheelJoint = 3;
  28556. PhysicsJoint.SliderJoint = 4;
  28557. //OIMO
  28558. PhysicsJoint.PrismaticJoint = 5;
  28559. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28560. PhysicsJoint.UniversalJoint = 6;
  28561. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28562. //Cannon
  28563. //Similar to a Ball-Joint. Different in params
  28564. PhysicsJoint.PointToPointJoint = 8;
  28565. //Cannon only at the moment
  28566. PhysicsJoint.SpringJoint = 9;
  28567. PhysicsJoint.LockJoint = 10;
  28568. return PhysicsJoint;
  28569. })();
  28570. BABYLON.PhysicsJoint = PhysicsJoint;
  28571. /**
  28572. * A class representing a physics distance joint.
  28573. */
  28574. var DistanceJoint = (function (_super) {
  28575. __extends(DistanceJoint, _super);
  28576. function DistanceJoint(jointData) {
  28577. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28578. }
  28579. /**
  28580. * Update the predefined distance.
  28581. */
  28582. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28583. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28584. };
  28585. return DistanceJoint;
  28586. })(PhysicsJoint);
  28587. BABYLON.DistanceJoint = DistanceJoint;
  28588. var MotorEnabledJoint = (function (_super) {
  28589. __extends(MotorEnabledJoint, _super);
  28590. function MotorEnabledJoint(type, jointData) {
  28591. _super.call(this, type, jointData);
  28592. }
  28593. /**
  28594. * Set the motor values.
  28595. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28596. * @param {number} force the force to apply
  28597. * @param {number} maxForce max force for this motor.
  28598. */
  28599. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28600. this._physicsPlugin.setMotor(this, force, maxForce);
  28601. };
  28602. /**
  28603. * Set the motor's limits.
  28604. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28605. */
  28606. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28607. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28608. };
  28609. return MotorEnabledJoint;
  28610. })(PhysicsJoint);
  28611. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28612. /**
  28613. * This class represents a single hinge physics joint
  28614. */
  28615. var HingeJoint = (function (_super) {
  28616. __extends(HingeJoint, _super);
  28617. function HingeJoint(jointData) {
  28618. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28619. }
  28620. /**
  28621. * Set the motor values.
  28622. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28623. * @param {number} force the force to apply
  28624. * @param {number} maxForce max force for this motor.
  28625. */
  28626. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28627. this._physicsPlugin.setMotor(this, force, maxForce);
  28628. };
  28629. /**
  28630. * Set the motor's limits.
  28631. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28632. */
  28633. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28634. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28635. };
  28636. return HingeJoint;
  28637. })(MotorEnabledJoint);
  28638. BABYLON.HingeJoint = HingeJoint;
  28639. /**
  28640. * This class represents a dual hinge physics joint (same as wheel joint)
  28641. */
  28642. var Hinge2Joint = (function (_super) {
  28643. __extends(Hinge2Joint, _super);
  28644. function Hinge2Joint(jointData) {
  28645. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28646. }
  28647. /**
  28648. * Set the motor values.
  28649. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28650. * @param {number} force the force to apply
  28651. * @param {number} maxForce max force for this motor.
  28652. * @param {motorIndex} the motor's index, 0 or 1.
  28653. */
  28654. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28655. if (motorIndex === void 0) { motorIndex = 0; }
  28656. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28657. };
  28658. /**
  28659. * Set the motor limits.
  28660. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28661. * @param {number} upperLimit the upper limit
  28662. * @param {number} lowerLimit lower limit
  28663. * @param {motorIndex} the motor's index, 0 or 1.
  28664. */
  28665. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28666. if (motorIndex === void 0) { motorIndex = 0; }
  28667. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28668. };
  28669. return Hinge2Joint;
  28670. })(MotorEnabledJoint);
  28671. BABYLON.Hinge2Joint = Hinge2Joint;
  28672. })(BABYLON || (BABYLON = {}));
  28673. var BABYLON;
  28674. (function (BABYLON) {
  28675. var PhysicsImpostor = (function () {
  28676. function PhysicsImpostor(object, type, _options, _scene) {
  28677. var _this = this;
  28678. if (_options === void 0) { _options = { mass: 0 }; }
  28679. this.object = object;
  28680. this.type = type;
  28681. this._options = _options;
  28682. this._scene = _scene;
  28683. this._bodyUpdateRequired = false;
  28684. this._onBeforePhysicsStepCallbacks = new Array();
  28685. this._onAfterPhysicsStepCallbacks = new Array();
  28686. this._onPhysicsCollideCallbacks = [];
  28687. this._deltaPosition = BABYLON.Vector3.Zero();
  28688. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28689. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28690. /**
  28691. * this function is executed by the physics engine.
  28692. */
  28693. this.beforeStep = function () {
  28694. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28695. //conjugate deltaRotation
  28696. if (_this._deltaRotationConjugated) {
  28697. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28698. }
  28699. else {
  28700. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28701. }
  28702. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28703. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28704. func(_this);
  28705. });
  28706. };
  28707. /**
  28708. * this function is executed by the physics engine.
  28709. */
  28710. this.afterStep = function () {
  28711. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28712. func(_this);
  28713. });
  28714. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28715. _this.object.position.addInPlace(_this._deltaPosition);
  28716. if (_this._deltaRotation) {
  28717. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28718. }
  28719. };
  28720. //event and body object due to cannon's event-based architecture.
  28721. this.onCollide = function (e) {
  28722. if (!_this._onPhysicsCollideCallbacks.length)
  28723. return;
  28724. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28725. if (otherImpostor) {
  28726. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28727. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28728. }).forEach(function (obj) {
  28729. obj.callback(_this, otherImpostor);
  28730. });
  28731. }
  28732. };
  28733. //sanity check!
  28734. if (!this.object) {
  28735. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28736. return;
  28737. }
  28738. //legacy support for old syntax.
  28739. if (!this._scene && object.getScene) {
  28740. this._scene = object.getScene();
  28741. }
  28742. this._physicsEngine = this._scene.getPhysicsEngine();
  28743. if (!this._physicsEngine) {
  28744. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28745. }
  28746. else {
  28747. //set the object's quaternion, if not set
  28748. if (!this.object.rotationQuaternion) {
  28749. if (this.object.rotation) {
  28750. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28751. }
  28752. else {
  28753. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28754. }
  28755. }
  28756. //default options params
  28757. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28758. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28759. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28760. this._joints = [];
  28761. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28762. if (!this.object.parent) {
  28763. this._init();
  28764. }
  28765. }
  28766. }
  28767. /**
  28768. * This function will completly initialize this impostor.
  28769. * It will create a new body - but only if this mesh has no parent.
  28770. * If it has, this impostor will not be used other than to define the impostor
  28771. * of the child mesh.
  28772. */
  28773. PhysicsImpostor.prototype._init = function () {
  28774. this._physicsEngine.removeImpostor(this);
  28775. this.physicsBody = null;
  28776. this._parent = this._parent || this._getPhysicsParent();
  28777. if (!this.parent) {
  28778. this._physicsEngine.addImpostor(this);
  28779. }
  28780. };
  28781. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28782. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28783. var parentMesh = this.object.parent;
  28784. return parentMesh.physicsImpostor;
  28785. }
  28786. return;
  28787. };
  28788. /**
  28789. * Should a new body be generated.
  28790. */
  28791. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28792. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28793. };
  28794. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28795. this.forceUpdate();
  28796. };
  28797. /**
  28798. * Force a regeneration of this or the parent's impostor's body.
  28799. * Use under cautious - This will remove all joints already implemented.
  28800. */
  28801. PhysicsImpostor.prototype.forceUpdate = function () {
  28802. this._init();
  28803. if (this.parent) {
  28804. this.parent.forceUpdate();
  28805. }
  28806. };
  28807. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28808. /*public get mesh(): AbstractMesh {
  28809. return this._mesh;
  28810. }*/
  28811. /**
  28812. * Gets the body that holds this impostor. Either its own, or its parent.
  28813. */
  28814. get: function () {
  28815. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28816. },
  28817. /**
  28818. * Set the physics body. Used mainly by the physics engine/plugin
  28819. */
  28820. set: function (physicsBody) {
  28821. if (this._physicsBody) {
  28822. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28823. }
  28824. this._physicsBody = physicsBody;
  28825. this.resetUpdateFlags();
  28826. },
  28827. enumerable: true,
  28828. configurable: true
  28829. });
  28830. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28831. get: function () {
  28832. return this._parent;
  28833. },
  28834. enumerable: true,
  28835. configurable: true
  28836. });
  28837. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28838. this._bodyUpdateRequired = false;
  28839. };
  28840. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28841. if (this.object.getBoundingInfo) {
  28842. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28843. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28844. }
  28845. else {
  28846. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28847. }
  28848. };
  28849. PhysicsImpostor.prototype.getObjectCenter = function () {
  28850. if (this.object.getBoundingInfo) {
  28851. return this.object.getBoundingInfo().boundingBox.center;
  28852. }
  28853. else {
  28854. return this.object.position;
  28855. }
  28856. };
  28857. /**
  28858. * Get a specific parametes from the options parameter.
  28859. */
  28860. PhysicsImpostor.prototype.getParam = function (paramName) {
  28861. return this._options[paramName];
  28862. };
  28863. /**
  28864. * Sets a specific parameter in the options given to the physics plugin
  28865. */
  28866. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28867. this._options[paramName] = value;
  28868. this._bodyUpdateRequired = true;
  28869. };
  28870. /**
  28871. * Specifically change the body's mass option. Won't recreate the physics body object
  28872. */
  28873. PhysicsImpostor.prototype.setMass = function (mass) {
  28874. if (this.getParam("mass") !== mass) {
  28875. this.setParam("mass", mass);
  28876. }
  28877. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28878. };
  28879. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28880. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28881. };
  28882. /**
  28883. * Set the body's linear velocity.
  28884. */
  28885. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28886. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28887. };
  28888. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28889. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28890. };
  28891. /**
  28892. * Set the body's linear velocity.
  28893. */
  28894. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28895. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28896. };
  28897. /**
  28898. * Execute a function with the physics plugin native code.
  28899. * Provide a function the will have two variables - the world object and the physics body object.
  28900. */
  28901. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28902. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28903. };
  28904. /**
  28905. * Register a function that will be executed before the physics world is stepping forward.
  28906. */
  28907. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28908. this._onBeforePhysicsStepCallbacks.push(func);
  28909. };
  28910. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28911. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28912. if (index > -1) {
  28913. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28914. }
  28915. else {
  28916. BABYLON.Tools.Warn("Function to remove was not found");
  28917. }
  28918. };
  28919. /**
  28920. * Register a function that will be executed after the physics step
  28921. */
  28922. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28923. this._onAfterPhysicsStepCallbacks.push(func);
  28924. };
  28925. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28926. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28927. if (index > -1) {
  28928. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28929. }
  28930. else {
  28931. BABYLON.Tools.Warn("Function to remove was not found");
  28932. }
  28933. };
  28934. /**
  28935. * register a function that will be executed when this impostor collides against a different body.
  28936. */
  28937. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28938. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28939. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28940. };
  28941. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28942. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28943. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28944. if (index > -1) {
  28945. this._onPhysicsCollideCallbacks.splice(index, 1);
  28946. }
  28947. else {
  28948. BABYLON.Tools.Warn("Function to remove was not found");
  28949. }
  28950. };
  28951. /**
  28952. * Apply a force
  28953. */
  28954. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28955. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28956. };
  28957. /**
  28958. * Apply an impulse
  28959. */
  28960. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28961. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28962. };
  28963. /**
  28964. * A help function to create a joint.
  28965. */
  28966. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28967. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28968. this.addJoint(otherImpostor, joint);
  28969. };
  28970. /**
  28971. * Add a joint to this impostor with a different impostor.
  28972. */
  28973. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28974. this._joints.push({
  28975. otherImpostor: otherImpostor,
  28976. joint: joint
  28977. });
  28978. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28979. };
  28980. /**
  28981. * Will keep this body still, in a sleep mode.
  28982. */
  28983. PhysicsImpostor.prototype.sleep = function () {
  28984. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28985. };
  28986. /**
  28987. * Wake the body up.
  28988. */
  28989. PhysicsImpostor.prototype.wakeUp = function () {
  28990. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28991. };
  28992. PhysicsImpostor.prototype.clone = function (newObject) {
  28993. if (!newObject)
  28994. return null;
  28995. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28996. };
  28997. PhysicsImpostor.prototype.dispose = function () {
  28998. var _this = this;
  28999. //no dispose if no physics engine is available.
  29000. if (!this._physicsEngine) {
  29001. return;
  29002. }
  29003. this._joints.forEach(function (j) {
  29004. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29005. });
  29006. //dispose the physics body
  29007. this._physicsEngine.removeImpostor(this);
  29008. if (this.parent) {
  29009. this.parent.forceUpdate();
  29010. }
  29011. else {
  29012. }
  29013. };
  29014. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29015. this._deltaPosition.copyFrom(position);
  29016. };
  29017. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29018. if (!this._deltaRotation) {
  29019. this._deltaRotation = new BABYLON.Quaternion();
  29020. }
  29021. this._deltaRotation.copyFrom(rotation);
  29022. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29023. };
  29024. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29025. //Impostor types
  29026. PhysicsImpostor.NoImpostor = 0;
  29027. PhysicsImpostor.SphereImpostor = 1;
  29028. PhysicsImpostor.BoxImpostor = 2;
  29029. PhysicsImpostor.PlaneImpostor = 3;
  29030. PhysicsImpostor.MeshImpostor = 4;
  29031. PhysicsImpostor.CylinderImpostor = 7;
  29032. PhysicsImpostor.ParticleImpostor = 8;
  29033. PhysicsImpostor.HeightmapImpostor = 9;
  29034. return PhysicsImpostor;
  29035. })();
  29036. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29037. })(BABYLON || (BABYLON = {}));
  29038. var BABYLON;
  29039. (function (BABYLON) {
  29040. var PhysicsEngine = (function () {
  29041. function PhysicsEngine(gravity, _physicsPlugin) {
  29042. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29043. this._physicsPlugin = _physicsPlugin;
  29044. //new methods and parameters
  29045. this._impostors = [];
  29046. this._joints = [];
  29047. if (!this._physicsPlugin.isSupported()) {
  29048. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29049. + "Please make sure it is included.");
  29050. }
  29051. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29052. this.setGravity(gravity);
  29053. this.setTimeStep();
  29054. }
  29055. PhysicsEngine.prototype.setGravity = function (gravity) {
  29056. this.gravity = gravity;
  29057. this._physicsPlugin.setGravity(this.gravity);
  29058. };
  29059. /**
  29060. * Set the time step of the physics engine.
  29061. * default is 1/60.
  29062. * To slow it down, enter 1/600 for example.
  29063. * To speed it up, 1/30
  29064. * @param {number} newTimeStep the new timestep to apply to this world.
  29065. */
  29066. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29067. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29068. this._physicsPlugin.setTimeStep(newTimeStep);
  29069. };
  29070. PhysicsEngine.prototype.dispose = function () {
  29071. this._impostors.forEach(function (impostor) {
  29072. impostor.dispose();
  29073. });
  29074. this._physicsPlugin.dispose();
  29075. };
  29076. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29077. return this._physicsPlugin.name;
  29078. };
  29079. /**
  29080. * Adding a new impostor for the impostor tracking.
  29081. * This will be done by the impostor itself.
  29082. * @param {PhysicsImpostor} impostor the impostor to add
  29083. */
  29084. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29085. impostor.uniqueId = this._impostors.push(impostor);
  29086. //if no parent, generate the body
  29087. if (!impostor.parent) {
  29088. this._physicsPlugin.generatePhysicsBody(impostor);
  29089. }
  29090. };
  29091. /**
  29092. * Remove an impostor from the engine.
  29093. * This impostor and its mesh will not longer be updated by the physics engine.
  29094. * @param {PhysicsImpostor} impostor the impostor to remove
  29095. */
  29096. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29097. var index = this._impostors.indexOf(impostor);
  29098. if (index > -1) {
  29099. var removed = this._impostors.splice(index, 1);
  29100. //Is it needed?
  29101. if (removed.length) {
  29102. //this will also remove it from the world.
  29103. removed[0].physicsBody = null;
  29104. }
  29105. }
  29106. };
  29107. /**
  29108. * Add a joint to the physics engine
  29109. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29110. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29111. * @param {PhysicsJoint} the joint that will connect both impostors.
  29112. */
  29113. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29114. var impostorJoint = {
  29115. mainImpostor: mainImpostor,
  29116. connectedImpostor: connectedImpostor,
  29117. joint: joint
  29118. };
  29119. joint.physicsPlugin = this._physicsPlugin;
  29120. this._joints.push(impostorJoint);
  29121. this._physicsPlugin.generateJoint(impostorJoint);
  29122. };
  29123. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29124. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29125. return (impostorJoint.connectedImpostor === connectedImpostor
  29126. && impostorJoint.joint === joint
  29127. && impostorJoint.mainImpostor === mainImpostor);
  29128. });
  29129. if (matchingJoints.length) {
  29130. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29131. }
  29132. };
  29133. /**
  29134. * Called by the scene. no need to call it.
  29135. */
  29136. PhysicsEngine.prototype._step = function (delta) {
  29137. var _this = this;
  29138. //check if any mesh has no body / requires an update
  29139. this._impostors.forEach(function (impostor) {
  29140. if (impostor.isBodyInitRequired()) {
  29141. _this._physicsPlugin.generatePhysicsBody(impostor);
  29142. }
  29143. });
  29144. if (delta > 0.1) {
  29145. delta = 0.1;
  29146. }
  29147. else if (delta <= 0) {
  29148. delta = 1.0 / 60.0;
  29149. }
  29150. this._physicsPlugin.executeStep(delta, this._impostors);
  29151. };
  29152. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29153. return this._physicsPlugin;
  29154. };
  29155. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29156. for (var i = 0; i < this._impostors.length; ++i) {
  29157. if (this._impostors[i].object === object) {
  29158. return this._impostors[i];
  29159. }
  29160. }
  29161. };
  29162. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29163. for (var i = 0; i < this._impostors.length; ++i) {
  29164. if (this._impostors[i].physicsBody === body) {
  29165. return this._impostors[i];
  29166. }
  29167. }
  29168. };
  29169. // Statics, Legacy support.
  29170. /**
  29171. * @Deprecated
  29172. *
  29173. */
  29174. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29175. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29176. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29177. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29178. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29179. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29180. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29181. PhysicsEngine.CapsuleImpostor = -1;
  29182. PhysicsEngine.ConeImpostor = -1;
  29183. PhysicsEngine.ConvexHullImpostor = -1;
  29184. PhysicsEngine.Epsilon = 0.001;
  29185. return PhysicsEngine;
  29186. })();
  29187. BABYLON.PhysicsEngine = PhysicsEngine;
  29188. })(BABYLON || (BABYLON = {}));
  29189. var BABYLON;
  29190. (function (BABYLON) {
  29191. var VertexData = (function () {
  29192. function VertexData() {
  29193. }
  29194. VertexData.prototype.set = function (data, kind) {
  29195. switch (kind) {
  29196. case BABYLON.VertexBuffer.PositionKind:
  29197. this.positions = data;
  29198. break;
  29199. case BABYLON.VertexBuffer.NormalKind:
  29200. this.normals = data;
  29201. break;
  29202. case BABYLON.VertexBuffer.UVKind:
  29203. this.uvs = data;
  29204. break;
  29205. case BABYLON.VertexBuffer.UV2Kind:
  29206. this.uvs2 = data;
  29207. break;
  29208. case BABYLON.VertexBuffer.UV3Kind:
  29209. this.uvs3 = data;
  29210. break;
  29211. case BABYLON.VertexBuffer.UV4Kind:
  29212. this.uvs4 = data;
  29213. break;
  29214. case BABYLON.VertexBuffer.UV5Kind:
  29215. this.uvs5 = data;
  29216. break;
  29217. case BABYLON.VertexBuffer.UV6Kind:
  29218. this.uvs6 = data;
  29219. break;
  29220. case BABYLON.VertexBuffer.ColorKind:
  29221. this.colors = data;
  29222. break;
  29223. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29224. this.matricesIndices = data;
  29225. break;
  29226. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29227. this.matricesWeights = data;
  29228. break;
  29229. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29230. this.matricesIndicesExtra = data;
  29231. break;
  29232. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29233. this.matricesWeightsExtra = data;
  29234. break;
  29235. }
  29236. };
  29237. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29238. this._applyTo(mesh, updatable);
  29239. };
  29240. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29241. this._applyTo(geometry, updatable);
  29242. };
  29243. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29244. this._update(mesh);
  29245. };
  29246. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29247. this._update(geometry);
  29248. };
  29249. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29250. if (this.positions) {
  29251. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29252. }
  29253. if (this.normals) {
  29254. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29255. }
  29256. if (this.uvs) {
  29257. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29258. }
  29259. if (this.uvs2) {
  29260. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29261. }
  29262. if (this.uvs3) {
  29263. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29264. }
  29265. if (this.uvs4) {
  29266. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29267. }
  29268. if (this.uvs5) {
  29269. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29270. }
  29271. if (this.uvs6) {
  29272. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29273. }
  29274. if (this.colors) {
  29275. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29276. }
  29277. if (this.matricesIndices) {
  29278. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29279. }
  29280. if (this.matricesWeights) {
  29281. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29282. }
  29283. if (this.matricesIndicesExtra) {
  29284. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29285. }
  29286. if (this.matricesWeightsExtra) {
  29287. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29288. }
  29289. if (this.indices) {
  29290. meshOrGeometry.setIndices(this.indices);
  29291. }
  29292. };
  29293. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29294. if (this.positions) {
  29295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29296. }
  29297. if (this.normals) {
  29298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29299. }
  29300. if (this.uvs) {
  29301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29302. }
  29303. if (this.uvs2) {
  29304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29305. }
  29306. if (this.uvs3) {
  29307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29308. }
  29309. if (this.uvs4) {
  29310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29311. }
  29312. if (this.uvs5) {
  29313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29314. }
  29315. if (this.uvs6) {
  29316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29317. }
  29318. if (this.colors) {
  29319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29320. }
  29321. if (this.matricesIndices) {
  29322. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29323. }
  29324. if (this.matricesWeights) {
  29325. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29326. }
  29327. if (this.matricesIndicesExtra) {
  29328. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29329. }
  29330. if (this.matricesWeightsExtra) {
  29331. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29332. }
  29333. if (this.indices) {
  29334. meshOrGeometry.setIndices(this.indices);
  29335. }
  29336. };
  29337. VertexData.prototype.transform = function (matrix) {
  29338. var transformed = BABYLON.Vector3.Zero();
  29339. var index;
  29340. if (this.positions) {
  29341. var position = BABYLON.Vector3.Zero();
  29342. for (index = 0; index < this.positions.length; index += 3) {
  29343. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29344. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29345. this.positions[index] = transformed.x;
  29346. this.positions[index + 1] = transformed.y;
  29347. this.positions[index + 2] = transformed.z;
  29348. }
  29349. }
  29350. if (this.normals) {
  29351. var normal = BABYLON.Vector3.Zero();
  29352. for (index = 0; index < this.normals.length; index += 3) {
  29353. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29354. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29355. this.normals[index] = transformed.x;
  29356. this.normals[index + 1] = transformed.y;
  29357. this.normals[index + 2] = transformed.z;
  29358. }
  29359. }
  29360. };
  29361. VertexData.prototype.merge = function (other) {
  29362. if (other.indices) {
  29363. if (!this.indices) {
  29364. this.indices = [];
  29365. }
  29366. var offset = this.positions ? this.positions.length / 3 : 0;
  29367. for (var index = 0; index < other.indices.length; index++) {
  29368. //TODO check type - if Int32Array!
  29369. this.indices.push(other.indices[index] + offset);
  29370. }
  29371. }
  29372. this.positions = this._mergeElement(this.positions, other.positions);
  29373. this.normals = this._mergeElement(this.normals, other.normals);
  29374. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29375. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29376. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29377. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29378. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29379. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29380. this.colors = this._mergeElement(this.colors, other.colors);
  29381. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29382. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29383. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29384. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29385. };
  29386. VertexData.prototype._mergeElement = function (source, other) {
  29387. if (!other)
  29388. return source;
  29389. if (!source)
  29390. return other;
  29391. var len = other.length + source.length;
  29392. var isSrcTypedArray = source instanceof Float32Array;
  29393. var isOthTypedArray = other instanceof Float32Array;
  29394. // use non-loop method when the source is Float32Array
  29395. if (isSrcTypedArray) {
  29396. var ret32 = new Float32Array(len);
  29397. ret32.set(source);
  29398. ret32.set(other, source.length);
  29399. return ret32;
  29400. }
  29401. else if (!isOthTypedArray) {
  29402. return source.concat(other);
  29403. }
  29404. else {
  29405. var ret = source.slice(0); // copy source to a separate array
  29406. for (var i = 0, len = other.length; i < len; i++) {
  29407. ret.push(other[i]);
  29408. }
  29409. return ret;
  29410. }
  29411. };
  29412. VertexData.prototype.serialize = function () {
  29413. var serializationObject = this.serialize();
  29414. if (this.positions) {
  29415. serializationObject.positions = this.positions;
  29416. }
  29417. if (this.normals) {
  29418. serializationObject.normals = this.normals;
  29419. }
  29420. if (this.uvs) {
  29421. serializationObject.uvs = this.uvs;
  29422. }
  29423. if (this.uvs2) {
  29424. serializationObject.uvs2 = this.uvs2;
  29425. }
  29426. if (this.uvs3) {
  29427. serializationObject.uvs3 = this.uvs3;
  29428. }
  29429. if (this.uvs4) {
  29430. serializationObject.uvs4 = this.uvs4;
  29431. }
  29432. if (this.uvs5) {
  29433. serializationObject.uvs5 = this.uvs5;
  29434. }
  29435. if (this.uvs6) {
  29436. serializationObject.uvs6 = this.uvs6;
  29437. }
  29438. if (this.colors) {
  29439. serializationObject.colors = this.colors;
  29440. }
  29441. if (this.matricesIndices) {
  29442. serializationObject.matricesIndices = this.matricesIndices;
  29443. serializationObject.matricesIndices._isExpanded = true;
  29444. }
  29445. if (this.matricesWeights) {
  29446. serializationObject.matricesWeights = this.matricesWeights;
  29447. }
  29448. if (this.matricesIndicesExtra) {
  29449. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29450. serializationObject.matricesIndicesExtra._isExpanded = true;
  29451. }
  29452. if (this.matricesWeightsExtra) {
  29453. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29454. }
  29455. serializationObject.indices = this.indices;
  29456. return serializationObject;
  29457. };
  29458. // Statics
  29459. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29460. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29461. };
  29462. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29463. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29464. };
  29465. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29466. var result = new VertexData();
  29467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29468. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29469. }
  29470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29471. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29472. }
  29473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29474. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29475. }
  29476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29477. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29478. }
  29479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29480. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29481. }
  29482. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29483. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29484. }
  29485. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29486. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29487. }
  29488. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29489. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29490. }
  29491. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29492. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29493. }
  29494. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29495. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29496. }
  29497. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29498. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29499. }
  29500. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29501. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29502. }
  29503. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29504. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29505. }
  29506. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29507. return result;
  29508. };
  29509. VertexData.CreateRibbon = function (options) {
  29510. var pathArray = options.pathArray;
  29511. var closeArray = options.closeArray || false;
  29512. var closePath = options.closePath || false;
  29513. var invertUV = options.invertUV || false;
  29514. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29515. var offset = options.offset || defaultOffset;
  29516. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29518. var positions = [];
  29519. var indices = [];
  29520. var normals = [];
  29521. var uvs = [];
  29522. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29523. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29524. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29525. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29526. var minlg; // minimal length among all paths from pathArray
  29527. var lg = []; // array of path lengths : nb of vertex per path
  29528. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29529. var p; // path iterator
  29530. var i; // point iterator
  29531. var j; // point iterator
  29532. // if single path in pathArray
  29533. if (pathArray.length < 2) {
  29534. var ar1 = [];
  29535. var ar2 = [];
  29536. for (i = 0; i < pathArray[0].length - offset; i++) {
  29537. ar1.push(pathArray[0][i]);
  29538. ar2.push(pathArray[0][i + offset]);
  29539. }
  29540. pathArray = [ar1, ar2];
  29541. }
  29542. // positions and horizontal distances (u)
  29543. var idc = 0;
  29544. var closePathCorr = (closePath) ? 1 : 0;
  29545. var path;
  29546. var l;
  29547. minlg = pathArray[0].length;
  29548. var vectlg;
  29549. var dist;
  29550. for (p = 0; p < pathArray.length; p++) {
  29551. uTotalDistance[p] = 0;
  29552. us[p] = [0];
  29553. path = pathArray[p];
  29554. l = path.length;
  29555. minlg = (minlg < l) ? minlg : l;
  29556. j = 0;
  29557. while (j < l) {
  29558. positions.push(path[j].x, path[j].y, path[j].z);
  29559. if (j > 0) {
  29560. vectlg = path[j].subtract(path[j - 1]).length();
  29561. dist = vectlg + uTotalDistance[p];
  29562. us[p].push(dist);
  29563. uTotalDistance[p] = dist;
  29564. }
  29565. j++;
  29566. }
  29567. if (closePath) {
  29568. j--;
  29569. positions.push(path[0].x, path[0].y, path[0].z);
  29570. vectlg = path[j].subtract(path[0]).length();
  29571. dist = vectlg + uTotalDistance[p];
  29572. us[p].push(dist);
  29573. uTotalDistance[p] = dist;
  29574. }
  29575. lg[p] = l + closePathCorr;
  29576. idx[p] = idc;
  29577. idc += (l + closePathCorr);
  29578. }
  29579. // vertical distances (v)
  29580. var path1;
  29581. var path2;
  29582. var vertex1;
  29583. var vertex2;
  29584. for (i = 0; i < minlg + closePathCorr; i++) {
  29585. vTotalDistance[i] = 0;
  29586. vs[i] = [0];
  29587. for (p = 0; p < pathArray.length - 1; p++) {
  29588. path1 = pathArray[p];
  29589. path2 = pathArray[p + 1];
  29590. if (i === minlg) {
  29591. vertex1 = path1[0];
  29592. vertex2 = path2[0];
  29593. }
  29594. else {
  29595. vertex1 = path1[i];
  29596. vertex2 = path2[i];
  29597. }
  29598. vectlg = vertex2.subtract(vertex1).length();
  29599. dist = vectlg + vTotalDistance[i];
  29600. vs[i].push(dist);
  29601. vTotalDistance[i] = dist;
  29602. }
  29603. if (closeArray) {
  29604. path1 = pathArray[p];
  29605. path2 = pathArray[0];
  29606. if (i === minlg) {
  29607. vertex2 = path2[0];
  29608. }
  29609. vectlg = vertex2.subtract(vertex1).length();
  29610. dist = vectlg + vTotalDistance[i];
  29611. vTotalDistance[i] = dist;
  29612. }
  29613. }
  29614. // uvs
  29615. var u;
  29616. var v;
  29617. for (p = 0; p < pathArray.length; p++) {
  29618. for (i = 0; i < minlg + closePathCorr; i++) {
  29619. u = us[p][i] / uTotalDistance[p];
  29620. v = vs[i][p] / vTotalDistance[i];
  29621. if (invertUV) {
  29622. uvs.push(v, u);
  29623. }
  29624. else {
  29625. uvs.push(u, v);
  29626. }
  29627. }
  29628. }
  29629. // indices
  29630. p = 0; // path index
  29631. var pi = 0; // positions array index
  29632. var l1 = lg[p] - 1; // path1 length
  29633. var l2 = lg[p + 1] - 1; // path2 length
  29634. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29635. var shft = idx[1] - idx[0]; // shift
  29636. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29637. while (pi <= min && p < path1nb) {
  29638. // 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
  29639. indices.push(pi, pi + shft, pi + 1);
  29640. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29641. pi += 1;
  29642. if (pi === min) {
  29643. p++;
  29644. if (p === lg.length - 1) {
  29645. shft = idx[0] - idx[p];
  29646. l1 = lg[p] - 1;
  29647. l2 = lg[0] - 1;
  29648. }
  29649. else {
  29650. shft = idx[p + 1] - idx[p];
  29651. l1 = lg[p] - 1;
  29652. l2 = lg[p + 1] - 1;
  29653. }
  29654. pi = idx[p];
  29655. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29656. }
  29657. }
  29658. // normals
  29659. VertexData.ComputeNormals(positions, indices, normals);
  29660. if (closePath) {
  29661. var indexFirst = 0;
  29662. var indexLast = 0;
  29663. for (p = 0; p < pathArray.length; p++) {
  29664. indexFirst = idx[p] * 3;
  29665. if (p + 1 < pathArray.length) {
  29666. indexLast = (idx[p + 1] - 1) * 3;
  29667. }
  29668. else {
  29669. indexLast = normals.length - 3;
  29670. }
  29671. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29672. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29673. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29674. normals[indexLast] = normals[indexFirst];
  29675. normals[indexLast + 1] = normals[indexFirst + 1];
  29676. normals[indexLast + 2] = normals[indexFirst + 2];
  29677. }
  29678. }
  29679. // sides
  29680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29681. // Result
  29682. var vertexData = new VertexData();
  29683. vertexData.indices = indices;
  29684. vertexData.positions = positions;
  29685. vertexData.normals = normals;
  29686. vertexData.uvs = uvs;
  29687. if (closePath) {
  29688. vertexData._idx = idx;
  29689. }
  29690. return vertexData;
  29691. };
  29692. VertexData.CreateBox = function (options) {
  29693. var normalsSource = [
  29694. new BABYLON.Vector3(0, 0, 1),
  29695. new BABYLON.Vector3(0, 0, -1),
  29696. new BABYLON.Vector3(1, 0, 0),
  29697. new BABYLON.Vector3(-1, 0, 0),
  29698. new BABYLON.Vector3(0, 1, 0),
  29699. new BABYLON.Vector3(0, -1, 0)
  29700. ];
  29701. var indices = [];
  29702. var positions = [];
  29703. var normals = [];
  29704. var uvs = [];
  29705. var width = options.width || options.size || 1;
  29706. var height = options.height || options.size || 1;
  29707. var depth = options.depth || options.size || 1;
  29708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29709. var faceUV = options.faceUV || new Array(6);
  29710. var faceColors = options.faceColors;
  29711. var colors = [];
  29712. // default face colors and UV if undefined
  29713. for (var f = 0; f < 6; f++) {
  29714. if (faceUV[f] === undefined) {
  29715. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29716. }
  29717. if (faceColors && faceColors[f] === undefined) {
  29718. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29719. }
  29720. }
  29721. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29722. // Create each face in turn.
  29723. for (var index = 0; index < normalsSource.length; index++) {
  29724. var normal = normalsSource[index];
  29725. // Get two vectors perpendicular to the face normal and to each other.
  29726. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29727. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29728. // Six indices (two triangles) per face.
  29729. var verticesLength = positions.length / 3;
  29730. indices.push(verticesLength);
  29731. indices.push(verticesLength + 1);
  29732. indices.push(verticesLength + 2);
  29733. indices.push(verticesLength);
  29734. indices.push(verticesLength + 2);
  29735. indices.push(verticesLength + 3);
  29736. // Four vertices per face.
  29737. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29738. positions.push(vertex.x, vertex.y, vertex.z);
  29739. normals.push(normal.x, normal.y, normal.z);
  29740. uvs.push(faceUV[index].z, faceUV[index].w);
  29741. if (faceColors) {
  29742. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29743. }
  29744. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29745. positions.push(vertex.x, vertex.y, vertex.z);
  29746. normals.push(normal.x, normal.y, normal.z);
  29747. uvs.push(faceUV[index].x, faceUV[index].w);
  29748. if (faceColors) {
  29749. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29750. }
  29751. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29752. positions.push(vertex.x, vertex.y, vertex.z);
  29753. normals.push(normal.x, normal.y, normal.z);
  29754. uvs.push(faceUV[index].x, faceUV[index].y);
  29755. if (faceColors) {
  29756. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29757. }
  29758. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29759. positions.push(vertex.x, vertex.y, vertex.z);
  29760. normals.push(normal.x, normal.y, normal.z);
  29761. uvs.push(faceUV[index].z, faceUV[index].y);
  29762. if (faceColors) {
  29763. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29764. }
  29765. }
  29766. // sides
  29767. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29768. // Result
  29769. var vertexData = new VertexData();
  29770. vertexData.indices = indices;
  29771. vertexData.positions = positions;
  29772. vertexData.normals = normals;
  29773. vertexData.uvs = uvs;
  29774. if (faceColors) {
  29775. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29776. vertexData.colors = totalColors;
  29777. }
  29778. return vertexData;
  29779. };
  29780. VertexData.CreateSphere = function (options) {
  29781. var segments = options.segments || 32;
  29782. var diameterX = options.diameterX || options.diameter || 1;
  29783. var diameterY = options.diameterY || options.diameter || 1;
  29784. var diameterZ = options.diameterZ || options.diameter || 1;
  29785. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29786. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29787. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29788. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29789. var totalZRotationSteps = 2 + segments;
  29790. var totalYRotationSteps = 2 * totalZRotationSteps;
  29791. var indices = [];
  29792. var positions = [];
  29793. var normals = [];
  29794. var uvs = [];
  29795. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29796. var normalizedZ = zRotationStep / totalZRotationSteps;
  29797. var angleZ = normalizedZ * Math.PI * slice;
  29798. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29799. var normalizedY = yRotationStep / totalYRotationSteps;
  29800. var angleY = normalizedY * Math.PI * 2 * arc;
  29801. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29802. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29803. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29804. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29805. var vertex = complete.multiply(radius);
  29806. var normal = complete.divide(radius).normalize();
  29807. positions.push(vertex.x, vertex.y, vertex.z);
  29808. normals.push(normal.x, normal.y, normal.z);
  29809. uvs.push(normalizedY, normalizedZ);
  29810. }
  29811. if (zRotationStep > 0) {
  29812. var verticesCount = positions.length / 3;
  29813. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29814. indices.push((firstIndex));
  29815. indices.push((firstIndex + 1));
  29816. indices.push(firstIndex + totalYRotationSteps + 1);
  29817. indices.push((firstIndex + totalYRotationSteps + 1));
  29818. indices.push((firstIndex + 1));
  29819. indices.push((firstIndex + totalYRotationSteps + 2));
  29820. }
  29821. }
  29822. }
  29823. // Sides
  29824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29825. // Result
  29826. var vertexData = new VertexData();
  29827. vertexData.indices = indices;
  29828. vertexData.positions = positions;
  29829. vertexData.normals = normals;
  29830. vertexData.uvs = uvs;
  29831. return vertexData;
  29832. };
  29833. // Cylinder and cone
  29834. VertexData.CreateCylinder = function (options) {
  29835. var height = options.height || 2;
  29836. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29837. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29838. var tessellation = options.tessellation || 24;
  29839. var subdivisions = options.subdivisions || 1;
  29840. var hasRings = options.hasRings;
  29841. var enclose = options.enclose;
  29842. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29843. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29844. var faceUV = options.faceUV || new Array(3);
  29845. var faceColors = options.faceColors;
  29846. // default face colors and UV if undefined
  29847. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29848. var ringNb = (hasRings) ? subdivisions : 1;
  29849. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29850. var f;
  29851. for (f = 0; f < surfaceNb; f++) {
  29852. if (faceColors && faceColors[f] === undefined) {
  29853. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29854. }
  29855. }
  29856. for (f = 0; f < surfaceNb; f++) {
  29857. if (faceUV && faceUV[f] === undefined) {
  29858. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29859. }
  29860. }
  29861. var indices = [];
  29862. var positions = [];
  29863. var normals = [];
  29864. var uvs = [];
  29865. var colors = [];
  29866. var angle_step = Math.PI * 2 * arc / tessellation;
  29867. var angle;
  29868. var h;
  29869. var radius;
  29870. var tan = (diameterBottom - diameterTop) / 2 / height;
  29871. var ringVertex = BABYLON.Vector3.Zero();
  29872. var ringNormal = BABYLON.Vector3.Zero();
  29873. var ringFirstVertex = BABYLON.Vector3.Zero();
  29874. var ringFirstNormal = BABYLON.Vector3.Zero();
  29875. var quadNormal = BABYLON.Vector3.Zero();
  29876. var Y = BABYLON.Axis.Y;
  29877. // positions, normals, uvs
  29878. var i;
  29879. var j;
  29880. var r;
  29881. var ringIdx = 1;
  29882. var s = 1; // surface index
  29883. var cs = 0;
  29884. var v = 0;
  29885. for (i = 0; i <= subdivisions; i++) {
  29886. h = i / subdivisions;
  29887. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29888. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29889. for (r = 0; r < ringIdx; r++) {
  29890. if (hasRings) {
  29891. s += r;
  29892. }
  29893. if (enclose) {
  29894. s += 2 * r;
  29895. }
  29896. for (j = 0; j <= tessellation; j++) {
  29897. angle = j * angle_step;
  29898. // position
  29899. ringVertex.x = Math.cos(-angle) * radius;
  29900. ringVertex.y = -height / 2 + h * height;
  29901. ringVertex.z = Math.sin(-angle) * radius;
  29902. // normal
  29903. if (diameterTop === 0 && i === subdivisions) {
  29904. // if no top cap, reuse former normals
  29905. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29906. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29907. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29908. }
  29909. else {
  29910. ringNormal.x = ringVertex.x;
  29911. ringNormal.z = ringVertex.z;
  29912. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29913. ringNormal.normalize();
  29914. }
  29915. // keep first ring vertex values for enclose
  29916. if (j === 0) {
  29917. ringFirstVertex.copyFrom(ringVertex);
  29918. ringFirstNormal.copyFrom(ringNormal);
  29919. }
  29920. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29921. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29922. if (hasRings) {
  29923. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29924. }
  29925. else {
  29926. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29927. }
  29928. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29929. if (faceColors) {
  29930. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29931. }
  29932. }
  29933. // if enclose, add four vertices and their dedicated normals
  29934. if (arc !== 1 && enclose) {
  29935. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29936. positions.push(0, ringVertex.y, 0);
  29937. positions.push(0, ringVertex.y, 0);
  29938. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29939. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29940. quadNormal.normalize();
  29941. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29942. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29943. quadNormal.normalize();
  29944. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29945. if (hasRings) {
  29946. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29947. }
  29948. else {
  29949. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29950. }
  29951. uvs.push(faceUV[s + 1].x, v);
  29952. uvs.push(faceUV[s + 1].z, v);
  29953. if (hasRings) {
  29954. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29955. }
  29956. else {
  29957. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29958. }
  29959. uvs.push(faceUV[s + 2].x, v);
  29960. uvs.push(faceUV[s + 2].z, v);
  29961. if (faceColors) {
  29962. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29963. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29964. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29965. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29966. }
  29967. }
  29968. if (cs !== s) {
  29969. cs = s;
  29970. }
  29971. }
  29972. }
  29973. // indices
  29974. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29975. var s;
  29976. i = 0;
  29977. for (s = 0; s < subdivisions; s++) {
  29978. for (j = 0; j < tessellation; j++) {
  29979. var i0 = i * (e + 1) + j;
  29980. var i1 = (i + 1) * (e + 1) + j;
  29981. var i2 = i * (e + 1) + (j + 1);
  29982. var i3 = (i + 1) * (e + 1) + (j + 1);
  29983. indices.push(i0, i1, i2);
  29984. indices.push(i3, i2, i1);
  29985. }
  29986. if (arc !== 1 && enclose) {
  29987. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29988. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29989. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29990. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29991. }
  29992. i = (hasRings) ? (i + 2) : (i + 1);
  29993. }
  29994. // Caps
  29995. var createCylinderCap = function (isTop) {
  29996. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29997. if (radius === 0) {
  29998. return;
  29999. }
  30000. // Cap positions, normals & uvs
  30001. var angle;
  30002. var circleVector;
  30003. var i;
  30004. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30005. var c;
  30006. if (faceColors) {
  30007. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30008. }
  30009. // cap center
  30010. var vbase = positions.length / 3;
  30011. var offset = isTop ? height / 2 : -height / 2;
  30012. var center = new BABYLON.Vector3(0, offset, 0);
  30013. positions.push(center.x, center.y, center.z);
  30014. normals.push(0, isTop ? 1 : -1, 0);
  30015. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30016. if (faceColors) {
  30017. colors.push(c.r, c.g, c.b, c.a);
  30018. }
  30019. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30020. for (i = 0; i <= tessellation; i++) {
  30021. angle = Math.PI * 2 * i * arc / tessellation;
  30022. var cos = Math.cos(-angle);
  30023. var sin = Math.sin(-angle);
  30024. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30025. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30026. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30027. normals.push(0, isTop ? 1 : -1, 0);
  30028. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30029. if (faceColors) {
  30030. colors.push(c.r, c.g, c.b, c.a);
  30031. }
  30032. }
  30033. // Cap indices
  30034. for (i = 0; i < tessellation; i++) {
  30035. if (!isTop) {
  30036. indices.push(vbase);
  30037. indices.push(vbase + (i + 1));
  30038. indices.push(vbase + (i + 2));
  30039. }
  30040. else {
  30041. indices.push(vbase);
  30042. indices.push(vbase + (i + 2));
  30043. indices.push(vbase + (i + 1));
  30044. }
  30045. }
  30046. };
  30047. // add caps to geometry
  30048. createCylinderCap(false);
  30049. createCylinderCap(true);
  30050. // Sides
  30051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30052. var vertexData = new VertexData();
  30053. vertexData.indices = indices;
  30054. vertexData.positions = positions;
  30055. vertexData.normals = normals;
  30056. vertexData.uvs = uvs;
  30057. if (faceColors) {
  30058. vertexData.colors = colors;
  30059. }
  30060. return vertexData;
  30061. };
  30062. VertexData.CreateTorus = function (options) {
  30063. var indices = [];
  30064. var positions = [];
  30065. var normals = [];
  30066. var uvs = [];
  30067. var diameter = options.diameter || 1;
  30068. var thickness = options.thickness || 0.5;
  30069. var tessellation = options.tessellation || 16;
  30070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30071. var stride = tessellation + 1;
  30072. for (var i = 0; i <= tessellation; i++) {
  30073. var u = i / tessellation;
  30074. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30075. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30076. for (var j = 0; j <= tessellation; j++) {
  30077. var v = 1 - j / tessellation;
  30078. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30079. var dx = Math.cos(innerAngle);
  30080. var dy = Math.sin(innerAngle);
  30081. // Create a vertex.
  30082. var normal = new BABYLON.Vector3(dx, dy, 0);
  30083. var position = normal.scale(thickness / 2);
  30084. var textureCoordinate = new BABYLON.Vector2(u, v);
  30085. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30086. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30087. positions.push(position.x, position.y, position.z);
  30088. normals.push(normal.x, normal.y, normal.z);
  30089. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30090. // And create indices for two triangles.
  30091. var nextI = (i + 1) % stride;
  30092. var nextJ = (j + 1) % stride;
  30093. indices.push(i * stride + j);
  30094. indices.push(i * stride + nextJ);
  30095. indices.push(nextI * stride + j);
  30096. indices.push(i * stride + nextJ);
  30097. indices.push(nextI * stride + nextJ);
  30098. indices.push(nextI * stride + j);
  30099. }
  30100. }
  30101. // Sides
  30102. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30103. // Result
  30104. var vertexData = new VertexData();
  30105. vertexData.indices = indices;
  30106. vertexData.positions = positions;
  30107. vertexData.normals = normals;
  30108. vertexData.uvs = uvs;
  30109. return vertexData;
  30110. };
  30111. VertexData.CreateLineSystem = function (options) {
  30112. var indices = [];
  30113. var positions = [];
  30114. var lines = options.lines;
  30115. var idx = 0;
  30116. for (var l = 0; l < lines.length; l++) {
  30117. var points = lines[l];
  30118. for (var index = 0; index < points.length; index++) {
  30119. positions.push(points[index].x, points[index].y, points[index].z);
  30120. if (index > 0) {
  30121. indices.push(idx - 1);
  30122. indices.push(idx);
  30123. }
  30124. idx++;
  30125. }
  30126. }
  30127. var vertexData = new VertexData();
  30128. vertexData.indices = indices;
  30129. vertexData.positions = positions;
  30130. return vertexData;
  30131. };
  30132. VertexData.CreateDashedLines = function (options) {
  30133. var dashSize = options.dashSize || 3;
  30134. var gapSize = options.gapSize || 1;
  30135. var dashNb = options.dashNb || 200;
  30136. var points = options.points;
  30137. var positions = new Array();
  30138. var indices = new Array();
  30139. var curvect = BABYLON.Vector3.Zero();
  30140. var lg = 0;
  30141. var nb = 0;
  30142. var shft = 0;
  30143. var dashshft = 0;
  30144. var curshft = 0;
  30145. var idx = 0;
  30146. var i = 0;
  30147. for (i = 0; i < points.length - 1; i++) {
  30148. points[i + 1].subtractToRef(points[i], curvect);
  30149. lg += curvect.length();
  30150. }
  30151. shft = lg / dashNb;
  30152. dashshft = dashSize * shft / (dashSize + gapSize);
  30153. for (i = 0; i < points.length - 1; i++) {
  30154. points[i + 1].subtractToRef(points[i], curvect);
  30155. nb = Math.floor(curvect.length() / shft);
  30156. curvect.normalize();
  30157. for (var j = 0; j < nb; j++) {
  30158. curshft = shft * j;
  30159. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30160. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30161. indices.push(idx, idx + 1);
  30162. idx += 2;
  30163. }
  30164. }
  30165. // Result
  30166. var vertexData = new VertexData();
  30167. vertexData.positions = positions;
  30168. vertexData.indices = indices;
  30169. return vertexData;
  30170. };
  30171. VertexData.CreateGround = function (options) {
  30172. var indices = [];
  30173. var positions = [];
  30174. var normals = [];
  30175. var uvs = [];
  30176. var row, col;
  30177. var width = options.width || 1;
  30178. var height = options.height || 1;
  30179. var subdivisions = options.subdivisions || 1;
  30180. for (row = 0; row <= subdivisions; row++) {
  30181. for (col = 0; col <= subdivisions; col++) {
  30182. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30183. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30184. positions.push(position.x, position.y, position.z);
  30185. normals.push(normal.x, normal.y, normal.z);
  30186. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30187. }
  30188. }
  30189. for (row = 0; row < subdivisions; row++) {
  30190. for (col = 0; col < subdivisions; col++) {
  30191. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30192. indices.push(col + 1 + row * (subdivisions + 1));
  30193. indices.push(col + row * (subdivisions + 1));
  30194. indices.push(col + (row + 1) * (subdivisions + 1));
  30195. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30196. indices.push(col + row * (subdivisions + 1));
  30197. }
  30198. }
  30199. // Result
  30200. var vertexData = new VertexData();
  30201. vertexData.indices = indices;
  30202. vertexData.positions = positions;
  30203. vertexData.normals = normals;
  30204. vertexData.uvs = uvs;
  30205. return vertexData;
  30206. };
  30207. VertexData.CreateTiledGround = function (options) {
  30208. var xmin = options.xmin || -1.0;
  30209. var zmin = options.zmin || -1.0;
  30210. var xmax = options.xmax || 1.0;
  30211. var zmax = options.zmax || 1.0;
  30212. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30213. var precision = options.precision || { w: 1, h: 1 };
  30214. var indices = [];
  30215. var positions = [];
  30216. var normals = [];
  30217. var uvs = [];
  30218. var row, col, tileRow, tileCol;
  30219. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30220. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30221. precision.w = (precision.w < 1) ? 1 : precision.w;
  30222. precision.h = (precision.h < 1) ? 1 : precision.h;
  30223. var tileSize = {
  30224. 'w': (xmax - xmin) / subdivisions.w,
  30225. 'h': (zmax - zmin) / subdivisions.h
  30226. };
  30227. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30228. // Indices
  30229. var base = positions.length / 3;
  30230. var rowLength = precision.w + 1;
  30231. for (row = 0; row < precision.h; row++) {
  30232. for (col = 0; col < precision.w; col++) {
  30233. var square = [
  30234. base + col + row * rowLength,
  30235. base + (col + 1) + row * rowLength,
  30236. base + (col + 1) + (row + 1) * rowLength,
  30237. base + col + (row + 1) * rowLength
  30238. ];
  30239. indices.push(square[1]);
  30240. indices.push(square[2]);
  30241. indices.push(square[3]);
  30242. indices.push(square[0]);
  30243. indices.push(square[1]);
  30244. indices.push(square[3]);
  30245. }
  30246. }
  30247. // Position, normals and uvs
  30248. var position = BABYLON.Vector3.Zero();
  30249. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30250. for (row = 0; row <= precision.h; row++) {
  30251. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30252. for (col = 0; col <= precision.w; col++) {
  30253. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30254. position.y = 0;
  30255. positions.push(position.x, position.y, position.z);
  30256. normals.push(normal.x, normal.y, normal.z);
  30257. uvs.push(col / precision.w, row / precision.h);
  30258. }
  30259. }
  30260. }
  30261. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30262. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30263. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30264. }
  30265. }
  30266. // Result
  30267. var vertexData = new VertexData();
  30268. vertexData.indices = indices;
  30269. vertexData.positions = positions;
  30270. vertexData.normals = normals;
  30271. vertexData.uvs = uvs;
  30272. return vertexData;
  30273. };
  30274. VertexData.CreateGroundFromHeightMap = function (options) {
  30275. var indices = [];
  30276. var positions = [];
  30277. var normals = [];
  30278. var uvs = [];
  30279. var row, col;
  30280. // Vertices
  30281. for (row = 0; row <= options.subdivisions; row++) {
  30282. for (col = 0; col <= options.subdivisions; col++) {
  30283. 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));
  30284. // Compute height
  30285. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30286. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30287. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30288. var r = options.buffer[pos] / 255.0;
  30289. var g = options.buffer[pos + 1] / 255.0;
  30290. var b = options.buffer[pos + 2] / 255.0;
  30291. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30292. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30293. // Add vertex
  30294. positions.push(position.x, position.y, position.z);
  30295. normals.push(0, 0, 0);
  30296. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30297. }
  30298. }
  30299. // Indices
  30300. for (row = 0; row < options.subdivisions; row++) {
  30301. for (col = 0; col < options.subdivisions; col++) {
  30302. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30303. indices.push(col + 1 + row * (options.subdivisions + 1));
  30304. indices.push(col + row * (options.subdivisions + 1));
  30305. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30306. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30307. indices.push(col + row * (options.subdivisions + 1));
  30308. }
  30309. }
  30310. // Normals
  30311. VertexData.ComputeNormals(positions, indices, normals);
  30312. // Result
  30313. var vertexData = new VertexData();
  30314. vertexData.indices = indices;
  30315. vertexData.positions = positions;
  30316. vertexData.normals = normals;
  30317. vertexData.uvs = uvs;
  30318. return vertexData;
  30319. };
  30320. VertexData.CreatePlane = function (options) {
  30321. var indices = [];
  30322. var positions = [];
  30323. var normals = [];
  30324. var uvs = [];
  30325. var width = options.width || options.size || 1;
  30326. var height = options.height || options.size || 1;
  30327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30328. // Vertices
  30329. var halfWidth = width / 2.0;
  30330. var halfHeight = height / 2.0;
  30331. positions.push(-halfWidth, -halfHeight, 0);
  30332. normals.push(0, 0, -1.0);
  30333. uvs.push(0.0, 0.0);
  30334. positions.push(halfWidth, -halfHeight, 0);
  30335. normals.push(0, 0, -1.0);
  30336. uvs.push(1.0, 0.0);
  30337. positions.push(halfWidth, halfHeight, 0);
  30338. normals.push(0, 0, -1.0);
  30339. uvs.push(1.0, 1.0);
  30340. positions.push(-halfWidth, halfHeight, 0);
  30341. normals.push(0, 0, -1.0);
  30342. uvs.push(0.0, 1.0);
  30343. // Indices
  30344. indices.push(0);
  30345. indices.push(1);
  30346. indices.push(2);
  30347. indices.push(0);
  30348. indices.push(2);
  30349. indices.push(3);
  30350. // Sides
  30351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30352. // Result
  30353. var vertexData = new VertexData();
  30354. vertexData.indices = indices;
  30355. vertexData.positions = positions;
  30356. vertexData.normals = normals;
  30357. vertexData.uvs = uvs;
  30358. return vertexData;
  30359. };
  30360. VertexData.CreateDisc = function (options) {
  30361. var positions = [];
  30362. var indices = [];
  30363. var normals = [];
  30364. var uvs = [];
  30365. var radius = options.radius || 0.5;
  30366. var tessellation = options.tessellation || 64;
  30367. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30368. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30369. // positions and uvs
  30370. positions.push(0, 0, 0); // disc center first
  30371. uvs.push(0.5, 0.5);
  30372. var theta = Math.PI * 2 * arc;
  30373. var step = theta / tessellation;
  30374. for (var a = 0; a < theta; a += step) {
  30375. var x = Math.cos(a);
  30376. var y = Math.sin(a);
  30377. var u = (x + 1) / 2;
  30378. var v = (1 - y) / 2;
  30379. positions.push(radius * x, radius * y, 0);
  30380. uvs.push(u, v);
  30381. }
  30382. if (arc === 1) {
  30383. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30384. uvs.push(uvs[2], uvs[3]);
  30385. }
  30386. //indices
  30387. var vertexNb = positions.length / 3;
  30388. for (var i = 1; i < vertexNb - 1; i++) {
  30389. indices.push(i + 1, 0, i);
  30390. }
  30391. // result
  30392. VertexData.ComputeNormals(positions, indices, normals);
  30393. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30394. var vertexData = new VertexData();
  30395. vertexData.indices = indices;
  30396. vertexData.positions = positions;
  30397. vertexData.normals = normals;
  30398. vertexData.uvs = uvs;
  30399. return vertexData;
  30400. };
  30401. VertexData.CreateIcoSphere = function (options) {
  30402. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30403. var radius = options.radius || 1;
  30404. var flat = (options.flat === undefined) ? true : options.flat;
  30405. var subdivisions = options.subdivisions || 4;
  30406. var radiusX = options.radiusX || radius;
  30407. var radiusY = options.radiusY || radius;
  30408. var radiusZ = options.radiusZ || radius;
  30409. var t = (1 + Math.sqrt(5)) / 2;
  30410. // 12 vertex x,y,z
  30411. var ico_vertices = [
  30412. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30413. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30414. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30415. ];
  30416. // index of 3 vertex makes a face of icopshere
  30417. var ico_indices = [
  30418. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30419. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30420. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30421. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30422. ];
  30423. // vertex for uv have aliased position, not for UV
  30424. var vertices_unalias_id = [
  30425. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30426. // vertex alias
  30427. 0,
  30428. 2,
  30429. 3,
  30430. 3,
  30431. 3,
  30432. 4,
  30433. 7,
  30434. 8,
  30435. 9,
  30436. 9,
  30437. 10,
  30438. 11 // 23: B + 12
  30439. ];
  30440. // uv as integer step (not pixels !)
  30441. var ico_vertexuv = [
  30442. 5, 1, 3, 1, 6, 4, 0, 0,
  30443. 5, 3, 4, 2, 2, 2, 4, 0,
  30444. 2, 0, 1, 1, 6, 0, 6, 2,
  30445. // vertex alias (for same vertex on different faces)
  30446. 0, 4,
  30447. 3, 3,
  30448. 4, 4,
  30449. 3, 1,
  30450. 4, 2,
  30451. 4, 4,
  30452. 0, 2,
  30453. 1, 1,
  30454. 2, 2,
  30455. 3, 3,
  30456. 1, 3,
  30457. 2, 4 // 23: B + 12
  30458. ];
  30459. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30460. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30461. // First island of uv mapping
  30462. // v = 4h 3+ 2
  30463. // v = 3h 9+ 4
  30464. // v = 2h 9+ 5 B
  30465. // v = 1h 9 1 0
  30466. // v = 0h 3 8 7 A
  30467. // u = 0 1 2 3 4 5 6 *a
  30468. // Second island of uv mapping
  30469. // v = 4h 0+ B+ 4+
  30470. // v = 3h A+ 2+
  30471. // v = 2h 7+ 6 3+
  30472. // v = 1h 8+ 3+
  30473. // v = 0h
  30474. // u = 0 1 2 3 4 5 6 *a
  30475. // Face layout on texture UV mapping
  30476. // ============
  30477. // \ 4 /\ 16 / ======
  30478. // \ / \ / /\ 11 /
  30479. // \/ 7 \/ / \ /
  30480. // ======= / 10 \/
  30481. // /\ 17 /\ =======
  30482. // / \ / \ \ 15 /\
  30483. // / 8 \/ 12 \ \ / \
  30484. // ============ \/ 6 \
  30485. // \ 18 /\ ============
  30486. // \ / \ \ 5 /\ 0 /
  30487. // \/ 13 \ \ / \ /
  30488. // ======= \/ 1 \/
  30489. // =============
  30490. // /\ 19 /\ 2 /\
  30491. // / \ / \ / \
  30492. // / 14 \/ 9 \/ 3 \
  30493. // ===================
  30494. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30495. var ustep = 138 / 1024;
  30496. var vstep = 239 / 1024;
  30497. var uoffset = 60 / 1024;
  30498. var voffset = 26 / 1024;
  30499. // Second island should have margin, not to touch the first island
  30500. // avoid any borderline artefact in pixel rounding
  30501. var island_u_offset = -40 / 1024;
  30502. var island_v_offset = +20 / 1024;
  30503. // face is either island 0 or 1 :
  30504. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30505. var island = [
  30506. 0, 0, 0, 0, 1,
  30507. 0, 0, 1, 1, 0,
  30508. 0, 0, 1, 1, 0,
  30509. 0, 1, 1, 1, 0 // 15 - 19
  30510. ];
  30511. var indices = [];
  30512. var positions = [];
  30513. var normals = [];
  30514. var uvs = [];
  30515. var current_indice = 0;
  30516. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30517. var face_vertex_pos = new Array(3);
  30518. var face_vertex_uv = new Array(3);
  30519. var v012;
  30520. for (v012 = 0; v012 < 3; v012++) {
  30521. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30522. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30523. }
  30524. // create all with normals
  30525. for (var face = 0; face < 20; face++) {
  30526. // 3 vertex per face
  30527. for (v012 = 0; v012 < 3; v012++) {
  30528. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30529. var v_id = ico_indices[3 * face + v012];
  30530. // vertex have 3D position (x,y,z)
  30531. 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]);
  30532. // Normalize to get normal, then scale to radius
  30533. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30534. // uv Coordinates from vertex ID
  30535. 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);
  30536. }
  30537. // Subdivide the face (interpolate pos, norm, uv)
  30538. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30539. // - norm is linear interpolation of vertex corner normal
  30540. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30541. // - uv is linear interpolation
  30542. //
  30543. // Topology is as below for sub-divide by 2
  30544. // vertex shown as v0,v1,v2
  30545. // interp index is i1 to progress in range [v0,v1[
  30546. // interp index is i2 to progress in range [v0,v2[
  30547. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30548. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30549. //
  30550. //
  30551. // i2 v2
  30552. // ^ ^
  30553. // / / \
  30554. // / / \
  30555. // / / \
  30556. // / / (0,1) \
  30557. // / #---------\
  30558. // / / \ (0,0)'/ \
  30559. // / / \ / \
  30560. // / / \ / \
  30561. // / / (0,0) \ / (1,0) \
  30562. // / #---------#---------\
  30563. // v0 v1
  30564. //
  30565. // --------------------> i1
  30566. //
  30567. // interp of (i1,i2):
  30568. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30569. // along i1 : lerp(x0,x1, i1/(S-i2))
  30570. //
  30571. // centroid of triangle is needed to get help normal computation
  30572. // (c1,c2) are used for centroid location
  30573. var interp_vertex = function (i1, i2, c1, c2) {
  30574. // vertex is interpolated from
  30575. // - face_vertex_pos[0..2]
  30576. // - face_vertex_uv[0..2]
  30577. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30578. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30579. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30580. pos_interp.normalize();
  30581. var vertex_normal;
  30582. if (flat) {
  30583. // in flat mode, recalculate normal as face centroid normal
  30584. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30585. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30586. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30587. }
  30588. else {
  30589. // in smooth mode, recalculate normal from each single vertex position
  30590. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30591. }
  30592. // Vertex normal need correction due to X,Y,Z radius scaling
  30593. vertex_normal.x /= radiusX;
  30594. vertex_normal.y /= radiusY;
  30595. vertex_normal.z /= radiusZ;
  30596. vertex_normal.normalize();
  30597. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30598. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30599. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30600. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30601. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30602. uvs.push(uv_interp.x, uv_interp.y);
  30603. // push each vertex has member of a face
  30604. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30605. indices.push(current_indice);
  30606. current_indice++;
  30607. };
  30608. for (var i2 = 0; i2 < subdivisions; i2++) {
  30609. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30610. // face : (i1,i2) for /\ :
  30611. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30612. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30613. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30614. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30615. if (i1 + i2 + 1 < subdivisions) {
  30616. // face : (i1,i2)' for \/ :
  30617. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30618. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30619. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30620. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30621. }
  30622. }
  30623. }
  30624. }
  30625. // Sides
  30626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30627. // Result
  30628. var vertexData = new VertexData();
  30629. vertexData.indices = indices;
  30630. vertexData.positions = positions;
  30631. vertexData.normals = normals;
  30632. vertexData.uvs = uvs;
  30633. return vertexData;
  30634. };
  30635. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30636. VertexData.CreatePolyhedron = function (options) {
  30637. // provided polyhedron types :
  30638. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30639. // 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)
  30640. var polyhedra = [];
  30641. 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]] };
  30642. 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]] };
  30643. polyhedra[2] = {
  30644. 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]],
  30645. 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]]
  30646. };
  30647. polyhedra[3] = {
  30648. 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]],
  30649. 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]]
  30650. };
  30651. polyhedra[4] = {
  30652. 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]],
  30653. 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]]
  30654. };
  30655. 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]] };
  30656. 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]] };
  30657. 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]] };
  30658. 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]] };
  30659. 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]] };
  30660. 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]] };
  30661. 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]] };
  30662. 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]] };
  30663. 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]] };
  30664. polyhedra[14] = {
  30665. 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]],
  30666. 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]]
  30667. };
  30668. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30669. var size = options.size;
  30670. var sizeX = options.sizeX || size || 1;
  30671. var sizeY = options.sizeY || size || 1;
  30672. var sizeZ = options.sizeZ || size || 1;
  30673. var data = options.custom || polyhedra[type];
  30674. var nbfaces = data.face.length;
  30675. var faceUV = options.faceUV || new Array(nbfaces);
  30676. var faceColors = options.faceColors;
  30677. var flat = (options.flat === undefined) ? true : options.flat;
  30678. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30679. var positions = [];
  30680. var indices = [];
  30681. var normals = [];
  30682. var uvs = [];
  30683. var colors = [];
  30684. var index = 0;
  30685. var faceIdx = 0; // face cursor in the array "indexes"
  30686. var indexes = [];
  30687. var i = 0;
  30688. var f = 0;
  30689. var u, v, ang, x, y, tmp;
  30690. // default face colors and UV if undefined
  30691. if (flat) {
  30692. for (f = 0; f < nbfaces; f++) {
  30693. if (faceColors && faceColors[f] === undefined) {
  30694. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30695. }
  30696. if (faceUV && faceUV[f] === undefined) {
  30697. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30698. }
  30699. }
  30700. }
  30701. if (!flat) {
  30702. for (i = 0; i < data.vertex.length; i++) {
  30703. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30704. uvs.push(0, 0);
  30705. }
  30706. for (f = 0; f < nbfaces; f++) {
  30707. for (i = 0; i < data.face[f].length - 2; i++) {
  30708. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30709. }
  30710. }
  30711. }
  30712. else {
  30713. for (f = 0; f < nbfaces; f++) {
  30714. var fl = data.face[f].length; // number of vertices of the current face
  30715. ang = 2 * Math.PI / fl;
  30716. x = 0.5 * Math.tan(ang / 2);
  30717. y = 0.5;
  30718. // positions, uvs, colors
  30719. for (i = 0; i < fl; i++) {
  30720. // positions
  30721. 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);
  30722. indexes.push(index);
  30723. index++;
  30724. // uvs
  30725. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30726. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30727. uvs.push(u, v);
  30728. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30729. y = x * Math.sin(ang) + y * Math.cos(ang);
  30730. x = tmp;
  30731. // colors
  30732. if (faceColors) {
  30733. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30734. }
  30735. }
  30736. // indices from indexes
  30737. for (i = 0; i < fl - 2; i++) {
  30738. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30739. }
  30740. faceIdx += fl;
  30741. }
  30742. }
  30743. VertexData.ComputeNormals(positions, indices, normals);
  30744. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30745. var vertexData = new VertexData();
  30746. vertexData.positions = positions;
  30747. vertexData.indices = indices;
  30748. vertexData.normals = normals;
  30749. vertexData.uvs = uvs;
  30750. if (faceColors && flat) {
  30751. vertexData.colors = colors;
  30752. }
  30753. return vertexData;
  30754. };
  30755. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30756. VertexData.CreateTorusKnot = function (options) {
  30757. var indices = [];
  30758. var positions = [];
  30759. var normals = [];
  30760. var uvs = [];
  30761. var radius = options.radius || 2;
  30762. var tube = options.tube || 0.5;
  30763. var radialSegments = options.radialSegments || 32;
  30764. var tubularSegments = options.tubularSegments || 32;
  30765. var p = options.p || 2;
  30766. var q = options.q || 3;
  30767. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30768. // Helper
  30769. var getPos = function (angle) {
  30770. var cu = Math.cos(angle);
  30771. var su = Math.sin(angle);
  30772. var quOverP = q / p * angle;
  30773. var cs = Math.cos(quOverP);
  30774. var tx = radius * (2 + cs) * 0.5 * cu;
  30775. var ty = radius * (2 + cs) * su * 0.5;
  30776. var tz = radius * Math.sin(quOverP) * 0.5;
  30777. return new BABYLON.Vector3(tx, ty, tz);
  30778. };
  30779. // Vertices
  30780. var i;
  30781. var j;
  30782. for (i = 0; i <= radialSegments; i++) {
  30783. var modI = i % radialSegments;
  30784. var u = modI / radialSegments * 2 * p * Math.PI;
  30785. var p1 = getPos(u);
  30786. var p2 = getPos(u + 0.01);
  30787. var tang = p2.subtract(p1);
  30788. var n = p2.add(p1);
  30789. var bitan = BABYLON.Vector3.Cross(tang, n);
  30790. n = BABYLON.Vector3.Cross(bitan, tang);
  30791. bitan.normalize();
  30792. n.normalize();
  30793. for (j = 0; j < tubularSegments; j++) {
  30794. var modJ = j % tubularSegments;
  30795. var v = modJ / tubularSegments * 2 * Math.PI;
  30796. var cx = -tube * Math.cos(v);
  30797. var cy = tube * Math.sin(v);
  30798. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30799. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30800. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30801. uvs.push(i / radialSegments);
  30802. uvs.push(j / tubularSegments);
  30803. }
  30804. }
  30805. for (i = 0; i < radialSegments; i++) {
  30806. for (j = 0; j < tubularSegments; j++) {
  30807. var jNext = (j + 1) % tubularSegments;
  30808. var a = i * tubularSegments + j;
  30809. var b = (i + 1) * tubularSegments + j;
  30810. var c = (i + 1) * tubularSegments + jNext;
  30811. var d = i * tubularSegments + jNext;
  30812. indices.push(d);
  30813. indices.push(b);
  30814. indices.push(a);
  30815. indices.push(d);
  30816. indices.push(c);
  30817. indices.push(b);
  30818. }
  30819. }
  30820. // Normals
  30821. VertexData.ComputeNormals(positions, indices, normals);
  30822. // Sides
  30823. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30824. // Result
  30825. var vertexData = new VertexData();
  30826. vertexData.indices = indices;
  30827. vertexData.positions = positions;
  30828. vertexData.normals = normals;
  30829. vertexData.uvs = uvs;
  30830. return vertexData;
  30831. };
  30832. // Tools
  30833. /**
  30834. * @param {any} - positions (number[] or Float32Array)
  30835. * @param {any} - indices (number[] or Uint16Array)
  30836. * @param {any} - normals (number[] or Float32Array)
  30837. */
  30838. VertexData.ComputeNormals = function (positions, indices, normals) {
  30839. var index = 0;
  30840. var p1p2x = 0.0;
  30841. var p1p2y = 0.0;
  30842. var p1p2z = 0.0;
  30843. var p3p2x = 0.0;
  30844. var p3p2y = 0.0;
  30845. var p3p2z = 0.0;
  30846. var faceNormalx = 0.0;
  30847. var faceNormaly = 0.0;
  30848. var faceNormalz = 0.0;
  30849. var length = 0.0;
  30850. var i1 = 0;
  30851. var i2 = 0;
  30852. var i3 = 0;
  30853. for (index = 0; index < positions.length; index++) {
  30854. normals[index] = 0.0;
  30855. }
  30856. // indice triplet = 1 face
  30857. var nbFaces = indices.length / 3;
  30858. for (index = 0; index < nbFaces; index++) {
  30859. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30860. i2 = indices[index * 3 + 1];
  30861. i3 = indices[index * 3 + 2];
  30862. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30863. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30864. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30865. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30866. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30867. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30868. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30869. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30870. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30871. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30872. length = (length === 0) ? 1.0 : length;
  30873. faceNormalx /= length; // normalize this normal
  30874. faceNormaly /= length;
  30875. faceNormalz /= length;
  30876. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30877. normals[i1 * 3 + 1] += faceNormaly;
  30878. normals[i1 * 3 + 2] += faceNormalz;
  30879. normals[i2 * 3] += faceNormalx;
  30880. normals[i2 * 3 + 1] += faceNormaly;
  30881. normals[i2 * 3 + 2] += faceNormalz;
  30882. normals[i3 * 3] += faceNormalx;
  30883. normals[i3 * 3 + 1] += faceNormaly;
  30884. normals[i3 * 3 + 2] += faceNormalz;
  30885. }
  30886. // last normalization of each normal
  30887. for (index = 0; index < normals.length / 3; index++) {
  30888. faceNormalx = normals[index * 3];
  30889. faceNormaly = normals[index * 3 + 1];
  30890. faceNormalz = normals[index * 3 + 2];
  30891. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30892. length = (length === 0) ? 1.0 : length;
  30893. faceNormalx /= length;
  30894. faceNormaly /= length;
  30895. faceNormalz /= length;
  30896. normals[index * 3] = faceNormalx;
  30897. normals[index * 3 + 1] = faceNormaly;
  30898. normals[index * 3 + 2] = faceNormalz;
  30899. }
  30900. };
  30901. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30902. var li = indices.length;
  30903. var ln = normals.length;
  30904. var i;
  30905. var n;
  30906. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30907. switch (sideOrientation) {
  30908. case BABYLON.Mesh.FRONTSIDE:
  30909. // nothing changed
  30910. break;
  30911. case BABYLON.Mesh.BACKSIDE:
  30912. var tmp;
  30913. // indices
  30914. for (i = 0; i < li; i += 3) {
  30915. tmp = indices[i];
  30916. indices[i] = indices[i + 2];
  30917. indices[i + 2] = tmp;
  30918. }
  30919. // normals
  30920. for (n = 0; n < ln; n++) {
  30921. normals[n] = -normals[n];
  30922. }
  30923. break;
  30924. case BABYLON.Mesh.DOUBLESIDE:
  30925. // positions
  30926. var lp = positions.length;
  30927. var l = lp / 3;
  30928. for (var p = 0; p < lp; p++) {
  30929. positions[lp + p] = positions[p];
  30930. }
  30931. // indices
  30932. for (i = 0; i < li; i += 3) {
  30933. indices[i + li] = indices[i + 2] + l;
  30934. indices[i + 1 + li] = indices[i + 1] + l;
  30935. indices[i + 2 + li] = indices[i] + l;
  30936. }
  30937. // normals
  30938. for (n = 0; n < ln; n++) {
  30939. normals[ln + n] = -normals[n];
  30940. }
  30941. // uvs
  30942. var lu = uvs.length;
  30943. for (var u = 0; u < lu; u++) {
  30944. uvs[u + lu] = uvs[u];
  30945. }
  30946. break;
  30947. }
  30948. };
  30949. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30950. var vertexData = new VertexData();
  30951. // positions
  30952. var positions = parsedVertexData.positions;
  30953. if (positions) {
  30954. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30955. }
  30956. // normals
  30957. var normals = parsedVertexData.normals;
  30958. if (normals) {
  30959. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30960. }
  30961. // uvs
  30962. var uvs = parsedVertexData.uvs;
  30963. if (uvs) {
  30964. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30965. }
  30966. // uv2s
  30967. var uv2s = parsedVertexData.uv2s;
  30968. if (uv2s) {
  30969. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30970. }
  30971. // uv3s
  30972. var uv3s = parsedVertexData.uv3s;
  30973. if (uv3s) {
  30974. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30975. }
  30976. // uv4s
  30977. var uv4s = parsedVertexData.uv4s;
  30978. if (uv4s) {
  30979. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30980. }
  30981. // uv5s
  30982. var uv5s = parsedVertexData.uv5s;
  30983. if (uv5s) {
  30984. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30985. }
  30986. // uv6s
  30987. var uv6s = parsedVertexData.uv6s;
  30988. if (uv6s) {
  30989. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30990. }
  30991. // colors
  30992. var colors = parsedVertexData.colors;
  30993. if (colors) {
  30994. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30995. }
  30996. // matricesIndices
  30997. var matricesIndices = parsedVertexData.matricesIndices;
  30998. if (matricesIndices) {
  30999. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31000. }
  31001. // matricesWeights
  31002. var matricesWeights = parsedVertexData.matricesWeights;
  31003. if (matricesWeights) {
  31004. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31005. }
  31006. // indices
  31007. var indices = parsedVertexData.indices;
  31008. if (indices) {
  31009. vertexData.indices = indices;
  31010. }
  31011. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31012. };
  31013. return VertexData;
  31014. })();
  31015. BABYLON.VertexData = VertexData;
  31016. })(BABYLON || (BABYLON = {}));
  31017. var BABYLON;
  31018. (function (BABYLON) {
  31019. var Tags = (function () {
  31020. function Tags() {
  31021. }
  31022. Tags.EnableFor = function (obj) {
  31023. obj._tags = obj._tags || {};
  31024. obj.hasTags = function () {
  31025. return Tags.HasTags(obj);
  31026. };
  31027. obj.addTags = function (tagsString) {
  31028. return Tags.AddTagsTo(obj, tagsString);
  31029. };
  31030. obj.removeTags = function (tagsString) {
  31031. return Tags.RemoveTagsFrom(obj, tagsString);
  31032. };
  31033. obj.matchesTagsQuery = function (tagsQuery) {
  31034. return Tags.MatchesQuery(obj, tagsQuery);
  31035. };
  31036. };
  31037. Tags.DisableFor = function (obj) {
  31038. delete obj._tags;
  31039. delete obj.hasTags;
  31040. delete obj.addTags;
  31041. delete obj.removeTags;
  31042. delete obj.matchesTagsQuery;
  31043. };
  31044. Tags.HasTags = function (obj) {
  31045. if (!obj._tags) {
  31046. return false;
  31047. }
  31048. return !BABYLON.Tools.IsEmpty(obj._tags);
  31049. };
  31050. Tags.GetTags = function (obj, asString) {
  31051. if (asString === void 0) { asString = true; }
  31052. if (!obj._tags) {
  31053. return null;
  31054. }
  31055. if (asString) {
  31056. var tagsArray = [];
  31057. for (var tag in obj._tags) {
  31058. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31059. tagsArray.push(tag);
  31060. }
  31061. }
  31062. return tagsArray.join(" ");
  31063. }
  31064. else {
  31065. return obj._tags;
  31066. }
  31067. };
  31068. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31069. // a tag cannot start with '||', '&&', and '!'
  31070. // it cannot contain whitespaces
  31071. Tags.AddTagsTo = function (obj, tagsString) {
  31072. if (!tagsString) {
  31073. return;
  31074. }
  31075. if (typeof tagsString !== "string") {
  31076. return;
  31077. }
  31078. var tags = tagsString.split(" ");
  31079. for (var t in tags) {
  31080. Tags._AddTagTo(obj, tags[t]);
  31081. }
  31082. };
  31083. Tags._AddTagTo = function (obj, tag) {
  31084. tag = tag.trim();
  31085. if (tag === "" || tag === "true" || tag === "false") {
  31086. return;
  31087. }
  31088. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31089. return;
  31090. }
  31091. Tags.EnableFor(obj);
  31092. obj._tags[tag] = true;
  31093. };
  31094. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31095. if (!Tags.HasTags(obj)) {
  31096. return;
  31097. }
  31098. var tags = tagsString.split(" ");
  31099. for (var t in tags) {
  31100. Tags._RemoveTagFrom(obj, tags[t]);
  31101. }
  31102. };
  31103. Tags._RemoveTagFrom = function (obj, tag) {
  31104. delete obj._tags[tag];
  31105. };
  31106. Tags.MatchesQuery = function (obj, tagsQuery) {
  31107. if (tagsQuery === undefined) {
  31108. return true;
  31109. }
  31110. if (tagsQuery === "") {
  31111. return Tags.HasTags(obj);
  31112. }
  31113. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31114. };
  31115. return Tags;
  31116. })();
  31117. BABYLON.Tags = Tags;
  31118. })(BABYLON || (BABYLON = {}));
  31119. var BABYLON;
  31120. (function (BABYLON) {
  31121. var Internals;
  31122. (function (Internals) {
  31123. var AndOrNotEvaluator = (function () {
  31124. function AndOrNotEvaluator() {
  31125. }
  31126. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31127. if (!query.match(/\([^\(\)]*\)/g)) {
  31128. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31129. }
  31130. else {
  31131. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31132. // remove parenthesis
  31133. r = r.slice(1, r.length - 1);
  31134. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31135. });
  31136. }
  31137. if (query === "true") {
  31138. return true;
  31139. }
  31140. if (query === "false") {
  31141. return false;
  31142. }
  31143. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31144. };
  31145. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31146. evaluateCallback = evaluateCallback || (function (r) {
  31147. return r === "true" ? true : false;
  31148. });
  31149. var result;
  31150. var or = parenthesisContent.split("||");
  31151. for (var i in or) {
  31152. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31153. var and = ori.split("&&");
  31154. if (and.length > 1) {
  31155. for (var j = 0; j < and.length; ++j) {
  31156. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31157. if (andj !== "true" && andj !== "false") {
  31158. if (andj[0] === "!") {
  31159. result = !evaluateCallback(andj.substring(1));
  31160. }
  31161. else {
  31162. result = evaluateCallback(andj);
  31163. }
  31164. }
  31165. else {
  31166. result = andj === "true" ? true : false;
  31167. }
  31168. if (!result) {
  31169. ori = "false";
  31170. break;
  31171. }
  31172. }
  31173. }
  31174. if (result || ori === "true") {
  31175. result = true;
  31176. break;
  31177. }
  31178. // result equals false (or undefined)
  31179. if (ori !== "true" && ori !== "false") {
  31180. if (ori[0] === "!") {
  31181. result = !evaluateCallback(ori.substring(1));
  31182. }
  31183. else {
  31184. result = evaluateCallback(ori);
  31185. }
  31186. }
  31187. else {
  31188. result = ori === "true" ? true : false;
  31189. }
  31190. }
  31191. // the whole parenthesis scope is replaced by 'true' or 'false'
  31192. return result ? "true" : "false";
  31193. };
  31194. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31195. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31196. // remove whitespaces
  31197. r = r.replace(/[\s]/g, function () { return ""; });
  31198. return r.length % 2 ? "!" : "";
  31199. });
  31200. booleanString = booleanString.trim();
  31201. if (booleanString === "!true") {
  31202. booleanString = "false";
  31203. }
  31204. else if (booleanString === "!false") {
  31205. booleanString = "true";
  31206. }
  31207. return booleanString;
  31208. };
  31209. return AndOrNotEvaluator;
  31210. })();
  31211. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31213. })(BABYLON || (BABYLON = {}));
  31214. var BABYLON;
  31215. (function (BABYLON) {
  31216. var PostProcessRenderPass = (function () {
  31217. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31218. this._enabled = true;
  31219. this._refCount = 0;
  31220. this._name = name;
  31221. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31222. this.setRenderList(renderList);
  31223. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31224. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31225. this._scene = scene;
  31226. this._renderList = renderList;
  31227. }
  31228. // private
  31229. PostProcessRenderPass.prototype._incRefCount = function () {
  31230. if (this._refCount === 0) {
  31231. this._scene.customRenderTargets.push(this._renderTexture);
  31232. }
  31233. return ++this._refCount;
  31234. };
  31235. PostProcessRenderPass.prototype._decRefCount = function () {
  31236. this._refCount--;
  31237. if (this._refCount <= 0) {
  31238. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31239. }
  31240. return this._refCount;
  31241. };
  31242. PostProcessRenderPass.prototype._update = function () {
  31243. this.setRenderList(this._renderList);
  31244. };
  31245. // public
  31246. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31247. this._renderTexture.renderList = renderList;
  31248. };
  31249. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31250. return this._renderTexture;
  31251. };
  31252. return PostProcessRenderPass;
  31253. })();
  31254. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31255. })(BABYLON || (BABYLON = {}));
  31256. var BABYLON;
  31257. (function (BABYLON) {
  31258. var PostProcessRenderEffect = (function () {
  31259. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31260. this._engine = engine;
  31261. this._name = name;
  31262. this._singleInstance = singleInstance || true;
  31263. this._getPostProcess = getPostProcess;
  31264. this._cameras = [];
  31265. this._indicesForCamera = [];
  31266. this._postProcesses = {};
  31267. this._renderPasses = {};
  31268. this._renderEffectAsPasses = {};
  31269. }
  31270. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31271. get: function () {
  31272. for (var index in this._postProcesses) {
  31273. if (!this._postProcesses[index].isSupported) {
  31274. return false;
  31275. }
  31276. }
  31277. return true;
  31278. },
  31279. enumerable: true,
  31280. configurable: true
  31281. });
  31282. PostProcessRenderEffect.prototype._update = function () {
  31283. for (var renderPassName in this._renderPasses) {
  31284. this._renderPasses[renderPassName]._update();
  31285. }
  31286. };
  31287. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31288. this._renderPasses[renderPass._name] = renderPass;
  31289. this._linkParameters();
  31290. };
  31291. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31292. delete this._renderPasses[renderPass._name];
  31293. this._linkParameters();
  31294. };
  31295. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31296. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31297. this._linkParameters();
  31298. };
  31299. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31300. for (var renderPassName in this._renderPasses) {
  31301. if (renderPassName === passName) {
  31302. return this._renderPasses[passName];
  31303. }
  31304. }
  31305. };
  31306. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31307. this._renderPasses = {};
  31308. this._linkParameters();
  31309. };
  31310. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31311. var cameraKey;
  31312. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31313. for (var i = 0; i < _cam.length; i++) {
  31314. var camera = _cam[i];
  31315. var cameraName = camera.name;
  31316. if (this._singleInstance) {
  31317. cameraKey = 0;
  31318. }
  31319. else {
  31320. cameraKey = cameraName;
  31321. }
  31322. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31323. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31324. if (!this._indicesForCamera[cameraName]) {
  31325. this._indicesForCamera[cameraName] = [];
  31326. }
  31327. this._indicesForCamera[cameraName].push(index);
  31328. if (this._cameras.indexOf(camera) === -1) {
  31329. this._cameras[cameraName] = camera;
  31330. }
  31331. for (var passName in this._renderPasses) {
  31332. this._renderPasses[passName]._incRefCount();
  31333. }
  31334. }
  31335. this._linkParameters();
  31336. };
  31337. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31338. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31339. for (var i = 0; i < _cam.length; i++) {
  31340. var camera = _cam[i];
  31341. var cameraName = camera.name;
  31342. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31343. var index = this._cameras.indexOf(cameraName);
  31344. this._indicesForCamera.splice(index, 1);
  31345. this._cameras.splice(index, 1);
  31346. for (var passName in this._renderPasses) {
  31347. this._renderPasses[passName]._decRefCount();
  31348. }
  31349. }
  31350. };
  31351. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31352. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31353. for (var i = 0; i < _cam.length; i++) {
  31354. var camera = _cam[i];
  31355. var cameraName = camera.name;
  31356. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31357. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31358. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31359. }
  31360. }
  31361. for (var passName in this._renderPasses) {
  31362. this._renderPasses[passName]._incRefCount();
  31363. }
  31364. }
  31365. };
  31366. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31367. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31368. for (var i = 0; i < _cam.length; i++) {
  31369. var camera = _cam[i];
  31370. var cameraName = camera.Name;
  31371. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31372. for (var passName in this._renderPasses) {
  31373. this._renderPasses[passName]._decRefCount();
  31374. }
  31375. }
  31376. };
  31377. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31378. if (this._singleInstance) {
  31379. return this._postProcesses[0];
  31380. }
  31381. else {
  31382. return this._postProcesses[camera.name];
  31383. }
  31384. };
  31385. PostProcessRenderEffect.prototype._linkParameters = function () {
  31386. var _this = this;
  31387. for (var index in this._postProcesses) {
  31388. if (this.applyParameters) {
  31389. this.applyParameters(this._postProcesses[index]);
  31390. }
  31391. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31392. _this._linkTextures(effect);
  31393. });
  31394. }
  31395. };
  31396. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31397. for (var renderPassName in this._renderPasses) {
  31398. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31399. }
  31400. for (var renderEffectName in this._renderEffectAsPasses) {
  31401. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31402. }
  31403. };
  31404. return PostProcessRenderEffect;
  31405. })();
  31406. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31407. })(BABYLON || (BABYLON = {}));
  31408. var BABYLON;
  31409. (function (BABYLON) {
  31410. var PostProcessRenderPipeline = (function () {
  31411. function PostProcessRenderPipeline(engine, name) {
  31412. this._engine = engine;
  31413. this._name = name;
  31414. this._renderEffects = {};
  31415. this._renderEffectsForIsolatedPass = {};
  31416. this._cameras = [];
  31417. }
  31418. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31419. get: function () {
  31420. for (var renderEffectName in this._renderEffects) {
  31421. if (!this._renderEffects[renderEffectName].isSupported) {
  31422. return false;
  31423. }
  31424. }
  31425. return true;
  31426. },
  31427. enumerable: true,
  31428. configurable: true
  31429. });
  31430. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31431. this._renderEffects[renderEffect._name] = renderEffect;
  31432. };
  31433. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31434. var renderEffects = this._renderEffects[renderEffectName];
  31435. if (!renderEffects) {
  31436. return;
  31437. }
  31438. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31439. };
  31440. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31441. var renderEffects = this._renderEffects[renderEffectName];
  31442. if (!renderEffects) {
  31443. return;
  31444. }
  31445. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31446. };
  31447. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31448. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31449. var indicesToDelete = [];
  31450. var i;
  31451. for (i = 0; i < _cam.length; i++) {
  31452. var camera = _cam[i];
  31453. var cameraName = camera.name;
  31454. if (this._cameras.indexOf(camera) === -1) {
  31455. this._cameras[cameraName] = camera;
  31456. }
  31457. else if (unique) {
  31458. indicesToDelete.push(i);
  31459. }
  31460. }
  31461. for (i = 0; i < indicesToDelete.length; i++) {
  31462. cameras.splice(indicesToDelete[i], 1);
  31463. }
  31464. for (var renderEffectName in this._renderEffects) {
  31465. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31466. }
  31467. };
  31468. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31469. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31470. for (var renderEffectName in this._renderEffects) {
  31471. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31472. }
  31473. for (var i = 0; i < _cam.length; i++) {
  31474. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31475. }
  31476. };
  31477. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31478. var _this = this;
  31479. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31480. var pass = null;
  31481. var renderEffectName;
  31482. for (renderEffectName in this._renderEffects) {
  31483. pass = this._renderEffects[renderEffectName].getPass(passName);
  31484. if (pass != null) {
  31485. break;
  31486. }
  31487. }
  31488. if (pass === null) {
  31489. return;
  31490. }
  31491. for (renderEffectName in this._renderEffects) {
  31492. this._renderEffects[renderEffectName]._disable(_cam);
  31493. }
  31494. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31495. for (var i = 0; i < _cam.length; i++) {
  31496. var camera = _cam[i];
  31497. var cameraName = camera.name;
  31498. 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); });
  31499. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31500. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31501. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31502. }
  31503. };
  31504. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31505. var _this = this;
  31506. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31507. for (var i = 0; i < _cam.length; i++) {
  31508. var camera = _cam[i];
  31509. var cameraName = camera.name;
  31510. 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); });
  31511. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31512. }
  31513. for (var renderEffectName in this._renderEffects) {
  31514. this._renderEffects[renderEffectName]._enable(_cam);
  31515. }
  31516. };
  31517. PostProcessRenderPipeline.prototype._update = function () {
  31518. for (var renderEffectName in this._renderEffects) {
  31519. this._renderEffects[renderEffectName]._update();
  31520. }
  31521. for (var i = 0; i < this._cameras.length; i++) {
  31522. var cameraName = this._cameras[i].name;
  31523. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31524. this._renderEffectsForIsolatedPass[cameraName]._update();
  31525. }
  31526. }
  31527. };
  31528. PostProcessRenderPipeline.prototype.dispose = function () {
  31529. // Must be implemented by children
  31530. };
  31531. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31532. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31533. return PostProcessRenderPipeline;
  31534. })();
  31535. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31536. })(BABYLON || (BABYLON = {}));
  31537. var BABYLON;
  31538. (function (BABYLON) {
  31539. var PostProcessRenderPipelineManager = (function () {
  31540. function PostProcessRenderPipelineManager() {
  31541. this._renderPipelines = {};
  31542. }
  31543. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31544. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31545. };
  31546. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31547. var renderPipeline = this._renderPipelines[renderPipelineName];
  31548. if (!renderPipeline) {
  31549. return;
  31550. }
  31551. renderPipeline._attachCameras(cameras, unique);
  31552. };
  31553. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31554. var renderPipeline = this._renderPipelines[renderPipelineName];
  31555. if (!renderPipeline) {
  31556. return;
  31557. }
  31558. renderPipeline._detachCameras(cameras);
  31559. };
  31560. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31561. var renderPipeline = this._renderPipelines[renderPipelineName];
  31562. if (!renderPipeline) {
  31563. return;
  31564. }
  31565. renderPipeline._enableEffect(renderEffectName, cameras);
  31566. };
  31567. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31568. var renderPipeline = this._renderPipelines[renderPipelineName];
  31569. if (!renderPipeline) {
  31570. return;
  31571. }
  31572. renderPipeline._disableEffect(renderEffectName, cameras);
  31573. };
  31574. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31575. var renderPipeline = this._renderPipelines[renderPipelineName];
  31576. if (!renderPipeline) {
  31577. return;
  31578. }
  31579. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31580. };
  31581. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31582. var renderPipeline = this._renderPipelines[renderPipelineName];
  31583. if (!renderPipeline) {
  31584. return;
  31585. }
  31586. renderPipeline._disableDisplayOnlyPass(cameras);
  31587. };
  31588. PostProcessRenderPipelineManager.prototype.update = function () {
  31589. for (var renderPipelineName in this._renderPipelines) {
  31590. var pipeline = this._renderPipelines[renderPipelineName];
  31591. if (!pipeline.isSupported) {
  31592. pipeline.dispose();
  31593. delete this._renderPipelines[renderPipelineName];
  31594. }
  31595. else {
  31596. pipeline._update();
  31597. }
  31598. }
  31599. };
  31600. return PostProcessRenderPipelineManager;
  31601. })();
  31602. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31603. })(BABYLON || (BABYLON = {}));
  31604. var BABYLON;
  31605. (function (BABYLON) {
  31606. var BoundingBoxRenderer = (function () {
  31607. function BoundingBoxRenderer(scene) {
  31608. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31609. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31610. this.showBackLines = true;
  31611. this.renderList = new BABYLON.SmartArray(32);
  31612. this._vertexBuffers = {};
  31613. this._scene = scene;
  31614. }
  31615. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31616. if (this._colorShader) {
  31617. return;
  31618. }
  31619. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31620. attributes: [BABYLON.VertexBuffer.PositionKind],
  31621. uniforms: ["worldViewProjection", "color"]
  31622. });
  31623. var engine = this._scene.getEngine();
  31624. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31625. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31626. 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]);
  31627. };
  31628. BoundingBoxRenderer.prototype.reset = function () {
  31629. this.renderList.reset();
  31630. };
  31631. BoundingBoxRenderer.prototype.render = function () {
  31632. if (this.renderList.length === 0) {
  31633. return;
  31634. }
  31635. this._prepareRessources();
  31636. if (!this._colorShader.isReady()) {
  31637. return;
  31638. }
  31639. var engine = this._scene.getEngine();
  31640. engine.setDepthWrite(false);
  31641. this._colorShader._preBind();
  31642. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31643. var boundingBox = this.renderList.data[boundingBoxIndex];
  31644. var min = boundingBox.minimum;
  31645. var max = boundingBox.maximum;
  31646. var diff = max.subtract(min);
  31647. var median = min.add(diff.scale(0.5));
  31648. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31649. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31650. .multiply(boundingBox.getWorldMatrix());
  31651. // VBOs
  31652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31653. if (this.showBackLines) {
  31654. // Back
  31655. engine.setDepthFunctionToGreaterOrEqual();
  31656. this._scene.resetCachedMaterial();
  31657. this._colorShader.setColor4("color", this.backColor.toColor4());
  31658. this._colorShader.bind(worldMatrix);
  31659. // Draw order
  31660. engine.draw(false, 0, 24);
  31661. }
  31662. // Front
  31663. engine.setDepthFunctionToLess();
  31664. this._scene.resetCachedMaterial();
  31665. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31666. this._colorShader.bind(worldMatrix);
  31667. // Draw order
  31668. engine.draw(false, 0, 24);
  31669. }
  31670. this._colorShader.unbind();
  31671. engine.setDepthFunctionToLessOrEqual();
  31672. engine.setDepthWrite(true);
  31673. };
  31674. BoundingBoxRenderer.prototype.dispose = function () {
  31675. if (!this._colorShader) {
  31676. return;
  31677. }
  31678. this._colorShader.dispose();
  31679. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31680. if (buffer) {
  31681. buffer.dispose();
  31682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31683. }
  31684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31685. };
  31686. return BoundingBoxRenderer;
  31687. })();
  31688. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31689. })(BABYLON || (BABYLON = {}));
  31690. var BABYLON;
  31691. (function (BABYLON) {
  31692. var Condition = (function () {
  31693. function Condition(actionManager) {
  31694. this._actionManager = actionManager;
  31695. }
  31696. Condition.prototype.isValid = function () {
  31697. return true;
  31698. };
  31699. Condition.prototype._getProperty = function (propertyPath) {
  31700. return this._actionManager._getProperty(propertyPath);
  31701. };
  31702. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31703. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31704. };
  31705. Condition.prototype.serialize = function () {
  31706. };
  31707. Condition.prototype._serialize = function (serializedCondition) {
  31708. return {
  31709. type: 2,
  31710. children: [],
  31711. name: serializedCondition.name,
  31712. properties: serializedCondition.properties
  31713. };
  31714. };
  31715. return Condition;
  31716. })();
  31717. BABYLON.Condition = Condition;
  31718. var ValueCondition = (function (_super) {
  31719. __extends(ValueCondition, _super);
  31720. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31721. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31722. _super.call(this, actionManager);
  31723. this.propertyPath = propertyPath;
  31724. this.value = value;
  31725. this.operator = operator;
  31726. this._target = target;
  31727. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31728. this._property = this._getProperty(this.propertyPath);
  31729. }
  31730. Object.defineProperty(ValueCondition, "IsEqual", {
  31731. get: function () {
  31732. return ValueCondition._IsEqual;
  31733. },
  31734. enumerable: true,
  31735. configurable: true
  31736. });
  31737. Object.defineProperty(ValueCondition, "IsDifferent", {
  31738. get: function () {
  31739. return ValueCondition._IsDifferent;
  31740. },
  31741. enumerable: true,
  31742. configurable: true
  31743. });
  31744. Object.defineProperty(ValueCondition, "IsGreater", {
  31745. get: function () {
  31746. return ValueCondition._IsGreater;
  31747. },
  31748. enumerable: true,
  31749. configurable: true
  31750. });
  31751. Object.defineProperty(ValueCondition, "IsLesser", {
  31752. get: function () {
  31753. return ValueCondition._IsLesser;
  31754. },
  31755. enumerable: true,
  31756. configurable: true
  31757. });
  31758. // Methods
  31759. ValueCondition.prototype.isValid = function () {
  31760. switch (this.operator) {
  31761. case ValueCondition.IsGreater:
  31762. return this._effectiveTarget[this._property] > this.value;
  31763. case ValueCondition.IsLesser:
  31764. return this._effectiveTarget[this._property] < this.value;
  31765. case ValueCondition.IsEqual:
  31766. case ValueCondition.IsDifferent:
  31767. var check;
  31768. if (this.value.equals) {
  31769. check = this.value.equals(this._effectiveTarget[this._property]);
  31770. }
  31771. else {
  31772. check = this.value === this._effectiveTarget[this._property];
  31773. }
  31774. return this.operator === ValueCondition.IsEqual ? check : !check;
  31775. }
  31776. return false;
  31777. };
  31778. ValueCondition.prototype.serialize = function () {
  31779. return this._serialize({
  31780. name: "ValueCondition",
  31781. properties: [
  31782. BABYLON.Action._GetTargetProperty(this._target),
  31783. { name: "propertyPath", value: this.propertyPath },
  31784. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31785. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31786. ]
  31787. });
  31788. };
  31789. ValueCondition.GetOperatorName = function (operator) {
  31790. switch (operator) {
  31791. case ValueCondition._IsEqual: return "IsEqual";
  31792. case ValueCondition._IsDifferent: return "IsDifferent";
  31793. case ValueCondition._IsGreater: return "IsGreater";
  31794. case ValueCondition._IsLesser: return "IsLesser";
  31795. default: return "";
  31796. }
  31797. };
  31798. // Statics
  31799. ValueCondition._IsEqual = 0;
  31800. ValueCondition._IsDifferent = 1;
  31801. ValueCondition._IsGreater = 2;
  31802. ValueCondition._IsLesser = 3;
  31803. return ValueCondition;
  31804. })(Condition);
  31805. BABYLON.ValueCondition = ValueCondition;
  31806. var PredicateCondition = (function (_super) {
  31807. __extends(PredicateCondition, _super);
  31808. function PredicateCondition(actionManager, predicate) {
  31809. _super.call(this, actionManager);
  31810. this.predicate = predicate;
  31811. }
  31812. PredicateCondition.prototype.isValid = function () {
  31813. return this.predicate();
  31814. };
  31815. return PredicateCondition;
  31816. })(Condition);
  31817. BABYLON.PredicateCondition = PredicateCondition;
  31818. var StateCondition = (function (_super) {
  31819. __extends(StateCondition, _super);
  31820. function StateCondition(actionManager, target, value) {
  31821. _super.call(this, actionManager);
  31822. this.value = value;
  31823. this._target = target;
  31824. }
  31825. // Methods
  31826. StateCondition.prototype.isValid = function () {
  31827. return this._target.state === this.value;
  31828. };
  31829. StateCondition.prototype.serialize = function () {
  31830. return this._serialize({
  31831. name: "StateCondition",
  31832. properties: [
  31833. BABYLON.Action._GetTargetProperty(this._target),
  31834. { name: "value", value: this.value }
  31835. ]
  31836. });
  31837. };
  31838. return StateCondition;
  31839. })(Condition);
  31840. BABYLON.StateCondition = StateCondition;
  31841. })(BABYLON || (BABYLON = {}));
  31842. var BABYLON;
  31843. (function (BABYLON) {
  31844. var Action = (function () {
  31845. function Action(triggerOptions, condition) {
  31846. this.triggerOptions = triggerOptions;
  31847. if (triggerOptions.parameter) {
  31848. this.trigger = triggerOptions.trigger;
  31849. this._triggerParameter = triggerOptions.parameter;
  31850. }
  31851. else {
  31852. this.trigger = triggerOptions;
  31853. }
  31854. this._nextActiveAction = this;
  31855. this._condition = condition;
  31856. }
  31857. // Methods
  31858. Action.prototype._prepare = function () {
  31859. };
  31860. Action.prototype.getTriggerParameter = function () {
  31861. return this._triggerParameter;
  31862. };
  31863. Action.prototype._executeCurrent = function (evt) {
  31864. if (this._nextActiveAction._condition) {
  31865. var condition = this._nextActiveAction._condition;
  31866. var currentRenderId = this._actionManager.getScene().getRenderId();
  31867. // We cache the current evaluation for the current frame
  31868. if (condition._evaluationId === currentRenderId) {
  31869. if (!condition._currentResult) {
  31870. return;
  31871. }
  31872. }
  31873. else {
  31874. condition._evaluationId = currentRenderId;
  31875. if (!condition.isValid()) {
  31876. condition._currentResult = false;
  31877. return;
  31878. }
  31879. condition._currentResult = true;
  31880. }
  31881. }
  31882. this._nextActiveAction.execute(evt);
  31883. this.skipToNextActiveAction();
  31884. };
  31885. Action.prototype.execute = function (evt) {
  31886. };
  31887. Action.prototype.skipToNextActiveAction = function () {
  31888. if (this._nextActiveAction._child) {
  31889. if (!this._nextActiveAction._child._actionManager) {
  31890. this._nextActiveAction._child._actionManager = this._actionManager;
  31891. }
  31892. this._nextActiveAction = this._nextActiveAction._child;
  31893. }
  31894. else {
  31895. this._nextActiveAction = this;
  31896. }
  31897. };
  31898. Action.prototype.then = function (action) {
  31899. this._child = action;
  31900. action._actionManager = this._actionManager;
  31901. action._prepare();
  31902. return action;
  31903. };
  31904. Action.prototype._getProperty = function (propertyPath) {
  31905. return this._actionManager._getProperty(propertyPath);
  31906. };
  31907. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31908. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31909. };
  31910. Action.prototype.serialize = function (parent) {
  31911. };
  31912. // Called by BABYLON.Action objects in serialize(...). Internal use
  31913. Action.prototype._serialize = function (serializedAction, parent) {
  31914. var serializationObject = {
  31915. type: 1,
  31916. children: [],
  31917. name: serializedAction.name,
  31918. properties: serializedAction.properties || []
  31919. };
  31920. // Serialize child
  31921. if (this._child) {
  31922. this._child.serialize(serializationObject);
  31923. }
  31924. // Check if "this" has a condition
  31925. if (this._condition) {
  31926. var serializedCondition = this._condition.serialize();
  31927. serializedCondition.children.push(serializationObject);
  31928. if (parent) {
  31929. parent.children.push(serializedCondition);
  31930. }
  31931. return serializedCondition;
  31932. }
  31933. if (parent) {
  31934. parent.children.push(serializationObject);
  31935. }
  31936. return serializationObject;
  31937. };
  31938. Action._SerializeValueAsString = function (value) {
  31939. if (typeof value === "number") {
  31940. return value.toString();
  31941. }
  31942. if (typeof value === "boolean") {
  31943. return value ? "true" : "false";
  31944. }
  31945. if (value instanceof BABYLON.Vector2) {
  31946. return value.x + ", " + value.y;
  31947. }
  31948. if (value instanceof BABYLON.Vector3) {
  31949. return value.x + ", " + value.y + ", " + value.z;
  31950. }
  31951. if (value instanceof BABYLON.Color3) {
  31952. return value.r + ", " + value.g + ", " + value.b;
  31953. }
  31954. if (value instanceof BABYLON.Color4) {
  31955. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31956. }
  31957. return value; // string
  31958. };
  31959. Action._GetTargetProperty = function (target) {
  31960. return {
  31961. name: "target",
  31962. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31963. : target instanceof BABYLON.Light ? "LightProperties"
  31964. : target instanceof BABYLON.Camera ? "CameraProperties"
  31965. : "SceneProperties",
  31966. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31967. };
  31968. };
  31969. return Action;
  31970. })();
  31971. BABYLON.Action = Action;
  31972. })(BABYLON || (BABYLON = {}));
  31973. var BABYLON;
  31974. (function (BABYLON) {
  31975. /**
  31976. * ActionEvent is the event beint sent when an action is triggered.
  31977. */
  31978. var ActionEvent = (function () {
  31979. /**
  31980. * @constructor
  31981. * @param source The mesh or sprite that triggered the action.
  31982. * @param pointerX The X mouse cursor position at the time of the event
  31983. * @param pointerY The Y mouse cursor position at the time of the event
  31984. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31985. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31986. */
  31987. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31988. this.source = source;
  31989. this.pointerX = pointerX;
  31990. this.pointerY = pointerY;
  31991. this.meshUnderPointer = meshUnderPointer;
  31992. this.sourceEvent = sourceEvent;
  31993. this.additionalData = additionalData;
  31994. }
  31995. /**
  31996. * Helper function to auto-create an ActionEvent from a source mesh.
  31997. * @param source The source mesh that triggered the event
  31998. * @param evt {Event} The original (browser) event
  31999. */
  32000. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32001. var scene = source.getScene();
  32002. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32003. };
  32004. /**
  32005. * Helper function to auto-create an ActionEvent from a source mesh.
  32006. * @param source The source sprite that triggered the event
  32007. * @param scene Scene associated with the sprite
  32008. * @param evt {Event} The original (browser) event
  32009. */
  32010. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32011. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32012. };
  32013. /**
  32014. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32015. * @param scene the scene where the event occurred
  32016. * @param evt {Event} The original (browser) event
  32017. */
  32018. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32019. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32020. };
  32021. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32022. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32023. };
  32024. return ActionEvent;
  32025. })();
  32026. BABYLON.ActionEvent = ActionEvent;
  32027. /**
  32028. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32029. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32030. */
  32031. var ActionManager = (function () {
  32032. function ActionManager(scene) {
  32033. // Members
  32034. this.actions = new Array();
  32035. this._scene = scene;
  32036. scene._actionManagers.push(this);
  32037. }
  32038. Object.defineProperty(ActionManager, "NothingTrigger", {
  32039. get: function () {
  32040. return ActionManager._NothingTrigger;
  32041. },
  32042. enumerable: true,
  32043. configurable: true
  32044. });
  32045. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32046. get: function () {
  32047. return ActionManager._OnPickTrigger;
  32048. },
  32049. enumerable: true,
  32050. configurable: true
  32051. });
  32052. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32053. get: function () {
  32054. return ActionManager._OnLeftPickTrigger;
  32055. },
  32056. enumerable: true,
  32057. configurable: true
  32058. });
  32059. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32060. get: function () {
  32061. return ActionManager._OnRightPickTrigger;
  32062. },
  32063. enumerable: true,
  32064. configurable: true
  32065. });
  32066. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32067. get: function () {
  32068. return ActionManager._OnCenterPickTrigger;
  32069. },
  32070. enumerable: true,
  32071. configurable: true
  32072. });
  32073. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32074. get: function () {
  32075. return ActionManager._OnPickDownTrigger;
  32076. },
  32077. enumerable: true,
  32078. configurable: true
  32079. });
  32080. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32081. get: function () {
  32082. return ActionManager._OnPickUpTrigger;
  32083. },
  32084. enumerable: true,
  32085. configurable: true
  32086. });
  32087. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32088. /// This trigger will only be raised if you also declared a OnPickDown
  32089. get: function () {
  32090. return ActionManager._OnPickOutTrigger;
  32091. },
  32092. enumerable: true,
  32093. configurable: true
  32094. });
  32095. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32096. get: function () {
  32097. return ActionManager._OnLongPressTrigger;
  32098. },
  32099. enumerable: true,
  32100. configurable: true
  32101. });
  32102. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32103. get: function () {
  32104. return ActionManager._OnPointerOverTrigger;
  32105. },
  32106. enumerable: true,
  32107. configurable: true
  32108. });
  32109. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32110. get: function () {
  32111. return ActionManager._OnPointerOutTrigger;
  32112. },
  32113. enumerable: true,
  32114. configurable: true
  32115. });
  32116. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32117. get: function () {
  32118. return ActionManager._OnEveryFrameTrigger;
  32119. },
  32120. enumerable: true,
  32121. configurable: true
  32122. });
  32123. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32124. get: function () {
  32125. return ActionManager._OnIntersectionEnterTrigger;
  32126. },
  32127. enumerable: true,
  32128. configurable: true
  32129. });
  32130. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32131. get: function () {
  32132. return ActionManager._OnIntersectionExitTrigger;
  32133. },
  32134. enumerable: true,
  32135. configurable: true
  32136. });
  32137. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32138. get: function () {
  32139. return ActionManager._OnKeyDownTrigger;
  32140. },
  32141. enumerable: true,
  32142. configurable: true
  32143. });
  32144. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32145. get: function () {
  32146. return ActionManager._OnKeyUpTrigger;
  32147. },
  32148. enumerable: true,
  32149. configurable: true
  32150. });
  32151. // Methods
  32152. ActionManager.prototype.dispose = function () {
  32153. var index = this._scene._actionManagers.indexOf(this);
  32154. if (index > -1) {
  32155. this._scene._actionManagers.splice(index, 1);
  32156. }
  32157. };
  32158. ActionManager.prototype.getScene = function () {
  32159. return this._scene;
  32160. };
  32161. /**
  32162. * Does this action manager handles actions of any of the given triggers
  32163. * @param {number[]} triggers - the triggers to be tested
  32164. * @return {boolean} whether one (or more) of the triggers is handeled
  32165. */
  32166. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32167. for (var index = 0; index < this.actions.length; index++) {
  32168. var action = this.actions[index];
  32169. if (triggers.indexOf(action.trigger) > -1) {
  32170. return true;
  32171. }
  32172. }
  32173. return false;
  32174. };
  32175. /**
  32176. * Does this action manager handles actions of a given trigger
  32177. * @param {number} trigger - the trigger to be tested
  32178. * @return {boolean} whether the trigger is handeled
  32179. */
  32180. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32181. for (var index = 0; index < this.actions.length; index++) {
  32182. var action = this.actions[index];
  32183. if (action.trigger === trigger) {
  32184. return true;
  32185. }
  32186. }
  32187. return false;
  32188. };
  32189. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32190. /**
  32191. * Does this action manager has pointer triggers
  32192. * @return {boolean} whether or not it has pointer triggers
  32193. */
  32194. get: function () {
  32195. for (var index = 0; index < this.actions.length; index++) {
  32196. var action = this.actions[index];
  32197. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32198. return true;
  32199. }
  32200. }
  32201. return false;
  32202. },
  32203. enumerable: true,
  32204. configurable: true
  32205. });
  32206. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32207. /**
  32208. * Does this action manager has pick triggers
  32209. * @return {boolean} whether or not it has pick triggers
  32210. */
  32211. get: function () {
  32212. for (var index = 0; index < this.actions.length; index++) {
  32213. var action = this.actions[index];
  32214. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32215. return true;
  32216. }
  32217. }
  32218. return false;
  32219. },
  32220. enumerable: true,
  32221. configurable: true
  32222. });
  32223. /**
  32224. * Registers an action to this action manager
  32225. * @param {BABYLON.Action} action - the action to be registered
  32226. * @return {BABYLON.Action} the action amended (prepared) after registration
  32227. */
  32228. ActionManager.prototype.registerAction = function (action) {
  32229. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32230. if (this.getScene().actionManager !== this) {
  32231. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32232. return null;
  32233. }
  32234. }
  32235. this.actions.push(action);
  32236. action._actionManager = this;
  32237. action._prepare();
  32238. return action;
  32239. };
  32240. /**
  32241. * Process a specific trigger
  32242. * @param {number} trigger - the trigger to process
  32243. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32244. */
  32245. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32246. for (var index = 0; index < this.actions.length; index++) {
  32247. var action = this.actions[index];
  32248. if (action.trigger === trigger) {
  32249. if (trigger === ActionManager.OnKeyUpTrigger
  32250. || trigger === ActionManager.OnKeyDownTrigger) {
  32251. var parameter = action.getTriggerParameter();
  32252. if (parameter) {
  32253. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32254. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32255. if (actualkey !== parameter.toLowerCase()) {
  32256. continue;
  32257. }
  32258. }
  32259. }
  32260. action._executeCurrent(evt);
  32261. }
  32262. }
  32263. };
  32264. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32265. var properties = propertyPath.split(".");
  32266. for (var index = 0; index < properties.length - 1; index++) {
  32267. target = target[properties[index]];
  32268. }
  32269. return target;
  32270. };
  32271. ActionManager.prototype._getProperty = function (propertyPath) {
  32272. var properties = propertyPath.split(".");
  32273. return properties[properties.length - 1];
  32274. };
  32275. ActionManager.prototype.serialize = function (name) {
  32276. var root = {
  32277. children: [],
  32278. name: name,
  32279. type: 3,
  32280. properties: [] // Empty for root but required
  32281. };
  32282. for (var i = 0; i < this.actions.length; i++) {
  32283. var triggerObject = {
  32284. type: 0,
  32285. children: [],
  32286. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32287. properties: []
  32288. };
  32289. var triggerOptions = this.actions[i].triggerOptions;
  32290. if (triggerOptions && typeof triggerOptions !== "number") {
  32291. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32292. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32293. }
  32294. else {
  32295. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32296. }
  32297. }
  32298. // Serialize child action, recursively
  32299. this.actions[i].serialize(triggerObject);
  32300. // Add serialized trigger
  32301. root.children.push(triggerObject);
  32302. }
  32303. return root;
  32304. };
  32305. ActionManager.Parse = function (parsedActions, object, scene) {
  32306. var actionManager = new BABYLON.ActionManager(scene);
  32307. if (object === null)
  32308. scene.actionManager = actionManager;
  32309. else
  32310. object.actionManager = actionManager;
  32311. // instanciate a new object
  32312. var instanciate = function (name, params) {
  32313. var newInstance = Object.create(BABYLON[name].prototype);
  32314. newInstance.constructor.apply(newInstance, params);
  32315. return newInstance;
  32316. };
  32317. var parseParameter = function (name, value, target, propertyPath) {
  32318. if (propertyPath === null) {
  32319. // String, boolean or float
  32320. var floatValue = parseFloat(value);
  32321. if (value === "true" || value === "false")
  32322. return value === "true";
  32323. else
  32324. return isNaN(floatValue) ? value : floatValue;
  32325. }
  32326. var effectiveTarget = propertyPath.split(".");
  32327. var values = value.split(",");
  32328. // Get effective Target
  32329. for (var i = 0; i < effectiveTarget.length; i++) {
  32330. target = target[effectiveTarget[i]];
  32331. }
  32332. // Return appropriate value with its type
  32333. if (typeof (target) === "boolean")
  32334. return values[0] === "true";
  32335. if (typeof (target) === "string")
  32336. return values[0];
  32337. // Parameters with multiple values such as Vector3 etc.
  32338. var split = new Array();
  32339. for (var i = 0; i < values.length; i++)
  32340. split.push(parseFloat(values[i]));
  32341. if (target instanceof BABYLON.Vector3)
  32342. return BABYLON.Vector3.FromArray(split);
  32343. if (target instanceof BABYLON.Vector4)
  32344. return BABYLON.Vector4.FromArray(split);
  32345. if (target instanceof BABYLON.Color3)
  32346. return BABYLON.Color3.FromArray(split);
  32347. if (target instanceof BABYLON.Color4)
  32348. return BABYLON.Color4.FromArray(split);
  32349. return parseFloat(values[0]);
  32350. };
  32351. // traverse graph per trigger
  32352. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32353. if (combineArray === void 0) { combineArray = null; }
  32354. if (parsedAction.detached)
  32355. return;
  32356. var parameters = new Array();
  32357. var target = null;
  32358. var propertyPath = null;
  32359. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32360. // Parameters
  32361. if (parsedAction.type === 2)
  32362. parameters.push(actionManager);
  32363. else
  32364. parameters.push(trigger);
  32365. if (combine) {
  32366. var actions = new Array();
  32367. for (var j = 0; j < parsedAction.combine.length; j++) {
  32368. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32369. }
  32370. parameters.push(actions);
  32371. }
  32372. else {
  32373. for (var i = 0; i < parsedAction.properties.length; i++) {
  32374. var value = parsedAction.properties[i].value;
  32375. var name = parsedAction.properties[i].name;
  32376. var targetType = parsedAction.properties[i].targetType;
  32377. if (name === "target")
  32378. if (targetType !== null && targetType === "SceneProperties")
  32379. value = target = scene;
  32380. else
  32381. value = target = scene.getNodeByName(value);
  32382. else if (name === "parent")
  32383. value = scene.getNodeByName(value);
  32384. else if (name === "sound")
  32385. value = scene.getSoundByName(value);
  32386. else if (name !== "propertyPath") {
  32387. if (parsedAction.type === 2 && name === "operator")
  32388. value = BABYLON.ValueCondition[value];
  32389. else
  32390. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32391. }
  32392. else {
  32393. propertyPath = value;
  32394. }
  32395. parameters.push(value);
  32396. }
  32397. }
  32398. if (combineArray === null) {
  32399. parameters.push(condition);
  32400. }
  32401. else {
  32402. parameters.push(null);
  32403. }
  32404. // If interpolate value action
  32405. if (parsedAction.name === "InterpolateValueAction") {
  32406. var param = parameters[parameters.length - 2];
  32407. parameters[parameters.length - 1] = param;
  32408. parameters[parameters.length - 2] = condition;
  32409. }
  32410. // Action or condition(s) and not CombineAction
  32411. var newAction = instanciate(parsedAction.name, parameters);
  32412. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32413. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32414. if (action)
  32415. action.then(nothing);
  32416. else
  32417. actionManager.registerAction(nothing);
  32418. action = nothing;
  32419. }
  32420. if (combineArray === null) {
  32421. if (newAction instanceof BABYLON.Condition) {
  32422. condition = newAction;
  32423. newAction = action;
  32424. }
  32425. else {
  32426. condition = null;
  32427. if (action)
  32428. action.then(newAction);
  32429. else
  32430. actionManager.registerAction(newAction);
  32431. }
  32432. }
  32433. else {
  32434. combineArray.push(newAction);
  32435. }
  32436. for (var i = 0; i < parsedAction.children.length; i++)
  32437. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32438. };
  32439. // triggers
  32440. for (var i = 0; i < parsedActions.children.length; i++) {
  32441. var triggerParams;
  32442. var trigger = parsedActions.children[i];
  32443. if (trigger.properties.length > 0) {
  32444. var param = trigger.properties[0].value;
  32445. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32446. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32447. }
  32448. else
  32449. triggerParams = BABYLON.ActionManager[trigger.name];
  32450. for (var j = 0; j < trigger.children.length; j++) {
  32451. if (!trigger.detached)
  32452. traverse(trigger.children[j], triggerParams, null, null);
  32453. }
  32454. }
  32455. };
  32456. ActionManager.GetTriggerName = function (trigger) {
  32457. switch (trigger) {
  32458. case 0: return "NothingTrigger";
  32459. case 1: return "OnPickTrigger";
  32460. case 2: return "OnLeftPickTrigger";
  32461. case 3: return "OnRightPickTrigger";
  32462. case 4: return "OnCenterPickTrigger";
  32463. case 5: return "OnPickDownTrigger";
  32464. case 6: return "OnPickUpTrigger";
  32465. case 7: return "OnLongPressTrigger";
  32466. case 8: return "OnPointerOverTrigger";
  32467. case 9: return "OnPointerOutTrigger";
  32468. case 10: return "OnEveryFrameTrigger";
  32469. case 11: return "OnIntersectionEnterTrigger";
  32470. case 12: return "OnIntersectionExitTrigger";
  32471. case 13: return "OnKeyDownTrigger";
  32472. case 14: return "OnKeyUpTrigger";
  32473. case 15: return "OnPickOutTrigger";
  32474. default: return "";
  32475. }
  32476. };
  32477. // Statics
  32478. ActionManager._NothingTrigger = 0;
  32479. ActionManager._OnPickTrigger = 1;
  32480. ActionManager._OnLeftPickTrigger = 2;
  32481. ActionManager._OnRightPickTrigger = 3;
  32482. ActionManager._OnCenterPickTrigger = 4;
  32483. ActionManager._OnPickDownTrigger = 5;
  32484. ActionManager._OnPickUpTrigger = 6;
  32485. ActionManager._OnLongPressTrigger = 7;
  32486. ActionManager._OnPointerOverTrigger = 8;
  32487. ActionManager._OnPointerOutTrigger = 9;
  32488. ActionManager._OnEveryFrameTrigger = 10;
  32489. ActionManager._OnIntersectionEnterTrigger = 11;
  32490. ActionManager._OnIntersectionExitTrigger = 12;
  32491. ActionManager._OnKeyDownTrigger = 13;
  32492. ActionManager._OnKeyUpTrigger = 14;
  32493. ActionManager._OnPickOutTrigger = 15;
  32494. ActionManager.DragMovementThreshold = 10; // in pixels
  32495. ActionManager.LongPressDelay = 500; // in milliseconds
  32496. return ActionManager;
  32497. })();
  32498. BABYLON.ActionManager = ActionManager;
  32499. })(BABYLON || (BABYLON = {}));
  32500. var BABYLON;
  32501. (function (BABYLON) {
  32502. var InterpolateValueAction = (function (_super) {
  32503. __extends(InterpolateValueAction, _super);
  32504. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32505. if (duration === void 0) { duration = 1000; }
  32506. _super.call(this, triggerOptions, condition);
  32507. this.propertyPath = propertyPath;
  32508. this.value = value;
  32509. this.duration = duration;
  32510. this.stopOtherAnimations = stopOtherAnimations;
  32511. this.onInterpolationDone = onInterpolationDone;
  32512. this._target = this._effectiveTarget = target;
  32513. }
  32514. InterpolateValueAction.prototype._prepare = function () {
  32515. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32516. this._property = this._getProperty(this.propertyPath);
  32517. };
  32518. InterpolateValueAction.prototype.execute = function () {
  32519. var scene = this._actionManager.getScene();
  32520. var keys = [
  32521. {
  32522. frame: 0,
  32523. value: this._effectiveTarget[this._property]
  32524. }, {
  32525. frame: 100,
  32526. value: this.value
  32527. }
  32528. ];
  32529. var dataType;
  32530. if (typeof this.value === "number") {
  32531. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32532. }
  32533. else if (this.value instanceof BABYLON.Color3) {
  32534. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32535. }
  32536. else if (this.value instanceof BABYLON.Vector3) {
  32537. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32538. }
  32539. else if (this.value instanceof BABYLON.Matrix) {
  32540. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32541. }
  32542. else if (this.value instanceof BABYLON.Quaternion) {
  32543. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32544. }
  32545. else {
  32546. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32547. return;
  32548. }
  32549. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32550. animation.setKeys(keys);
  32551. if (this.stopOtherAnimations) {
  32552. scene.stopAnimation(this._effectiveTarget);
  32553. }
  32554. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32555. };
  32556. InterpolateValueAction.prototype.serialize = function (parent) {
  32557. return _super.prototype._serialize.call(this, {
  32558. name: "InterpolateValueAction",
  32559. properties: [
  32560. BABYLON.Action._GetTargetProperty(this._target),
  32561. { name: "propertyPath", value: this.propertyPath },
  32562. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32563. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32564. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32565. ]
  32566. }, parent);
  32567. };
  32568. return InterpolateValueAction;
  32569. })(BABYLON.Action);
  32570. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32571. })(BABYLON || (BABYLON = {}));
  32572. var BABYLON;
  32573. (function (BABYLON) {
  32574. var SwitchBooleanAction = (function (_super) {
  32575. __extends(SwitchBooleanAction, _super);
  32576. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32577. _super.call(this, triggerOptions, condition);
  32578. this.propertyPath = propertyPath;
  32579. this._target = this._effectiveTarget = target;
  32580. }
  32581. SwitchBooleanAction.prototype._prepare = function () {
  32582. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32583. this._property = this._getProperty(this.propertyPath);
  32584. };
  32585. SwitchBooleanAction.prototype.execute = function () {
  32586. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32587. };
  32588. SwitchBooleanAction.prototype.serialize = function (parent) {
  32589. return _super.prototype._serialize.call(this, {
  32590. name: "SwitchBooleanAction",
  32591. properties: [
  32592. BABYLON.Action._GetTargetProperty(this._target),
  32593. { name: "propertyPath", value: this.propertyPath }
  32594. ]
  32595. }, parent);
  32596. };
  32597. return SwitchBooleanAction;
  32598. })(BABYLON.Action);
  32599. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32600. var SetStateAction = (function (_super) {
  32601. __extends(SetStateAction, _super);
  32602. function SetStateAction(triggerOptions, target, value, condition) {
  32603. _super.call(this, triggerOptions, condition);
  32604. this.value = value;
  32605. this._target = target;
  32606. }
  32607. SetStateAction.prototype.execute = function () {
  32608. this._target.state = this.value;
  32609. };
  32610. SetStateAction.prototype.serialize = function (parent) {
  32611. return _super.prototype._serialize.call(this, {
  32612. name: "SetStateAction",
  32613. properties: [
  32614. BABYLON.Action._GetTargetProperty(this._target),
  32615. { name: "value", value: this.value }
  32616. ]
  32617. }, parent);
  32618. };
  32619. return SetStateAction;
  32620. })(BABYLON.Action);
  32621. BABYLON.SetStateAction = SetStateAction;
  32622. var SetValueAction = (function (_super) {
  32623. __extends(SetValueAction, _super);
  32624. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32625. _super.call(this, triggerOptions, condition);
  32626. this.propertyPath = propertyPath;
  32627. this.value = value;
  32628. this._target = this._effectiveTarget = target;
  32629. }
  32630. SetValueAction.prototype._prepare = function () {
  32631. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32632. this._property = this._getProperty(this.propertyPath);
  32633. };
  32634. SetValueAction.prototype.execute = function () {
  32635. this._effectiveTarget[this._property] = this.value;
  32636. if (this._target.markAsDirty) {
  32637. this._target.markAsDirty(this._property);
  32638. }
  32639. };
  32640. SetValueAction.prototype.serialize = function (parent) {
  32641. return _super.prototype._serialize.call(this, {
  32642. name: "SetValueAction",
  32643. properties: [
  32644. BABYLON.Action._GetTargetProperty(this._target),
  32645. { name: "propertyPath", value: this.propertyPath },
  32646. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32647. ]
  32648. }, parent);
  32649. };
  32650. return SetValueAction;
  32651. })(BABYLON.Action);
  32652. BABYLON.SetValueAction = SetValueAction;
  32653. var IncrementValueAction = (function (_super) {
  32654. __extends(IncrementValueAction, _super);
  32655. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32656. _super.call(this, triggerOptions, condition);
  32657. this.propertyPath = propertyPath;
  32658. this.value = value;
  32659. this._target = this._effectiveTarget = target;
  32660. }
  32661. IncrementValueAction.prototype._prepare = function () {
  32662. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32663. this._property = this._getProperty(this.propertyPath);
  32664. if (typeof this._effectiveTarget[this._property] !== "number") {
  32665. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32666. }
  32667. };
  32668. IncrementValueAction.prototype.execute = function () {
  32669. this._effectiveTarget[this._property] += this.value;
  32670. if (this._target.markAsDirty) {
  32671. this._target.markAsDirty(this._property);
  32672. }
  32673. };
  32674. IncrementValueAction.prototype.serialize = function (parent) {
  32675. return _super.prototype._serialize.call(this, {
  32676. name: "IncrementValueAction",
  32677. properties: [
  32678. BABYLON.Action._GetTargetProperty(this._target),
  32679. { name: "propertyPath", value: this.propertyPath },
  32680. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32681. ]
  32682. }, parent);
  32683. };
  32684. return IncrementValueAction;
  32685. })(BABYLON.Action);
  32686. BABYLON.IncrementValueAction = IncrementValueAction;
  32687. var PlayAnimationAction = (function (_super) {
  32688. __extends(PlayAnimationAction, _super);
  32689. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32690. _super.call(this, triggerOptions, condition);
  32691. this.from = from;
  32692. this.to = to;
  32693. this.loop = loop;
  32694. this._target = target;
  32695. }
  32696. PlayAnimationAction.prototype._prepare = function () {
  32697. };
  32698. PlayAnimationAction.prototype.execute = function () {
  32699. var scene = this._actionManager.getScene();
  32700. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32701. };
  32702. PlayAnimationAction.prototype.serialize = function (parent) {
  32703. return _super.prototype._serialize.call(this, {
  32704. name: "PlayAnimationAction",
  32705. properties: [
  32706. BABYLON.Action._GetTargetProperty(this._target),
  32707. { name: "from", value: String(this.from) },
  32708. { name: "to", value: String(this.to) },
  32709. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32710. ]
  32711. }, parent);
  32712. };
  32713. return PlayAnimationAction;
  32714. })(BABYLON.Action);
  32715. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32716. var StopAnimationAction = (function (_super) {
  32717. __extends(StopAnimationAction, _super);
  32718. function StopAnimationAction(triggerOptions, target, condition) {
  32719. _super.call(this, triggerOptions, condition);
  32720. this._target = target;
  32721. }
  32722. StopAnimationAction.prototype._prepare = function () {
  32723. };
  32724. StopAnimationAction.prototype.execute = function () {
  32725. var scene = this._actionManager.getScene();
  32726. scene.stopAnimation(this._target);
  32727. };
  32728. StopAnimationAction.prototype.serialize = function (parent) {
  32729. return _super.prototype._serialize.call(this, {
  32730. name: "StopAnimationAction",
  32731. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32732. }, parent);
  32733. };
  32734. return StopAnimationAction;
  32735. })(BABYLON.Action);
  32736. BABYLON.StopAnimationAction = StopAnimationAction;
  32737. var DoNothingAction = (function (_super) {
  32738. __extends(DoNothingAction, _super);
  32739. function DoNothingAction(triggerOptions, condition) {
  32740. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32741. _super.call(this, triggerOptions, condition);
  32742. }
  32743. DoNothingAction.prototype.execute = function () {
  32744. };
  32745. DoNothingAction.prototype.serialize = function (parent) {
  32746. return _super.prototype._serialize.call(this, {
  32747. name: "DoNothingAction",
  32748. properties: []
  32749. }, parent);
  32750. };
  32751. return DoNothingAction;
  32752. })(BABYLON.Action);
  32753. BABYLON.DoNothingAction = DoNothingAction;
  32754. var CombineAction = (function (_super) {
  32755. __extends(CombineAction, _super);
  32756. function CombineAction(triggerOptions, children, condition) {
  32757. _super.call(this, triggerOptions, condition);
  32758. this.children = children;
  32759. }
  32760. CombineAction.prototype._prepare = function () {
  32761. for (var index = 0; index < this.children.length; index++) {
  32762. this.children[index]._actionManager = this._actionManager;
  32763. this.children[index]._prepare();
  32764. }
  32765. };
  32766. CombineAction.prototype.execute = function (evt) {
  32767. for (var index = 0; index < this.children.length; index++) {
  32768. this.children[index].execute(evt);
  32769. }
  32770. };
  32771. CombineAction.prototype.serialize = function (parent) {
  32772. var serializationObject = _super.prototype._serialize.call(this, {
  32773. name: "CombineAction",
  32774. properties: [],
  32775. combine: []
  32776. }, parent);
  32777. for (var i = 0; i < this.children.length; i++) {
  32778. serializationObject.combine.push(this.children[i].serialize(null));
  32779. }
  32780. return serializationObject;
  32781. };
  32782. return CombineAction;
  32783. })(BABYLON.Action);
  32784. BABYLON.CombineAction = CombineAction;
  32785. var ExecuteCodeAction = (function (_super) {
  32786. __extends(ExecuteCodeAction, _super);
  32787. function ExecuteCodeAction(triggerOptions, func, condition) {
  32788. _super.call(this, triggerOptions, condition);
  32789. this.func = func;
  32790. }
  32791. ExecuteCodeAction.prototype.execute = function (evt) {
  32792. this.func(evt);
  32793. };
  32794. return ExecuteCodeAction;
  32795. })(BABYLON.Action);
  32796. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32797. var SetParentAction = (function (_super) {
  32798. __extends(SetParentAction, _super);
  32799. function SetParentAction(triggerOptions, target, parent, condition) {
  32800. _super.call(this, triggerOptions, condition);
  32801. this._target = target;
  32802. this._parent = parent;
  32803. }
  32804. SetParentAction.prototype._prepare = function () {
  32805. };
  32806. SetParentAction.prototype.execute = function () {
  32807. if (this._target.parent === this._parent) {
  32808. return;
  32809. }
  32810. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32811. invertParentWorldMatrix.invert();
  32812. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32813. this._target.parent = this._parent;
  32814. };
  32815. SetParentAction.prototype.serialize = function (parent) {
  32816. return _super.prototype._serialize.call(this, {
  32817. name: "SetParentAction",
  32818. properties: [
  32819. BABYLON.Action._GetTargetProperty(this._target),
  32820. BABYLON.Action._GetTargetProperty(this._parent),
  32821. ]
  32822. }, parent);
  32823. };
  32824. return SetParentAction;
  32825. })(BABYLON.Action);
  32826. BABYLON.SetParentAction = SetParentAction;
  32827. var PlaySoundAction = (function (_super) {
  32828. __extends(PlaySoundAction, _super);
  32829. function PlaySoundAction(triggerOptions, sound, condition) {
  32830. _super.call(this, triggerOptions, condition);
  32831. this._sound = sound;
  32832. }
  32833. PlaySoundAction.prototype._prepare = function () {
  32834. };
  32835. PlaySoundAction.prototype.execute = function () {
  32836. if (this._sound !== undefined)
  32837. this._sound.play();
  32838. };
  32839. PlaySoundAction.prototype.serialize = function (parent) {
  32840. return _super.prototype._serialize.call(this, {
  32841. name: "PlaySoundAction",
  32842. properties: [{ name: "sound", value: this._sound.name }]
  32843. }, parent);
  32844. };
  32845. return PlaySoundAction;
  32846. })(BABYLON.Action);
  32847. BABYLON.PlaySoundAction = PlaySoundAction;
  32848. var StopSoundAction = (function (_super) {
  32849. __extends(StopSoundAction, _super);
  32850. function StopSoundAction(triggerOptions, sound, condition) {
  32851. _super.call(this, triggerOptions, condition);
  32852. this._sound = sound;
  32853. }
  32854. StopSoundAction.prototype._prepare = function () {
  32855. };
  32856. StopSoundAction.prototype.execute = function () {
  32857. if (this._sound !== undefined)
  32858. this._sound.stop();
  32859. };
  32860. StopSoundAction.prototype.serialize = function (parent) {
  32861. return _super.prototype._serialize.call(this, {
  32862. name: "StopSoundAction",
  32863. properties: [{ name: "sound", value: this._sound.name }]
  32864. }, parent);
  32865. };
  32866. return StopSoundAction;
  32867. })(BABYLON.Action);
  32868. BABYLON.StopSoundAction = StopSoundAction;
  32869. })(BABYLON || (BABYLON = {}));
  32870. var BABYLON;
  32871. (function (BABYLON) {
  32872. var Geometry = (function () {
  32873. function Geometry(id, scene, vertexData, updatable, mesh) {
  32874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32875. this._totalVertices = 0;
  32876. this._isDisposed = false;
  32877. this.id = id;
  32878. this._engine = scene.getEngine();
  32879. this._meshes = [];
  32880. this._scene = scene;
  32881. //Init vertex buffer cache
  32882. this._vertexBuffers = {};
  32883. this._indices = [];
  32884. // vertexData
  32885. if (vertexData) {
  32886. this.setAllVerticesData(vertexData, updatable);
  32887. }
  32888. else {
  32889. this._totalVertices = 0;
  32890. this._indices = [];
  32891. }
  32892. // applyToMesh
  32893. if (mesh) {
  32894. if (mesh instanceof BABYLON.LinesMesh) {
  32895. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32896. this.updateExtend();
  32897. }
  32898. this.applyToMesh(mesh);
  32899. mesh.computeWorldMatrix(true);
  32900. }
  32901. }
  32902. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32903. /**
  32904. * 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
  32905. * @returns The Bias Vector
  32906. */
  32907. get: function () {
  32908. return this._boundingBias;
  32909. },
  32910. set: function (value) {
  32911. if (this._boundingBias && this._boundingBias.equals(value)) {
  32912. return;
  32913. }
  32914. this._boundingBias = value.clone();
  32915. this.updateBoundingInfo(true, null);
  32916. },
  32917. enumerable: true,
  32918. configurable: true
  32919. });
  32920. Object.defineProperty(Geometry.prototype, "extend", {
  32921. get: function () {
  32922. return this._extend;
  32923. },
  32924. enumerable: true,
  32925. configurable: true
  32926. });
  32927. Geometry.prototype.getScene = function () {
  32928. return this._scene;
  32929. };
  32930. Geometry.prototype.getEngine = function () {
  32931. return this._engine;
  32932. };
  32933. Geometry.prototype.isReady = function () {
  32934. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32935. };
  32936. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32937. vertexData.applyToGeometry(this, updatable);
  32938. this.notifyUpdate();
  32939. };
  32940. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32941. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32942. this.setVerticesBuffer(buffer);
  32943. };
  32944. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32945. var kind = buffer.getKind();
  32946. if (this._vertexBuffers[kind]) {
  32947. this._vertexBuffers[kind].dispose();
  32948. }
  32949. this._vertexBuffers[kind] = buffer;
  32950. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32951. var data = buffer.getData();
  32952. var stride = buffer.getStrideSize();
  32953. this._totalVertices = data.length / stride;
  32954. this.updateExtend(data, stride);
  32955. var meshes = this._meshes;
  32956. var numOfMeshes = meshes.length;
  32957. for (var index = 0; index < numOfMeshes; index++) {
  32958. var mesh = meshes[index];
  32959. mesh._resetPointsArrayCache();
  32960. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32961. mesh._createGlobalSubMesh();
  32962. mesh.computeWorldMatrix(true);
  32963. }
  32964. }
  32965. this.notifyUpdate(kind);
  32966. };
  32967. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32968. var vertexBuffer = this.getVertexBuffer(kind);
  32969. if (!vertexBuffer) {
  32970. return;
  32971. }
  32972. vertexBuffer.updateDirectly(data, offset);
  32973. this.notifyUpdate(kind);
  32974. };
  32975. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32976. var vertexBuffer = this.getVertexBuffer(kind);
  32977. if (!vertexBuffer) {
  32978. return;
  32979. }
  32980. vertexBuffer.update(data);
  32981. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32982. var stride = vertexBuffer.getStrideSize();
  32983. this._totalVertices = data.length / stride;
  32984. this.updateBoundingInfo(updateExtends, data);
  32985. }
  32986. this.notifyUpdate(kind);
  32987. };
  32988. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32989. if (updateExtends) {
  32990. this.updateExtend(data);
  32991. }
  32992. var meshes = this._meshes;
  32993. var numOfMeshes = meshes.length;
  32994. for (var index = 0; index < numOfMeshes; index++) {
  32995. var mesh = meshes[index];
  32996. mesh._resetPointsArrayCache();
  32997. if (updateExtends) {
  32998. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32999. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33000. var subMesh = mesh.subMeshes[subIndex];
  33001. subMesh.refreshBoundingInfo();
  33002. }
  33003. }
  33004. }
  33005. };
  33006. Geometry.prototype.getTotalVertices = function () {
  33007. if (!this.isReady()) {
  33008. return 0;
  33009. }
  33010. return this._totalVertices;
  33011. };
  33012. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33013. var vertexBuffer = this.getVertexBuffer(kind);
  33014. if (!vertexBuffer) {
  33015. return null;
  33016. }
  33017. var orig = vertexBuffer.getData();
  33018. if (!copyWhenShared || this._meshes.length === 1) {
  33019. return orig;
  33020. }
  33021. else {
  33022. var len = orig.length;
  33023. var copy = [];
  33024. for (var i = 0; i < len; i++) {
  33025. copy.push(orig[i]);
  33026. }
  33027. return copy;
  33028. }
  33029. };
  33030. Geometry.prototype.getVertexBuffer = function (kind) {
  33031. if (!this.isReady()) {
  33032. return null;
  33033. }
  33034. return this._vertexBuffers[kind];
  33035. };
  33036. Geometry.prototype.getVertexBuffers = function () {
  33037. if (!this.isReady()) {
  33038. return null;
  33039. }
  33040. return this._vertexBuffers;
  33041. };
  33042. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33043. if (!this._vertexBuffers) {
  33044. if (this._delayInfo) {
  33045. return this._delayInfo.indexOf(kind) !== -1;
  33046. }
  33047. return false;
  33048. }
  33049. return this._vertexBuffers[kind] !== undefined;
  33050. };
  33051. Geometry.prototype.getVerticesDataKinds = function () {
  33052. var result = [];
  33053. var kind;
  33054. if (!this._vertexBuffers && this._delayInfo) {
  33055. for (kind in this._delayInfo) {
  33056. result.push(kind);
  33057. }
  33058. }
  33059. else {
  33060. for (kind in this._vertexBuffers) {
  33061. result.push(kind);
  33062. }
  33063. }
  33064. return result;
  33065. };
  33066. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33067. if (this._indexBuffer) {
  33068. this._engine._releaseBuffer(this._indexBuffer);
  33069. }
  33070. this._indices = indices;
  33071. if (this._meshes.length !== 0 && this._indices) {
  33072. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33073. }
  33074. if (totalVertices !== undefined) {
  33075. this._totalVertices = totalVertices;
  33076. }
  33077. var meshes = this._meshes;
  33078. var numOfMeshes = meshes.length;
  33079. for (var index = 0; index < numOfMeshes; index++) {
  33080. meshes[index]._createGlobalSubMesh();
  33081. }
  33082. this.notifyUpdate();
  33083. };
  33084. Geometry.prototype.getTotalIndices = function () {
  33085. if (!this.isReady()) {
  33086. return 0;
  33087. }
  33088. return this._indices.length;
  33089. };
  33090. Geometry.prototype.getIndices = function (copyWhenShared) {
  33091. if (!this.isReady()) {
  33092. return null;
  33093. }
  33094. var orig = this._indices;
  33095. if (!copyWhenShared || this._meshes.length === 1) {
  33096. return orig;
  33097. }
  33098. else {
  33099. var len = orig.length;
  33100. var copy = [];
  33101. for (var i = 0; i < len; i++) {
  33102. copy.push(orig[i]);
  33103. }
  33104. return copy;
  33105. }
  33106. };
  33107. Geometry.prototype.getIndexBuffer = function () {
  33108. if (!this.isReady()) {
  33109. return null;
  33110. }
  33111. return this._indexBuffer;
  33112. };
  33113. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33114. var meshes = this._meshes;
  33115. var index = meshes.indexOf(mesh);
  33116. if (index === -1) {
  33117. return;
  33118. }
  33119. for (var kind in this._vertexBuffers) {
  33120. this._vertexBuffers[kind].dispose();
  33121. }
  33122. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33123. this._indexBuffer = null;
  33124. }
  33125. meshes.splice(index, 1);
  33126. mesh._geometry = null;
  33127. if (meshes.length === 0 && shouldDispose) {
  33128. this.dispose();
  33129. }
  33130. };
  33131. Geometry.prototype.applyToMesh = function (mesh) {
  33132. if (mesh._geometry === this) {
  33133. return;
  33134. }
  33135. var previousGeometry = mesh._geometry;
  33136. if (previousGeometry) {
  33137. previousGeometry.releaseForMesh(mesh);
  33138. }
  33139. var meshes = this._meshes;
  33140. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33141. mesh._geometry = this;
  33142. this._scene.pushGeometry(this);
  33143. meshes.push(mesh);
  33144. if (this.isReady()) {
  33145. this._applyToMesh(mesh);
  33146. }
  33147. else {
  33148. mesh._boundingInfo = this._boundingInfo;
  33149. }
  33150. };
  33151. Geometry.prototype.updateExtend = function (data, stride) {
  33152. if (data === void 0) { data = null; }
  33153. if (!data) {
  33154. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33155. }
  33156. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33157. };
  33158. Geometry.prototype._applyToMesh = function (mesh) {
  33159. var numOfMeshes = this._meshes.length;
  33160. // vertexBuffers
  33161. for (var kind in this._vertexBuffers) {
  33162. if (numOfMeshes === 1) {
  33163. this._vertexBuffers[kind].create();
  33164. }
  33165. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33166. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33167. mesh._resetPointsArrayCache();
  33168. if (!this._extend) {
  33169. this.updateExtend(this._vertexBuffers[kind].getData());
  33170. }
  33171. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33172. mesh._createGlobalSubMesh();
  33173. //bounding info was just created again, world matrix should be applied again.
  33174. mesh._updateBoundingInfo();
  33175. }
  33176. }
  33177. // indexBuffer
  33178. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33179. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33180. }
  33181. if (this._indexBuffer) {
  33182. this._indexBuffer.references = numOfMeshes;
  33183. }
  33184. };
  33185. Geometry.prototype.notifyUpdate = function (kind) {
  33186. if (this.onGeometryUpdated) {
  33187. this.onGeometryUpdated(this, kind);
  33188. }
  33189. };
  33190. Geometry.prototype.load = function (scene, onLoaded) {
  33191. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33192. return;
  33193. }
  33194. if (this.isReady()) {
  33195. if (onLoaded) {
  33196. onLoaded();
  33197. }
  33198. return;
  33199. }
  33200. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33201. this._queueLoad(scene, onLoaded);
  33202. };
  33203. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33204. var _this = this;
  33205. scene._addPendingData(this);
  33206. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33207. _this._delayLoadingFunction(JSON.parse(data), _this);
  33208. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33209. _this._delayInfo = [];
  33210. scene._removePendingData(_this);
  33211. var meshes = _this._meshes;
  33212. var numOfMeshes = meshes.length;
  33213. for (var index = 0; index < numOfMeshes; index++) {
  33214. _this._applyToMesh(meshes[index]);
  33215. }
  33216. if (onLoaded) {
  33217. onLoaded();
  33218. }
  33219. }, function () { }, scene.database);
  33220. };
  33221. /**
  33222. * Invert the geometry to move from a right handed system to a left handed one.
  33223. */
  33224. Geometry.prototype.toLeftHanded = function () {
  33225. // Flip faces
  33226. var tIndices = this.getIndices(false);
  33227. if (tIndices != null && tIndices.length > 0) {
  33228. for (var i = 0; i < tIndices.length; i += 3) {
  33229. var tTemp = tIndices[i + 0];
  33230. tIndices[i + 0] = tIndices[i + 2];
  33231. tIndices[i + 2] = tTemp;
  33232. }
  33233. this.setIndices(tIndices);
  33234. }
  33235. // Negate position.z
  33236. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33237. if (tPositions != null && tPositions.length > 0) {
  33238. for (var i = 0; i < tPositions.length; i += 3) {
  33239. tPositions[i + 2] = -tPositions[i + 2];
  33240. }
  33241. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33242. }
  33243. // Negate normal.z
  33244. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33245. if (tNormals != null && tNormals.length > 0) {
  33246. for (var i = 0; i < tNormals.length; i += 3) {
  33247. tNormals[i + 2] = -tNormals[i + 2];
  33248. }
  33249. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33250. }
  33251. };
  33252. Geometry.prototype.isDisposed = function () {
  33253. return this._isDisposed;
  33254. };
  33255. Geometry.prototype.dispose = function () {
  33256. var meshes = this._meshes;
  33257. var numOfMeshes = meshes.length;
  33258. var index;
  33259. for (index = 0; index < numOfMeshes; index++) {
  33260. this.releaseForMesh(meshes[index]);
  33261. }
  33262. this._meshes = [];
  33263. for (var kind in this._vertexBuffers) {
  33264. this._vertexBuffers[kind].dispose();
  33265. }
  33266. this._vertexBuffers = {};
  33267. this._totalVertices = 0;
  33268. if (this._indexBuffer) {
  33269. this._engine._releaseBuffer(this._indexBuffer);
  33270. }
  33271. this._indexBuffer = null;
  33272. this._indices = [];
  33273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33274. this.delayLoadingFile = null;
  33275. this._delayLoadingFunction = null;
  33276. this._delayInfo = [];
  33277. this._boundingInfo = null;
  33278. this._scene.removeGeometry(this);
  33279. this._isDisposed = true;
  33280. };
  33281. Geometry.prototype.copy = function (id) {
  33282. var vertexData = new BABYLON.VertexData();
  33283. vertexData.indices = [];
  33284. var indices = this.getIndices();
  33285. for (var index = 0; index < indices.length; index++) {
  33286. vertexData.indices.push(indices[index]);
  33287. }
  33288. var updatable = false;
  33289. var stopChecking = false;
  33290. var kind;
  33291. for (kind in this._vertexBuffers) {
  33292. // using slice() to make a copy of the array and not just reference it
  33293. var data = this.getVerticesData(kind);
  33294. if (data instanceof Float32Array) {
  33295. vertexData.set(new Float32Array(data), kind);
  33296. }
  33297. else {
  33298. vertexData.set(data.slice(0), kind);
  33299. }
  33300. if (!stopChecking) {
  33301. updatable = this.getVertexBuffer(kind).isUpdatable();
  33302. stopChecking = !updatable;
  33303. }
  33304. }
  33305. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33306. geometry.delayLoadState = this.delayLoadState;
  33307. geometry.delayLoadingFile = this.delayLoadingFile;
  33308. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33309. for (kind in this._delayInfo) {
  33310. geometry._delayInfo = geometry._delayInfo || [];
  33311. geometry._delayInfo.push(kind);
  33312. }
  33313. // Bounding info
  33314. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33315. return geometry;
  33316. };
  33317. Geometry.prototype.serialize = function () {
  33318. var serializationObject = {};
  33319. serializationObject.id = this.id;
  33320. if (BABYLON.Tags.HasTags(this)) {
  33321. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33322. }
  33323. return serializationObject;
  33324. };
  33325. Geometry.prototype.serializeVerticeData = function () {
  33326. var serializationObject = this.serialize();
  33327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33328. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33329. }
  33330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33331. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33332. }
  33333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33334. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33335. }
  33336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33337. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33338. }
  33339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33340. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33341. }
  33342. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33343. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33344. }
  33345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33346. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33347. }
  33348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33349. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33350. }
  33351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33352. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33353. }
  33354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33355. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33356. serializationObject.matricesIndices._isExpanded = true;
  33357. }
  33358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33359. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33360. }
  33361. serializationObject.indices = this.getIndices();
  33362. return serializationObject;
  33363. };
  33364. // Statics
  33365. Geometry.ExtractFromMesh = function (mesh, id) {
  33366. var geometry = mesh._geometry;
  33367. if (!geometry) {
  33368. return null;
  33369. }
  33370. return geometry.copy(id);
  33371. };
  33372. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33373. // be aware Math.random() could cause collisions
  33374. Geometry.RandomId = function () {
  33375. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33376. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33377. return v.toString(16);
  33378. });
  33379. };
  33380. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33381. var scene = mesh.getScene();
  33382. // Geometry
  33383. var geometryId = parsedGeometry.geometryId;
  33384. if (geometryId) {
  33385. var geometry = scene.getGeometryByID(geometryId);
  33386. if (geometry) {
  33387. geometry.applyToMesh(mesh);
  33388. }
  33389. }
  33390. else if (parsedGeometry instanceof ArrayBuffer) {
  33391. var binaryInfo = mesh._binaryInfo;
  33392. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33393. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33394. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33395. }
  33396. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33397. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33398. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33399. }
  33400. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33401. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33402. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33403. }
  33404. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33405. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33406. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33407. }
  33408. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33409. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33410. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33411. }
  33412. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33413. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33414. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33415. }
  33416. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33417. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33418. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33419. }
  33420. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33421. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33422. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33423. }
  33424. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33425. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33426. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33427. }
  33428. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33429. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33431. }
  33432. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33433. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33435. }
  33436. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33437. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33438. mesh.setIndices(indicesData);
  33439. }
  33440. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33441. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33442. mesh.subMeshes = [];
  33443. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33444. var materialIndex = subMeshesData[(i * 5) + 0];
  33445. var verticesStart = subMeshesData[(i * 5) + 1];
  33446. var verticesCount = subMeshesData[(i * 5) + 2];
  33447. var indexStart = subMeshesData[(i * 5) + 3];
  33448. var indexCount = subMeshesData[(i * 5) + 4];
  33449. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33450. }
  33451. }
  33452. }
  33453. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33454. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33455. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33456. if (parsedGeometry.uvs) {
  33457. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33458. }
  33459. if (parsedGeometry.uvs2) {
  33460. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33461. }
  33462. if (parsedGeometry.uvs3) {
  33463. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33464. }
  33465. if (parsedGeometry.uvs4) {
  33466. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33467. }
  33468. if (parsedGeometry.uvs5) {
  33469. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33470. }
  33471. if (parsedGeometry.uvs6) {
  33472. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33473. }
  33474. if (parsedGeometry.colors) {
  33475. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33476. }
  33477. if (parsedGeometry.matricesIndices) {
  33478. if (!parsedGeometry.matricesIndices._isExpanded) {
  33479. var floatIndices = [];
  33480. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33481. var matricesIndex = parsedGeometry.matricesIndices[i];
  33482. floatIndices.push(matricesIndex & 0x000000FF);
  33483. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33484. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33485. floatIndices.push(matricesIndex >> 24);
  33486. }
  33487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33488. }
  33489. else {
  33490. delete parsedGeometry.matricesIndices._isExpanded;
  33491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33492. }
  33493. }
  33494. if (parsedGeometry.matricesIndicesExtra) {
  33495. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33496. var floatIndices = [];
  33497. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33498. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33499. floatIndices.push(matricesIndex & 0x000000FF);
  33500. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33501. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33502. floatIndices.push(matricesIndex >> 24);
  33503. }
  33504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33505. }
  33506. else {
  33507. delete parsedGeometry.matricesIndices._isExpanded;
  33508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33509. }
  33510. }
  33511. if (parsedGeometry.matricesWeights) {
  33512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33513. }
  33514. if (parsedGeometry.matricesWeightsExtra) {
  33515. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33516. }
  33517. mesh.setIndices(parsedGeometry.indices);
  33518. }
  33519. // SubMeshes
  33520. if (parsedGeometry.subMeshes) {
  33521. mesh.subMeshes = [];
  33522. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33523. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33524. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33525. }
  33526. }
  33527. // Flat shading
  33528. if (mesh._shouldGenerateFlatShading) {
  33529. mesh.convertToFlatShadedMesh();
  33530. delete mesh._shouldGenerateFlatShading;
  33531. }
  33532. // Update
  33533. mesh.computeWorldMatrix(true);
  33534. // Octree
  33535. if (scene['_selectionOctree']) {
  33536. scene['_selectionOctree'].addMesh(mesh);
  33537. }
  33538. };
  33539. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33540. if (scene.getGeometryByID(parsedVertexData.id)) {
  33541. return null; // null since geometry could be something else than a box...
  33542. }
  33543. var geometry = new Geometry(parsedVertexData.id, scene);
  33544. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33545. if (parsedVertexData.delayLoadingFile) {
  33546. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33547. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33548. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33549. geometry._delayInfo = [];
  33550. if (parsedVertexData.hasUVs) {
  33551. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33552. }
  33553. if (parsedVertexData.hasUVs2) {
  33554. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33555. }
  33556. if (parsedVertexData.hasUVs3) {
  33557. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33558. }
  33559. if (parsedVertexData.hasUVs4) {
  33560. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33561. }
  33562. if (parsedVertexData.hasUVs5) {
  33563. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33564. }
  33565. if (parsedVertexData.hasUVs6) {
  33566. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33567. }
  33568. if (parsedVertexData.hasColors) {
  33569. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33570. }
  33571. if (parsedVertexData.hasMatricesIndices) {
  33572. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33573. }
  33574. if (parsedVertexData.hasMatricesWeights) {
  33575. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33576. }
  33577. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33578. }
  33579. else {
  33580. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33581. }
  33582. scene.pushGeometry(geometry, true);
  33583. return geometry;
  33584. };
  33585. return Geometry;
  33586. })();
  33587. BABYLON.Geometry = Geometry;
  33588. /////// Primitives //////////////////////////////////////////////
  33589. var Geometry;
  33590. (function (Geometry) {
  33591. var Primitives;
  33592. (function (Primitives) {
  33593. /// Abstract class
  33594. var _Primitive = (function (_super) {
  33595. __extends(_Primitive, _super);
  33596. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33597. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33598. this._canBeRegenerated = _canBeRegenerated;
  33599. this._beingRegenerated = true;
  33600. this.regenerate();
  33601. this._beingRegenerated = false;
  33602. }
  33603. _Primitive.prototype.canBeRegenerated = function () {
  33604. return this._canBeRegenerated;
  33605. };
  33606. _Primitive.prototype.regenerate = function () {
  33607. if (!this._canBeRegenerated) {
  33608. return;
  33609. }
  33610. this._beingRegenerated = true;
  33611. this.setAllVerticesData(this._regenerateVertexData(), false);
  33612. this._beingRegenerated = false;
  33613. };
  33614. _Primitive.prototype.asNewGeometry = function (id) {
  33615. return _super.prototype.copy.call(this, id);
  33616. };
  33617. // overrides
  33618. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33619. if (!this._beingRegenerated) {
  33620. return;
  33621. }
  33622. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33623. };
  33624. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33625. if (!this._beingRegenerated) {
  33626. return;
  33627. }
  33628. _super.prototype.setVerticesData.call(this, kind, data, false);
  33629. };
  33630. // to override
  33631. // protected
  33632. _Primitive.prototype._regenerateVertexData = function () {
  33633. throw new Error("Abstract method");
  33634. };
  33635. _Primitive.prototype.copy = function (id) {
  33636. throw new Error("Must be overriden in sub-classes.");
  33637. };
  33638. _Primitive.prototype.serialize = function () {
  33639. var serializationObject = _super.prototype.serialize.call(this);
  33640. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33641. return serializationObject;
  33642. };
  33643. return _Primitive;
  33644. })(Geometry);
  33645. Primitives._Primitive = _Primitive;
  33646. var Ribbon = (function (_super) {
  33647. __extends(Ribbon, _super);
  33648. // Members
  33649. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33650. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33651. _super.call(this, id, scene, canBeRegenerated, mesh);
  33652. this.pathArray = pathArray;
  33653. this.closeArray = closeArray;
  33654. this.closePath = closePath;
  33655. this.offset = offset;
  33656. this.side = side;
  33657. }
  33658. Ribbon.prototype._regenerateVertexData = function () {
  33659. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33660. };
  33661. Ribbon.prototype.copy = function (id) {
  33662. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33663. };
  33664. return Ribbon;
  33665. })(_Primitive);
  33666. Primitives.Ribbon = Ribbon;
  33667. var Box = (function (_super) {
  33668. __extends(Box, _super);
  33669. // Members
  33670. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33671. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33672. _super.call(this, id, scene, canBeRegenerated, mesh);
  33673. this.size = size;
  33674. this.side = side;
  33675. }
  33676. Box.prototype._regenerateVertexData = function () {
  33677. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33678. };
  33679. Box.prototype.copy = function (id) {
  33680. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33681. };
  33682. Box.prototype.serialize = function () {
  33683. var serializationObject = _super.prototype.serialize.call(this);
  33684. serializationObject.size = this.size;
  33685. return serializationObject;
  33686. };
  33687. Box.Parse = function (parsedBox, scene) {
  33688. if (scene.getGeometryByID(parsedBox.id)) {
  33689. return null; // null since geometry could be something else than a box...
  33690. }
  33691. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33692. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33693. scene.pushGeometry(box, true);
  33694. return box;
  33695. };
  33696. return Box;
  33697. })(_Primitive);
  33698. Primitives.Box = Box;
  33699. var Sphere = (function (_super) {
  33700. __extends(Sphere, _super);
  33701. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33702. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33703. _super.call(this, id, scene, canBeRegenerated, mesh);
  33704. this.segments = segments;
  33705. this.diameter = diameter;
  33706. this.side = side;
  33707. }
  33708. Sphere.prototype._regenerateVertexData = function () {
  33709. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33710. };
  33711. Sphere.prototype.copy = function (id) {
  33712. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33713. };
  33714. Sphere.prototype.serialize = function () {
  33715. var serializationObject = _super.prototype.serialize.call(this);
  33716. serializationObject.segments = this.segments;
  33717. serializationObject.diameter = this.diameter;
  33718. return serializationObject;
  33719. };
  33720. Sphere.Parse = function (parsedSphere, scene) {
  33721. if (scene.getGeometryByID(parsedSphere.id)) {
  33722. return null; // null since geometry could be something else than a sphere...
  33723. }
  33724. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33725. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33726. scene.pushGeometry(sphere, true);
  33727. return sphere;
  33728. };
  33729. return Sphere;
  33730. })(_Primitive);
  33731. Primitives.Sphere = Sphere;
  33732. var Disc = (function (_super) {
  33733. __extends(Disc, _super);
  33734. // Members
  33735. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33736. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33737. _super.call(this, id, scene, canBeRegenerated, mesh);
  33738. this.radius = radius;
  33739. this.tessellation = tessellation;
  33740. this.side = side;
  33741. }
  33742. Disc.prototype._regenerateVertexData = function () {
  33743. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33744. };
  33745. Disc.prototype.copy = function (id) {
  33746. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33747. };
  33748. return Disc;
  33749. })(_Primitive);
  33750. Primitives.Disc = Disc;
  33751. var Cylinder = (function (_super) {
  33752. __extends(Cylinder, _super);
  33753. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33754. if (subdivisions === void 0) { subdivisions = 1; }
  33755. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33756. _super.call(this, id, scene, canBeRegenerated, mesh);
  33757. this.height = height;
  33758. this.diameterTop = diameterTop;
  33759. this.diameterBottom = diameterBottom;
  33760. this.tessellation = tessellation;
  33761. this.subdivisions = subdivisions;
  33762. this.side = side;
  33763. }
  33764. Cylinder.prototype._regenerateVertexData = function () {
  33765. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33766. };
  33767. Cylinder.prototype.copy = function (id) {
  33768. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33769. };
  33770. Cylinder.prototype.serialize = function () {
  33771. var serializationObject = _super.prototype.serialize.call(this);
  33772. serializationObject.height = this.height;
  33773. serializationObject.diameterTop = this.diameterTop;
  33774. serializationObject.diameterBottom = this.diameterBottom;
  33775. serializationObject.tessellation = this.tessellation;
  33776. return serializationObject;
  33777. };
  33778. Cylinder.Parse = function (parsedCylinder, scene) {
  33779. if (scene.getGeometryByID(parsedCylinder.id)) {
  33780. return null; // null since geometry could be something else than a cylinder...
  33781. }
  33782. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33783. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33784. scene.pushGeometry(cylinder, true);
  33785. return cylinder;
  33786. };
  33787. return Cylinder;
  33788. })(_Primitive);
  33789. Primitives.Cylinder = Cylinder;
  33790. var Torus = (function (_super) {
  33791. __extends(Torus, _super);
  33792. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33793. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33794. _super.call(this, id, scene, canBeRegenerated, mesh);
  33795. this.diameter = diameter;
  33796. this.thickness = thickness;
  33797. this.tessellation = tessellation;
  33798. this.side = side;
  33799. }
  33800. Torus.prototype._regenerateVertexData = function () {
  33801. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33802. };
  33803. Torus.prototype.copy = function (id) {
  33804. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33805. };
  33806. Torus.prototype.serialize = function () {
  33807. var serializationObject = _super.prototype.serialize.call(this);
  33808. serializationObject.diameter = this.diameter;
  33809. serializationObject.thickness = this.thickness;
  33810. serializationObject.tessellation = this.tessellation;
  33811. return serializationObject;
  33812. };
  33813. Torus.Parse = function (parsedTorus, scene) {
  33814. if (scene.getGeometryByID(parsedTorus.id)) {
  33815. return null; // null since geometry could be something else than a torus...
  33816. }
  33817. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33818. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33819. scene.pushGeometry(torus, true);
  33820. return torus;
  33821. };
  33822. return Torus;
  33823. })(_Primitive);
  33824. Primitives.Torus = Torus;
  33825. var Ground = (function (_super) {
  33826. __extends(Ground, _super);
  33827. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33828. _super.call(this, id, scene, canBeRegenerated, mesh);
  33829. this.width = width;
  33830. this.height = height;
  33831. this.subdivisions = subdivisions;
  33832. }
  33833. Ground.prototype._regenerateVertexData = function () {
  33834. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33835. };
  33836. Ground.prototype.copy = function (id) {
  33837. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33838. };
  33839. Ground.prototype.serialize = function () {
  33840. var serializationObject = _super.prototype.serialize.call(this);
  33841. serializationObject.width = this.width;
  33842. serializationObject.height = this.height;
  33843. serializationObject.subdivisions = this.subdivisions;
  33844. return serializationObject;
  33845. };
  33846. Ground.Parse = function (parsedGround, scene) {
  33847. if (scene.getGeometryByID(parsedGround.id)) {
  33848. return null; // null since geometry could be something else than a ground...
  33849. }
  33850. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33851. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33852. scene.pushGeometry(ground, true);
  33853. return ground;
  33854. };
  33855. return Ground;
  33856. })(_Primitive);
  33857. Primitives.Ground = Ground;
  33858. var TiledGround = (function (_super) {
  33859. __extends(TiledGround, _super);
  33860. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  33861. _super.call(this, id, scene, canBeRegenerated, mesh);
  33862. this.xmin = xmin;
  33863. this.zmin = zmin;
  33864. this.xmax = xmax;
  33865. this.zmax = zmax;
  33866. this.subdivisions = subdivisions;
  33867. this.precision = precision;
  33868. }
  33869. TiledGround.prototype._regenerateVertexData = function () {
  33870. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33871. };
  33872. TiledGround.prototype.copy = function (id) {
  33873. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33874. };
  33875. return TiledGround;
  33876. })(_Primitive);
  33877. Primitives.TiledGround = TiledGround;
  33878. var Plane = (function (_super) {
  33879. __extends(Plane, _super);
  33880. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  33881. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33882. _super.call(this, id, scene, canBeRegenerated, mesh);
  33883. this.size = size;
  33884. this.side = side;
  33885. }
  33886. Plane.prototype._regenerateVertexData = function () {
  33887. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33888. };
  33889. Plane.prototype.copy = function (id) {
  33890. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33891. };
  33892. Plane.prototype.serialize = function () {
  33893. var serializationObject = _super.prototype.serialize.call(this);
  33894. serializationObject.size = this.size;
  33895. return serializationObject;
  33896. };
  33897. Plane.Parse = function (parsedPlane, scene) {
  33898. if (scene.getGeometryByID(parsedPlane.id)) {
  33899. return null; // null since geometry could be something else than a ground...
  33900. }
  33901. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33902. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33903. scene.pushGeometry(plane, true);
  33904. return plane;
  33905. };
  33906. return Plane;
  33907. })(_Primitive);
  33908. Primitives.Plane = Plane;
  33909. var TorusKnot = (function (_super) {
  33910. __extends(TorusKnot, _super);
  33911. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33912. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33913. _super.call(this, id, scene, canBeRegenerated, mesh);
  33914. this.radius = radius;
  33915. this.tube = tube;
  33916. this.radialSegments = radialSegments;
  33917. this.tubularSegments = tubularSegments;
  33918. this.p = p;
  33919. this.q = q;
  33920. this.side = side;
  33921. }
  33922. TorusKnot.prototype._regenerateVertexData = function () {
  33923. 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 });
  33924. };
  33925. TorusKnot.prototype.copy = function (id) {
  33926. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33927. };
  33928. TorusKnot.prototype.serialize = function () {
  33929. var serializationObject = _super.prototype.serialize.call(this);
  33930. serializationObject.radius = this.radius;
  33931. serializationObject.tube = this.tube;
  33932. serializationObject.radialSegments = this.radialSegments;
  33933. serializationObject.tubularSegments = this.tubularSegments;
  33934. serializationObject.p = this.p;
  33935. serializationObject.q = this.q;
  33936. return serializationObject;
  33937. };
  33938. ;
  33939. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33940. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33941. return null; // null since geometry could be something else than a ground...
  33942. }
  33943. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33944. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33945. scene.pushGeometry(torusKnot, true);
  33946. return torusKnot;
  33947. };
  33948. return TorusKnot;
  33949. })(_Primitive);
  33950. Primitives.TorusKnot = TorusKnot;
  33951. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33952. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33953. })(BABYLON || (BABYLON = {}));
  33954. var BABYLON;
  33955. (function (BABYLON) {
  33956. var GroundMesh = (function (_super) {
  33957. __extends(GroundMesh, _super);
  33958. function GroundMesh(name, scene) {
  33959. _super.call(this, name, scene);
  33960. this.generateOctree = false;
  33961. this._worldInverse = new BABYLON.Matrix();
  33962. }
  33963. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33964. get: function () {
  33965. return this._subdivisions;
  33966. },
  33967. enumerable: true,
  33968. configurable: true
  33969. });
  33970. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33971. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33972. this._subdivisions = chunksCount;
  33973. this.subdivide(this._subdivisions);
  33974. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33975. };
  33976. /**
  33977. * Returns a height (y) value in the Worl system :
  33978. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33979. * Returns the ground y position if (x, z) are outside the ground surface.
  33980. * Not pertinent if the ground is rotated.
  33981. */
  33982. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33983. // express x and y in the ground local system
  33984. x -= this.position.x;
  33985. z -= this.position.z;
  33986. x /= this.scaling.x;
  33987. z /= this.scaling.z;
  33988. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33989. return this.position.y;
  33990. }
  33991. if (!this._heightQuads || this._heightQuads.length == 0) {
  33992. this._initHeightQuads();
  33993. this._computeHeightQuads();
  33994. }
  33995. var facet = this._getFacetAt(x, z);
  33996. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33997. // return y in the World system
  33998. return y * this.scaling.y + this.position.y;
  33999. };
  34000. /**
  34001. * Returns a normalized vector (Vector3) orthogonal to the ground
  34002. * at the ground coordinates (x, z) expressed in the World system.
  34003. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34004. * Not pertinent if the ground is rotated.
  34005. */
  34006. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34007. var normal = new BABYLON.Vector3(0, 1, 0);
  34008. this.getNormalAtCoordinatesToRef(x, z, normal);
  34009. return normal;
  34010. };
  34011. /**
  34012. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34013. * at the ground coordinates (x, z) expressed in the World system.
  34014. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34015. * Not pertinent if the ground is rotated.
  34016. */
  34017. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34018. // express x and y in the ground local system
  34019. x -= this.position.x;
  34020. z -= this.position.z;
  34021. x /= this.scaling.x;
  34022. z /= this.scaling.z;
  34023. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34024. return;
  34025. }
  34026. if (!this._heightQuads || this._heightQuads.length == 0) {
  34027. this._initHeightQuads();
  34028. this._computeHeightQuads();
  34029. }
  34030. var facet = this._getFacetAt(x, z);
  34031. ref.x = facet.x;
  34032. ref.y = facet.y;
  34033. ref.z = facet.z;
  34034. };
  34035. /**
  34036. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34037. * if the ground has been updated.
  34038. * This can be used in the render loop
  34039. */
  34040. GroundMesh.prototype.updateCoordinateHeights = function () {
  34041. if (!this._heightQuads || this._heightQuads.length == 0) {
  34042. this._initHeightQuads();
  34043. }
  34044. this._computeHeightQuads();
  34045. };
  34046. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34047. GroundMesh.prototype._getFacetAt = function (x, z) {
  34048. // retrieve col and row from x, z coordinates in the ground local system
  34049. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34050. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34051. var quad = this._heightQuads[row * this._subdivisions + col];
  34052. var facet;
  34053. if (z < quad.slope.x * x + quad.slope.y) {
  34054. facet = quad.facet1;
  34055. }
  34056. else {
  34057. facet = quad.facet2;
  34058. }
  34059. return facet;
  34060. };
  34061. // Creates and populates the heightMap array with "facet" elements :
  34062. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34063. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34064. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34065. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34066. GroundMesh.prototype._initHeightQuads = function () {
  34067. this._heightQuads = new Array();
  34068. for (var row = 0; row < this._subdivisions; row++) {
  34069. for (var col = 0; col < this._subdivisions; col++) {
  34070. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34071. this._heightQuads[row * this._subdivisions + col] = quad;
  34072. }
  34073. }
  34074. };
  34075. // Compute each quad element values and update the the heightMap array :
  34076. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34077. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34078. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34079. GroundMesh.prototype._computeHeightQuads = function () {
  34080. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34081. var v1 = BABYLON.Tmp.Vector3[3];
  34082. var v2 = BABYLON.Tmp.Vector3[2];
  34083. var v3 = BABYLON.Tmp.Vector3[1];
  34084. var v4 = BABYLON.Tmp.Vector3[0];
  34085. var v1v2 = BABYLON.Tmp.Vector3[4];
  34086. var v1v3 = BABYLON.Tmp.Vector3[5];
  34087. var v1v4 = BABYLON.Tmp.Vector3[6];
  34088. var norm1 = BABYLON.Tmp.Vector3[7];
  34089. var norm2 = BABYLON.Tmp.Vector3[8];
  34090. var i = 0;
  34091. var j = 0;
  34092. var k = 0;
  34093. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34094. var h = 0;
  34095. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34096. var d2 = 0;
  34097. for (var row = 0; row < this._subdivisions; row++) {
  34098. for (var col = 0; col < this._subdivisions; col++) {
  34099. i = col * 3;
  34100. j = row * (this._subdivisions + 1) * 3;
  34101. k = (row + 1) * (this._subdivisions + 1) * 3;
  34102. v1.x = positions[j + i];
  34103. v1.y = positions[j + i + 1];
  34104. v1.z = positions[j + i + 2];
  34105. v2.x = positions[j + i + 3];
  34106. v2.y = positions[j + i + 4];
  34107. v2.z = positions[j + i + 5];
  34108. v3.x = positions[k + i];
  34109. v3.y = positions[k + i + 1];
  34110. v3.z = positions[k + i + 2];
  34111. v4.x = positions[k + i + 3];
  34112. v4.y = positions[k + i + 4];
  34113. v4.z = positions[k + i + 5];
  34114. // 2D slope V1V4
  34115. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34116. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34117. // facet equations :
  34118. // we compute each facet normal vector
  34119. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34120. // we compute the value d by applying the equation to v1 which belongs to the plane
  34121. // then we store the facet equation in a Vector4
  34122. v2.subtractToRef(v1, v1v2);
  34123. v3.subtractToRef(v1, v1v3);
  34124. v4.subtractToRef(v1, v1v4);
  34125. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34126. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34127. norm1.normalize();
  34128. norm2.normalize();
  34129. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34130. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34131. var quad = this._heightQuads[row * this._subdivisions + col];
  34132. quad.slope.copyFromFloats(cd, h);
  34133. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34134. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34135. }
  34136. }
  34137. };
  34138. return GroundMesh;
  34139. })(BABYLON.Mesh);
  34140. BABYLON.GroundMesh = GroundMesh;
  34141. })(BABYLON || (BABYLON = {}));
  34142. var BABYLON;
  34143. (function (BABYLON) {
  34144. var LinesMesh = (function (_super) {
  34145. __extends(LinesMesh, _super);
  34146. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34147. if (parent === void 0) { parent = null; }
  34148. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34149. this.color = new BABYLON.Color3(1, 1, 1);
  34150. this.alpha = 1;
  34151. this._positionBuffer = {};
  34152. if (source) {
  34153. this.color = source.color.clone();
  34154. this.alpha = source.alpha;
  34155. }
  34156. this._intersectionThreshold = 0.1;
  34157. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34158. attributes: [BABYLON.VertexBuffer.PositionKind],
  34159. uniforms: ["worldViewProjection", "color"],
  34160. needAlphaBlending: true
  34161. });
  34162. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34163. }
  34164. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34165. /**
  34166. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34167. * This margin is expressed in world space coordinates, so its value may vary.
  34168. * Default value is 0.1
  34169. * @returns the intersection Threshold value.
  34170. */
  34171. get: function () {
  34172. return this._intersectionThreshold;
  34173. },
  34174. /**
  34175. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34176. * This margin is expressed in world space coordinates, so its value may vary.
  34177. * @param value the new threshold to apply
  34178. */
  34179. set: function (value) {
  34180. if (this._intersectionThreshold === value) {
  34181. return;
  34182. }
  34183. this._intersectionThreshold = value;
  34184. if (this.geometry) {
  34185. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34186. }
  34187. },
  34188. enumerable: true,
  34189. configurable: true
  34190. });
  34191. Object.defineProperty(LinesMesh.prototype, "material", {
  34192. get: function () {
  34193. return this._colorShader;
  34194. },
  34195. enumerable: true,
  34196. configurable: true
  34197. });
  34198. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34199. get: function () {
  34200. return false;
  34201. },
  34202. enumerable: true,
  34203. configurable: true
  34204. });
  34205. LinesMesh.prototype.createInstance = function (name) {
  34206. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34207. return null;
  34208. };
  34209. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34210. var engine = this.getScene().getEngine();
  34211. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34212. // VBOs
  34213. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34214. // Color
  34215. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34216. };
  34217. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34218. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34219. return;
  34220. }
  34221. var engine = this.getScene().getEngine();
  34222. // Draw order
  34223. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34224. };
  34225. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34226. this._colorShader.dispose();
  34227. _super.prototype.dispose.call(this, doNotRecurse);
  34228. };
  34229. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34230. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34231. };
  34232. return LinesMesh;
  34233. })(BABYLON.Mesh);
  34234. BABYLON.LinesMesh = LinesMesh;
  34235. })(BABYLON || (BABYLON = {}));
  34236. var BABYLON;
  34237. (function (BABYLON) {
  34238. var DefaultLoadingScreen = (function () {
  34239. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34240. var _this = this;
  34241. if (_loadingText === void 0) { _loadingText = ""; }
  34242. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34243. this._renderingCanvas = _renderingCanvas;
  34244. this._loadingText = _loadingText;
  34245. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34246. // Resize
  34247. this._resizeLoadingUI = function () {
  34248. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34249. _this._loadingDiv.style.position = "absolute";
  34250. _this._loadingDiv.style.left = canvasRect.left + "px";
  34251. _this._loadingDiv.style.top = canvasRect.top + "px";
  34252. _this._loadingDiv.style.width = canvasRect.width + "px";
  34253. _this._loadingDiv.style.height = canvasRect.height + "px";
  34254. };
  34255. }
  34256. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34257. var _this = this;
  34258. if (this._loadingDiv) {
  34259. // Do not add a loading screen if there is already one
  34260. return;
  34261. }
  34262. this._loadingDiv = document.createElement("div");
  34263. this._loadingDiv.id = "babylonjsLoadingDiv";
  34264. this._loadingDiv.style.opacity = "0";
  34265. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34266. // Loading text
  34267. this._loadingTextDiv = document.createElement("div");
  34268. this._loadingTextDiv.style.position = "absolute";
  34269. this._loadingTextDiv.style.left = "0";
  34270. this._loadingTextDiv.style.top = "50%";
  34271. this._loadingTextDiv.style.marginTop = "80px";
  34272. this._loadingTextDiv.style.width = "100%";
  34273. this._loadingTextDiv.style.height = "20px";
  34274. this._loadingTextDiv.style.fontFamily = "Arial";
  34275. this._loadingTextDiv.style.fontSize = "14px";
  34276. this._loadingTextDiv.style.color = "white";
  34277. this._loadingTextDiv.style.textAlign = "center";
  34278. this._loadingTextDiv.innerHTML = "Loading";
  34279. this._loadingDiv.appendChild(this._loadingTextDiv);
  34280. //set the predefined text
  34281. this._loadingTextDiv.innerHTML = this._loadingText;
  34282. // Loading img
  34283. var imgBack = new Image();
  34284. 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==";
  34285. imgBack.style.position = "absolute";
  34286. imgBack.style.left = "50%";
  34287. imgBack.style.top = "50%";
  34288. imgBack.style.marginLeft = "-50px";
  34289. imgBack.style.marginTop = "-50px";
  34290. imgBack.style.transition = "transform 1.0s ease";
  34291. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34292. var deg = 360;
  34293. var onTransitionEnd = function () {
  34294. deg += 360;
  34295. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34296. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34297. };
  34298. imgBack.addEventListener("transitionend", onTransitionEnd);
  34299. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34300. this._loadingDiv.appendChild(imgBack);
  34301. // front image
  34302. var imgFront = new Image();
  34303. 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=";
  34304. imgFront.style.position = "absolute";
  34305. imgFront.style.left = "50%";
  34306. imgFront.style.top = "50%";
  34307. imgFront.style.marginLeft = "-50px";
  34308. imgFront.style.marginTop = "-50px";
  34309. this._loadingDiv.appendChild(imgFront);
  34310. this._resizeLoadingUI();
  34311. window.addEventListener("resize", this._resizeLoadingUI);
  34312. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34313. document.body.appendChild(this._loadingDiv);
  34314. setTimeout(function () {
  34315. _this._loadingDiv.style.opacity = "1";
  34316. imgBack.style.transform = "rotateZ(360deg)";
  34317. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34318. }, 0);
  34319. };
  34320. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34321. var _this = this;
  34322. if (!this._loadingDiv) {
  34323. return;
  34324. }
  34325. var onTransitionEnd = function () {
  34326. if (!_this._loadingDiv) {
  34327. return;
  34328. }
  34329. document.body.removeChild(_this._loadingDiv);
  34330. window.removeEventListener("resize", _this._resizeLoadingUI);
  34331. _this._loadingDiv = null;
  34332. };
  34333. this._loadingDiv.style.opacity = "0";
  34334. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34335. };
  34336. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34337. set: function (text) {
  34338. this._loadingText = text;
  34339. if (this._loadingTextDiv) {
  34340. this._loadingTextDiv.innerHTML = this._loadingText;
  34341. }
  34342. },
  34343. enumerable: true,
  34344. configurable: true
  34345. });
  34346. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34347. get: function () {
  34348. return this._loadingDivBackgroundColor;
  34349. },
  34350. set: function (color) {
  34351. this._loadingDivBackgroundColor = color;
  34352. if (!this._loadingDiv) {
  34353. return;
  34354. }
  34355. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34356. },
  34357. enumerable: true,
  34358. configurable: true
  34359. });
  34360. return DefaultLoadingScreen;
  34361. })();
  34362. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34363. })(BABYLON || (BABYLON = {}));
  34364. var BABYLON;
  34365. (function (BABYLON) {
  34366. var AudioEngine = (function () {
  34367. function AudioEngine() {
  34368. this._audioContext = null;
  34369. this._audioContextInitialized = false;
  34370. this.canUseWebAudio = false;
  34371. this.WarnedWebAudioUnsupported = false;
  34372. this.unlocked = false;
  34373. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34374. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34375. this.canUseWebAudio = true;
  34376. }
  34377. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34378. this._unlockiOSaudio();
  34379. }
  34380. else {
  34381. this.unlocked = true;
  34382. }
  34383. }
  34384. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34385. get: function () {
  34386. if (!this._audioContextInitialized) {
  34387. this._initializeAudioContext();
  34388. }
  34389. return this._audioContext;
  34390. },
  34391. enumerable: true,
  34392. configurable: true
  34393. });
  34394. AudioEngine.prototype._unlockiOSaudio = function () {
  34395. var _this = this;
  34396. var unlockaudio = function () {
  34397. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34398. var source = _this.audioContext.createBufferSource();
  34399. source.buffer = buffer;
  34400. source.connect(_this.audioContext.destination);
  34401. source.start(0);
  34402. setTimeout(function () {
  34403. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34404. _this.unlocked = true;
  34405. window.removeEventListener('touchend', unlockaudio, false);
  34406. if (_this.onAudioUnlocked) {
  34407. _this.onAudioUnlocked();
  34408. }
  34409. }
  34410. }, 0);
  34411. };
  34412. window.addEventListener('touchend', unlockaudio, false);
  34413. };
  34414. AudioEngine.prototype._initializeAudioContext = function () {
  34415. try {
  34416. if (this.canUseWebAudio) {
  34417. this._audioContext = new AudioContext();
  34418. // create a global volume gain node
  34419. this.masterGain = this._audioContext.createGain();
  34420. this.masterGain.gain.value = 1;
  34421. this.masterGain.connect(this._audioContext.destination);
  34422. this._audioContextInitialized = true;
  34423. }
  34424. }
  34425. catch (e) {
  34426. this.canUseWebAudio = false;
  34427. BABYLON.Tools.Error("Web Audio: " + e.message);
  34428. }
  34429. };
  34430. AudioEngine.prototype.dispose = function () {
  34431. if (this.canUseWebAudio && this._audioContextInitialized) {
  34432. if (this._connectedAnalyser) {
  34433. this._connectedAnalyser.stopDebugCanvas();
  34434. this._connectedAnalyser.dispose();
  34435. this.masterGain.disconnect();
  34436. this.masterGain.connect(this._audioContext.destination);
  34437. this._connectedAnalyser = null;
  34438. }
  34439. this.masterGain.gain.value = 1;
  34440. }
  34441. this.WarnedWebAudioUnsupported = false;
  34442. };
  34443. AudioEngine.prototype.getGlobalVolume = function () {
  34444. if (this.canUseWebAudio && this._audioContextInitialized) {
  34445. return this.masterGain.gain.value;
  34446. }
  34447. else {
  34448. return -1;
  34449. }
  34450. };
  34451. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34452. if (this.canUseWebAudio && this._audioContextInitialized) {
  34453. this.masterGain.gain.value = newVolume;
  34454. }
  34455. };
  34456. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34457. if (this._connectedAnalyser) {
  34458. this._connectedAnalyser.stopDebugCanvas();
  34459. }
  34460. if (this.canUseWebAudio && this._audioContextInitialized) {
  34461. this._connectedAnalyser = analyser;
  34462. this.masterGain.disconnect();
  34463. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34464. }
  34465. };
  34466. return AudioEngine;
  34467. })();
  34468. BABYLON.AudioEngine = AudioEngine;
  34469. })(BABYLON || (BABYLON = {}));
  34470. var BABYLON;
  34471. (function (BABYLON) {
  34472. var Sound = (function () {
  34473. /**
  34474. * Create a sound and attach it to a scene
  34475. * @param name Name of your sound
  34476. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34477. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34478. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34479. */
  34480. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34481. var _this = this;
  34482. this.autoplay = false;
  34483. this.loop = false;
  34484. this.useCustomAttenuation = false;
  34485. this.spatialSound = false;
  34486. this.refDistance = 1;
  34487. this.rolloffFactor = 1;
  34488. this.maxDistance = 100;
  34489. this.distanceModel = "linear";
  34490. this._panningModel = "equalpower";
  34491. this._playbackRate = 1;
  34492. this._streaming = false;
  34493. this._startTime = 0;
  34494. this._startOffset = 0;
  34495. this._position = BABYLON.Vector3.Zero();
  34496. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34497. this._volume = 1;
  34498. this._isLoaded = false;
  34499. this._isReadyToPlay = false;
  34500. this.isPlaying = false;
  34501. this.isPaused = false;
  34502. this._isDirectional = false;
  34503. // Used if you'd like to create a directional sound.
  34504. // If not set, the sound will be omnidirectional
  34505. this._coneInnerAngle = 360;
  34506. this._coneOuterAngle = 360;
  34507. this._coneOuterGain = 0;
  34508. this._isOutputConnected = false;
  34509. this.name = name;
  34510. this._scene = scene;
  34511. this._readyToPlayCallback = readyToPlayCallback;
  34512. // Default custom attenuation function is a linear attenuation
  34513. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34514. if (currentDistance < maxDistance) {
  34515. return currentVolume * (1 - currentDistance / maxDistance);
  34516. }
  34517. else {
  34518. return 0;
  34519. }
  34520. };
  34521. if (options) {
  34522. this.autoplay = options.autoplay || false;
  34523. this.loop = options.loop || false;
  34524. // if volume === 0, we need another way to check this option
  34525. if (options.volume !== undefined) {
  34526. this._volume = options.volume;
  34527. }
  34528. this.spatialSound = options.spatialSound || false;
  34529. this.maxDistance = options.maxDistance || 100;
  34530. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34531. this.rolloffFactor = options.rolloffFactor || 1;
  34532. this.refDistance = options.refDistance || 1;
  34533. this.distanceModel = options.distanceModel || "linear";
  34534. this._playbackRate = options.playbackRate || 1;
  34535. this._streaming = options.streaming || false;
  34536. }
  34537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34538. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34539. this._soundGain.gain.value = this._volume;
  34540. this._inputAudioNode = this._soundGain;
  34541. this._ouputAudioNode = this._soundGain;
  34542. if (this.spatialSound) {
  34543. this._createSpatialParameters();
  34544. }
  34545. this._scene.mainSoundTrack.AddSound(this);
  34546. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34547. if (urlOrArrayBuffer) {
  34548. // If it's an URL
  34549. if (typeof (urlOrArrayBuffer) === "string") {
  34550. // Loading sound using XHR2
  34551. if (!this._streaming) {
  34552. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34553. }
  34554. else {
  34555. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34556. this._htmlAudioElement.controls = false;
  34557. this._htmlAudioElement.loop = this.loop;
  34558. this._htmlAudioElement.crossOrigin = "anonymous";
  34559. this._htmlAudioElement.preload = "auto";
  34560. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34561. _this._isReadyToPlay = true;
  34562. if (_this.autoplay) {
  34563. _this.play();
  34564. }
  34565. if (_this._readyToPlayCallback) {
  34566. _this._readyToPlayCallback();
  34567. }
  34568. });
  34569. document.body.appendChild(this._htmlAudioElement);
  34570. }
  34571. }
  34572. else {
  34573. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34574. if (urlOrArrayBuffer.byteLength > 0) {
  34575. this._soundLoaded(urlOrArrayBuffer);
  34576. }
  34577. }
  34578. else {
  34579. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34580. }
  34581. }
  34582. }
  34583. }
  34584. else {
  34585. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34586. this._scene.mainSoundTrack.AddSound(this);
  34587. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34588. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34589. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34590. }
  34591. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34592. if (this._readyToPlayCallback) {
  34593. window.setTimeout(function () {
  34594. _this._readyToPlayCallback();
  34595. }, 1000);
  34596. }
  34597. }
  34598. }
  34599. Sound.prototype.dispose = function () {
  34600. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34601. if (this.isPlaying) {
  34602. this.stop();
  34603. }
  34604. this._isReadyToPlay = false;
  34605. if (this.soundTrackId === -1) {
  34606. this._scene.mainSoundTrack.RemoveSound(this);
  34607. }
  34608. else {
  34609. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34610. }
  34611. if (this._soundGain) {
  34612. this._soundGain.disconnect();
  34613. this._soundGain = null;
  34614. }
  34615. if (this._soundPanner) {
  34616. this._soundPanner.disconnect();
  34617. this._soundPanner = null;
  34618. }
  34619. if (this._soundSource) {
  34620. this._soundSource.disconnect();
  34621. this._soundSource = null;
  34622. }
  34623. this._audioBuffer = null;
  34624. if (this._htmlAudioElement) {
  34625. this._htmlAudioElement.pause();
  34626. this._htmlAudioElement.src = "";
  34627. document.body.removeChild(this._htmlAudioElement);
  34628. }
  34629. if (this._connectedMesh) {
  34630. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34631. this._connectedMesh = null;
  34632. }
  34633. }
  34634. };
  34635. Sound.prototype._soundLoaded = function (audioData) {
  34636. var _this = this;
  34637. this._isLoaded = true;
  34638. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34639. _this._audioBuffer = buffer;
  34640. _this._isReadyToPlay = true;
  34641. if (_this.autoplay) {
  34642. _this.play();
  34643. }
  34644. if (_this._readyToPlayCallback) {
  34645. _this._readyToPlayCallback();
  34646. }
  34647. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34648. };
  34649. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34650. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34651. this._audioBuffer = audioBuffer;
  34652. this._isReadyToPlay = true;
  34653. }
  34654. };
  34655. Sound.prototype.updateOptions = function (options) {
  34656. if (options) {
  34657. this.loop = options.loop || this.loop;
  34658. this.maxDistance = options.maxDistance || this.maxDistance;
  34659. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34660. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34661. this.refDistance = options.refDistance || this.refDistance;
  34662. this.distanceModel = options.distanceModel || this.distanceModel;
  34663. this._playbackRate = options.playbackRate || this._playbackRate;
  34664. this._updateSpatialParameters();
  34665. if (this.isPlaying) {
  34666. if (this._streaming) {
  34667. this._htmlAudioElement.playbackRate = this._playbackRate;
  34668. }
  34669. else {
  34670. this._soundSource.playbackRate.value = this._playbackRate;
  34671. }
  34672. }
  34673. }
  34674. };
  34675. Sound.prototype._createSpatialParameters = function () {
  34676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34677. if (this._scene.headphone) {
  34678. this._panningModel = "HRTF";
  34679. }
  34680. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34681. this._updateSpatialParameters();
  34682. this._soundPanner.connect(this._ouputAudioNode);
  34683. this._inputAudioNode = this._soundPanner;
  34684. }
  34685. };
  34686. Sound.prototype._updateSpatialParameters = function () {
  34687. if (this.spatialSound) {
  34688. if (this.useCustomAttenuation) {
  34689. // Tricks to disable in a way embedded Web Audio attenuation
  34690. this._soundPanner.distanceModel = "linear";
  34691. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34692. this._soundPanner.refDistance = 1;
  34693. this._soundPanner.rolloffFactor = 1;
  34694. this._soundPanner.panningModel = this._panningModel;
  34695. }
  34696. else {
  34697. this._soundPanner.distanceModel = this.distanceModel;
  34698. this._soundPanner.maxDistance = this.maxDistance;
  34699. this._soundPanner.refDistance = this.refDistance;
  34700. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34701. this._soundPanner.panningModel = this._panningModel;
  34702. }
  34703. }
  34704. };
  34705. Sound.prototype.switchPanningModelToHRTF = function () {
  34706. this._panningModel = "HRTF";
  34707. this._switchPanningModel();
  34708. };
  34709. Sound.prototype.switchPanningModelToEqualPower = function () {
  34710. this._panningModel = "equalpower";
  34711. this._switchPanningModel();
  34712. };
  34713. Sound.prototype._switchPanningModel = function () {
  34714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34715. this._soundPanner.panningModel = this._panningModel;
  34716. }
  34717. };
  34718. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34720. if (this._isOutputConnected) {
  34721. this._ouputAudioNode.disconnect();
  34722. }
  34723. this._ouputAudioNode.connect(soundTrackAudioNode);
  34724. this._isOutputConnected = true;
  34725. }
  34726. };
  34727. /**
  34728. * Transform this sound into a directional source
  34729. * @param coneInnerAngle Size of the inner cone in degree
  34730. * @param coneOuterAngle Size of the outer cone in degree
  34731. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34732. */
  34733. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34734. if (coneOuterAngle < coneInnerAngle) {
  34735. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34736. return;
  34737. }
  34738. this._coneInnerAngle = coneInnerAngle;
  34739. this._coneOuterAngle = coneOuterAngle;
  34740. this._coneOuterGain = coneOuterGain;
  34741. this._isDirectional = true;
  34742. if (this.isPlaying && this.loop) {
  34743. this.stop();
  34744. this.play();
  34745. }
  34746. };
  34747. Sound.prototype.setPosition = function (newPosition) {
  34748. this._position = newPosition;
  34749. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34750. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34751. }
  34752. };
  34753. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34754. this._localDirection = newLocalDirection;
  34755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34756. this._updateDirection();
  34757. }
  34758. };
  34759. Sound.prototype._updateDirection = function () {
  34760. var mat = this._connectedMesh.getWorldMatrix();
  34761. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34762. direction.normalize();
  34763. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34764. };
  34765. Sound.prototype.updateDistanceFromListener = function () {
  34766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34767. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34768. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34769. }
  34770. };
  34771. Sound.prototype.setAttenuationFunction = function (callback) {
  34772. this._customAttenuationFunction = callback;
  34773. };
  34774. /**
  34775. * Play the sound
  34776. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34777. * @param offset (optional) Start the sound setting it at a specific time
  34778. */
  34779. Sound.prototype.play = function (time, offset) {
  34780. var _this = this;
  34781. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34782. try {
  34783. if (this._startOffset < 0) {
  34784. time = -this._startOffset;
  34785. this._startOffset = 0;
  34786. }
  34787. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34788. if (!this._soundSource || !this._streamingSource) {
  34789. if (this.spatialSound) {
  34790. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34791. if (this._isDirectional) {
  34792. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34793. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34794. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34795. if (this._connectedMesh) {
  34796. this._updateDirection();
  34797. }
  34798. else {
  34799. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34800. }
  34801. }
  34802. }
  34803. }
  34804. if (this._streaming) {
  34805. if (!this._streamingSource) {
  34806. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34807. this._htmlAudioElement.onended = function () { _this._onended(); };
  34808. this._htmlAudioElement.playbackRate = this._playbackRate;
  34809. }
  34810. this._streamingSource.disconnect();
  34811. this._streamingSource.connect(this._inputAudioNode);
  34812. this._htmlAudioElement.play();
  34813. }
  34814. else {
  34815. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34816. this._soundSource.buffer = this._audioBuffer;
  34817. this._soundSource.connect(this._inputAudioNode);
  34818. this._soundSource.loop = this.loop;
  34819. this._soundSource.playbackRate.value = this._playbackRate;
  34820. this._soundSource.onended = function () { _this._onended(); };
  34821. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  34822. }
  34823. this._startTime = startTime;
  34824. this.isPlaying = true;
  34825. this.isPaused = false;
  34826. }
  34827. catch (ex) {
  34828. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34829. }
  34830. }
  34831. };
  34832. Sound.prototype._onended = function () {
  34833. this.isPlaying = false;
  34834. if (this.onended) {
  34835. this.onended();
  34836. }
  34837. };
  34838. /**
  34839. * Stop the sound
  34840. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34841. */
  34842. Sound.prototype.stop = function (time) {
  34843. if (this.isPlaying) {
  34844. if (this._streaming) {
  34845. this._htmlAudioElement.pause();
  34846. // Test needed for Firefox or it will generate an Invalid State Error
  34847. if (this._htmlAudioElement.currentTime > 0) {
  34848. this._htmlAudioElement.currentTime = 0;
  34849. }
  34850. }
  34851. else {
  34852. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34853. this._soundSource.stop(stopTime);
  34854. this._soundSource.onended = null;
  34855. if (!this.isPaused) {
  34856. this._startOffset = 0;
  34857. }
  34858. }
  34859. this.isPlaying = false;
  34860. }
  34861. };
  34862. Sound.prototype.pause = function () {
  34863. if (this.isPlaying) {
  34864. this.isPaused = true;
  34865. if (this._streaming) {
  34866. this._htmlAudioElement.pause();
  34867. }
  34868. else {
  34869. this.stop(0);
  34870. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34871. }
  34872. }
  34873. };
  34874. Sound.prototype.setVolume = function (newVolume, time) {
  34875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34876. if (time) {
  34877. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34878. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34879. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34880. }
  34881. else {
  34882. this._soundGain.gain.value = newVolume;
  34883. }
  34884. }
  34885. this._volume = newVolume;
  34886. };
  34887. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34888. this._playbackRate = newPlaybackRate;
  34889. if (this.isPlaying) {
  34890. if (this._streaming) {
  34891. this._htmlAudioElement.playbackRate = this._playbackRate;
  34892. }
  34893. else {
  34894. this._soundSource.playbackRate.value = this._playbackRate;
  34895. }
  34896. }
  34897. };
  34898. Sound.prototype.getVolume = function () {
  34899. return this._volume;
  34900. };
  34901. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34902. var _this = this;
  34903. if (this._connectedMesh) {
  34904. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34905. this._registerFunc = null;
  34906. }
  34907. this._connectedMesh = meshToConnectTo;
  34908. if (!this.spatialSound) {
  34909. this.spatialSound = true;
  34910. this._createSpatialParameters();
  34911. if (this.isPlaying && this.loop) {
  34912. this.stop();
  34913. this.play();
  34914. }
  34915. }
  34916. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34917. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34918. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34919. };
  34920. Sound.prototype.detachFromMesh = function () {
  34921. if (this._connectedMesh) {
  34922. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34923. this._registerFunc = null;
  34924. this._connectedMesh = null;
  34925. }
  34926. };
  34927. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34928. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34929. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34930. this._updateDirection();
  34931. }
  34932. };
  34933. Sound.prototype.clone = function () {
  34934. var _this = this;
  34935. if (!this._streaming) {
  34936. var setBufferAndRun = function () {
  34937. if (_this._isReadyToPlay) {
  34938. clonedSound._audioBuffer = _this.getAudioBuffer();
  34939. clonedSound._isReadyToPlay = true;
  34940. if (clonedSound.autoplay) {
  34941. clonedSound.play();
  34942. }
  34943. }
  34944. else {
  34945. window.setTimeout(setBufferAndRun, 300);
  34946. }
  34947. };
  34948. var currentOptions = {
  34949. autoplay: this.autoplay, loop: this.loop,
  34950. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34951. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34952. refDistance: this.refDistance, distanceModel: this.distanceModel
  34953. };
  34954. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34955. if (this.useCustomAttenuation) {
  34956. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34957. }
  34958. clonedSound.setPosition(this._position);
  34959. clonedSound.setPlaybackRate(this._playbackRate);
  34960. setBufferAndRun();
  34961. return clonedSound;
  34962. }
  34963. else {
  34964. return null;
  34965. }
  34966. };
  34967. Sound.prototype.getAudioBuffer = function () {
  34968. return this._audioBuffer;
  34969. };
  34970. Sound.prototype.serialize = function () {
  34971. var serializationObject = {
  34972. name: this.name,
  34973. url: this.name,
  34974. autoplay: this.autoplay,
  34975. loop: this.loop,
  34976. volume: this._volume,
  34977. spatialSound: this.spatialSound,
  34978. maxDistance: this.maxDistance,
  34979. rolloffFactor: this.rolloffFactor,
  34980. refDistance: this.refDistance,
  34981. distanceModel: this.distanceModel,
  34982. playbackRate: this._playbackRate,
  34983. panningModel: this._panningModel,
  34984. soundTrackId: this.soundTrackId
  34985. };
  34986. if (this.spatialSound) {
  34987. if (this._connectedMesh)
  34988. serializationObject.connectedMeshId = this._connectedMesh.id;
  34989. serializationObject.position = this._position.asArray();
  34990. serializationObject.refDistance = this.refDistance;
  34991. serializationObject.distanceModel = this.distanceModel;
  34992. serializationObject.isDirectional = this._isDirectional;
  34993. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  34994. serializationObject.coneInnerAngle = this._coneInnerAngle;
  34995. serializationObject.coneOuterAngle = this._coneOuterAngle;
  34996. serializationObject.coneOuterGain = this._coneOuterGain;
  34997. }
  34998. return serializationObject;
  34999. };
  35000. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35001. var soundName = parsedSound.name;
  35002. var soundUrl;
  35003. if (parsedSound.url) {
  35004. soundUrl = rootUrl + parsedSound.url;
  35005. }
  35006. else {
  35007. soundUrl = rootUrl + soundName;
  35008. }
  35009. var options = {
  35010. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35011. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35012. rolloffFactor: parsedSound.rolloffFactor,
  35013. refDistance: parsedSound.refDistance,
  35014. distanceModel: parsedSound.distanceModel,
  35015. playbackRate: parsedSound.playbackRate
  35016. };
  35017. var newSound;
  35018. if (!sourceSound) {
  35019. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35020. scene._addPendingData(newSound);
  35021. }
  35022. else {
  35023. var setBufferAndRun = function () {
  35024. if (sourceSound._isReadyToPlay) {
  35025. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35026. newSound._isReadyToPlay = true;
  35027. if (newSound.autoplay) {
  35028. newSound.play();
  35029. }
  35030. }
  35031. else {
  35032. window.setTimeout(setBufferAndRun, 300);
  35033. }
  35034. };
  35035. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35036. setBufferAndRun();
  35037. }
  35038. if (parsedSound.position) {
  35039. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35040. newSound.setPosition(soundPosition);
  35041. }
  35042. if (parsedSound.isDirectional) {
  35043. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35044. if (parsedSound.localDirectionToMesh) {
  35045. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35046. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35047. }
  35048. }
  35049. if (parsedSound.connectedMeshId) {
  35050. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35051. if (connectedMesh) {
  35052. newSound.attachToMesh(connectedMesh);
  35053. }
  35054. }
  35055. return newSound;
  35056. };
  35057. return Sound;
  35058. })();
  35059. BABYLON.Sound = Sound;
  35060. })(BABYLON || (BABYLON = {}));
  35061. var BABYLON;
  35062. (function (BABYLON) {
  35063. var SoundTrack = (function () {
  35064. function SoundTrack(scene, options) {
  35065. this.id = -1;
  35066. this._isMainTrack = false;
  35067. this._isInitialized = false;
  35068. this._scene = scene;
  35069. this.soundCollection = new Array();
  35070. this._options = options;
  35071. if (!this._isMainTrack) {
  35072. this._scene.soundTracks.push(this);
  35073. this.id = this._scene.soundTracks.length - 1;
  35074. }
  35075. }
  35076. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35077. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35078. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35079. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35080. if (this._options) {
  35081. if (this._options.volume) {
  35082. this._outputAudioNode.gain.value = this._options.volume;
  35083. }
  35084. if (this._options.mainTrack) {
  35085. this._isMainTrack = this._options.mainTrack;
  35086. }
  35087. }
  35088. this._isInitialized = true;
  35089. }
  35090. };
  35091. SoundTrack.prototype.dispose = function () {
  35092. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35093. if (this._connectedAnalyser) {
  35094. this._connectedAnalyser.stopDebugCanvas();
  35095. }
  35096. while (this.soundCollection.length) {
  35097. this.soundCollection[0].dispose();
  35098. }
  35099. if (this._outputAudioNode) {
  35100. this._outputAudioNode.disconnect();
  35101. }
  35102. this._outputAudioNode = null;
  35103. }
  35104. };
  35105. SoundTrack.prototype.AddSound = function (sound) {
  35106. if (!this._isInitialized) {
  35107. this._initializeSoundTrackAudioGraph();
  35108. }
  35109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35110. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35111. }
  35112. if (sound.soundTrackId) {
  35113. if (sound.soundTrackId === -1) {
  35114. this._scene.mainSoundTrack.RemoveSound(sound);
  35115. }
  35116. else {
  35117. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35118. }
  35119. }
  35120. this.soundCollection.push(sound);
  35121. sound.soundTrackId = this.id;
  35122. };
  35123. SoundTrack.prototype.RemoveSound = function (sound) {
  35124. var index = this.soundCollection.indexOf(sound);
  35125. if (index !== -1) {
  35126. this.soundCollection.splice(index, 1);
  35127. }
  35128. };
  35129. SoundTrack.prototype.setVolume = function (newVolume) {
  35130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35131. this._outputAudioNode.gain.value = newVolume;
  35132. }
  35133. };
  35134. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35136. for (var i = 0; i < this.soundCollection.length; i++) {
  35137. this.soundCollection[i].switchPanningModelToHRTF();
  35138. }
  35139. }
  35140. };
  35141. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35142. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35143. for (var i = 0; i < this.soundCollection.length; i++) {
  35144. this.soundCollection[i].switchPanningModelToEqualPower();
  35145. }
  35146. }
  35147. };
  35148. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35149. if (this._connectedAnalyser) {
  35150. this._connectedAnalyser.stopDebugCanvas();
  35151. }
  35152. this._connectedAnalyser = analyser;
  35153. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35154. this._outputAudioNode.disconnect();
  35155. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35156. }
  35157. };
  35158. return SoundTrack;
  35159. })();
  35160. BABYLON.SoundTrack = SoundTrack;
  35161. })(BABYLON || (BABYLON = {}));
  35162. var BABYLON;
  35163. (function (BABYLON) {
  35164. var SIMDVector3 = (function () {
  35165. function SIMDVector3() {
  35166. }
  35167. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  35168. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  35169. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35170. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35171. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35172. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35173. 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));
  35174. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35175. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35176. };
  35177. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  35178. var v0 = SIMD.float32x4.splat(x);
  35179. var v1 = SIMD.float32x4.splat(y);
  35180. var v2 = SIMD.float32x4.splat(z);
  35181. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35182. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35183. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35184. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35185. 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));
  35186. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35187. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35188. };
  35189. return SIMDVector3;
  35190. })();
  35191. BABYLON.SIMDVector3 = SIMDVector3;
  35192. var SIMDMatrix = (function () {
  35193. function SIMDMatrix() {
  35194. }
  35195. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  35196. if (offset === void 0) { offset = 0; }
  35197. var tm = this.m;
  35198. var om = other.m;
  35199. var om0 = SIMD.float32x4.load(om, 0);
  35200. var om1 = SIMD.float32x4.load(om, 4);
  35201. var om2 = SIMD.float32x4.load(om, 8);
  35202. var om3 = SIMD.float32x4.load(om, 12);
  35203. var tm0 = SIMD.float32x4.load(tm, 0);
  35204. 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)))));
  35205. var tm1 = SIMD.float32x4.load(tm, 4);
  35206. 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)))));
  35207. var tm2 = SIMD.float32x4.load(tm, 8);
  35208. 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)))));
  35209. var tm3 = SIMD.float32x4.load(tm, 12);
  35210. 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)))));
  35211. };
  35212. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  35213. var src = this.m;
  35214. var dest = other.m;
  35215. var row0, row1, row2, row3;
  35216. var tmp1;
  35217. var minor0, minor1, minor2, minor3;
  35218. var det;
  35219. // Load the 4 rows
  35220. var src0 = SIMD.float32x4.load(src, 0);
  35221. var src1 = SIMD.float32x4.load(src, 4);
  35222. var src2 = SIMD.float32x4.load(src, 8);
  35223. var src3 = SIMD.float32x4.load(src, 12);
  35224. // Transpose the source matrix. Sort of. Not a true transpose operation
  35225. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35226. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35227. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  35228. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  35229. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35230. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35231. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  35232. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  35233. // This is a true transposition, but it will lead to an incorrect result
  35234. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35235. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35236. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35237. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35238. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35239. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35240. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35241. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35242. // ----
  35243. tmp1 = SIMD.float32x4.mul(row2, row3);
  35244. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35245. minor0 = SIMD.float32x4.mul(row1, tmp1);
  35246. minor1 = SIMD.float32x4.mul(row0, tmp1);
  35247. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35248. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  35249. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  35250. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  35251. // ----
  35252. tmp1 = SIMD.float32x4.mul(row1, row2);
  35253. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35254. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  35255. minor3 = SIMD.float32x4.mul(row0, tmp1);
  35256. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35257. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  35258. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  35259. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  35260. // ----
  35261. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  35262. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35263. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  35264. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  35265. minor2 = SIMD.float32x4.mul(row0, tmp1);
  35266. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35267. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  35268. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  35269. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  35270. // ----
  35271. tmp1 = SIMD.float32x4.mul(row0, row1);
  35272. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35273. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  35274. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  35275. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35276. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  35277. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  35278. // ----
  35279. tmp1 = SIMD.float32x4.mul(row0, row3);
  35280. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35281. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  35282. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  35283. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35284. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  35285. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  35286. // ----
  35287. tmp1 = SIMD.float32x4.mul(row0, row2);
  35288. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35289. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  35290. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  35291. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35292. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  35293. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  35294. // Compute determinant
  35295. det = SIMD.float32x4.mul(row0, minor0);
  35296. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  35297. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  35298. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  35299. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  35300. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  35301. // These shuffles aren't necessary if the faulty transposition is done
  35302. // up at the top of this function.
  35303. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  35304. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  35305. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  35306. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  35307. // Compute final values by multiplying with 1/det
  35308. minor0 = SIMD.float32x4.mul(det, minor0);
  35309. minor1 = SIMD.float32x4.mul(det, minor1);
  35310. minor2 = SIMD.float32x4.mul(det, minor2);
  35311. minor3 = SIMD.float32x4.mul(det, minor3);
  35312. SIMD.float32x4.store(dest, 0, minor0);
  35313. SIMD.float32x4.store(dest, 4, minor1);
  35314. SIMD.float32x4.store(dest, 8, minor2);
  35315. SIMD.float32x4.store(dest, 12, minor3);
  35316. return this;
  35317. };
  35318. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  35319. var out = result.m;
  35320. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  35321. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  35322. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  35323. // cc.kmVec3Subtract(f, pCenter, pEye);
  35324. var f = SIMD.float32x4.sub(center, eye);
  35325. // cc.kmVec3Normalize(f, f);
  35326. var tmp = SIMD.float32x4.mul(f, f);
  35327. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35328. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35329. // cc.kmVec3Assign(up, pUp);
  35330. // cc.kmVec3Normalize(up, up);
  35331. tmp = SIMD.float32x4.mul(up, up);
  35332. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35333. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35334. // cc.kmVec3Cross(s, f, up);
  35335. 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)));
  35336. // cc.kmVec3Normalize(s, s);
  35337. tmp = SIMD.float32x4.mul(s, s);
  35338. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35339. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35340. // cc.kmVec3Cross(u, s, f);
  35341. 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)));
  35342. // cc.kmVec3Normalize(s, s);
  35343. tmp = SIMD.float32x4.mul(s, s);
  35344. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35345. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35346. var zero = SIMD.float32x4.splat(0.0);
  35347. s = SIMD.float32x4.neg(s);
  35348. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  35349. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  35350. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35351. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  35352. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  35353. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  35354. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35355. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  35356. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  35357. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  35358. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  35359. var b3 = SIMD.float32x4.neg(eye);
  35360. b3 = SIMD.float32x4.withW(b3, 1.0);
  35361. 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)))));
  35362. 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)))));
  35363. 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)))));
  35364. 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)))));
  35365. };
  35366. return SIMDMatrix;
  35367. })();
  35368. BABYLON.SIMDMatrix = SIMDMatrix;
  35369. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  35370. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  35371. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  35372. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  35373. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  35374. var SIMDHelper = (function () {
  35375. function SIMDHelper() {
  35376. }
  35377. Object.defineProperty(SIMDHelper, "IsEnabled", {
  35378. get: function () {
  35379. return SIMDHelper._isEnabled;
  35380. },
  35381. enumerable: true,
  35382. configurable: true
  35383. });
  35384. SIMDHelper.DisableSIMD = function () {
  35385. // Replace functions
  35386. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  35387. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  35388. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  35389. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  35390. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  35391. SIMDHelper._isEnabled = false;
  35392. };
  35393. SIMDHelper.EnableSIMD = function () {
  35394. if (window.SIMD === undefined) {
  35395. return;
  35396. }
  35397. // Replace functions
  35398. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  35399. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  35400. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  35401. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  35402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  35403. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  35404. get: function () { return this._data[0]; },
  35405. set: function (value) {
  35406. if (!this._data) {
  35407. this._data = new Float32Array(3);
  35408. }
  35409. this._data[0] = value;
  35410. }
  35411. });
  35412. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  35413. get: function () { return this._data[1]; },
  35414. set: function (value) {
  35415. this._data[1] = value;
  35416. }
  35417. });
  35418. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  35419. get: function () { return this._data[2]; },
  35420. set: function (value) {
  35421. this._data[2] = value;
  35422. }
  35423. });
  35424. SIMDHelper._isEnabled = true;
  35425. };
  35426. SIMDHelper._isEnabled = false;
  35427. return SIMDHelper;
  35428. })();
  35429. BABYLON.SIMDHelper = SIMDHelper;
  35430. })(BABYLON || (BABYLON = {}));
  35431. var BABYLON;
  35432. (function (BABYLON) {
  35433. /**
  35434. * This class describe a rectangle that were added to the map.
  35435. * You have access to its coordinates either in pixel or normalized (UV)
  35436. */
  35437. var PackedRect = (function () {
  35438. function PackedRect(root, parent, pos, size) {
  35439. this._pos = pos;
  35440. this._size = size;
  35441. this._root = root;
  35442. this._parent = parent;
  35443. }
  35444. Object.defineProperty(PackedRect.prototype, "pos", {
  35445. /**
  35446. * @returns the position of this node into the map
  35447. */
  35448. get: function () {
  35449. return this._pos;
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(PackedRect.prototype, "contentSize", {
  35455. /**
  35456. * @returns the size of the rectangle this node handles
  35457. */
  35458. get: function () {
  35459. return this._contentSize;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(PackedRect.prototype, "UVs", {
  35465. /**
  35466. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  35467. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  35468. */
  35469. get: function () {
  35470. return this.getUVsForCustomSize(this._root._size);
  35471. },
  35472. enumerable: true,
  35473. configurable: true
  35474. });
  35475. /**
  35476. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  35477. * This method will return the UVs for this part by given the custom size of what you really use
  35478. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  35479. */
  35480. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  35481. var mainWidth = this._root._size.width;
  35482. var mainHeight = this._root._size.height;
  35483. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  35484. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  35485. var uvs = new Array();
  35486. uvs.push(topLeft);
  35487. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  35488. uvs.push(rightBottom);
  35489. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  35490. return uvs;
  35491. };
  35492. /**
  35493. * Free this rectangle from the map.
  35494. * Call this method when you no longer need the rectangle to be in the map.
  35495. */
  35496. PackedRect.prototype.freeContent = function () {
  35497. if (!this.contentSize) {
  35498. return;
  35499. }
  35500. this._contentSize = null;
  35501. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  35502. this.attemptDefrag();
  35503. };
  35504. Object.defineProperty(PackedRect.prototype, "isUsed", {
  35505. get: function () {
  35506. return this._contentSize != null || this._leftNode != null;
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  35512. var node = this.findNode(contentSize);
  35513. // Not enough space...
  35514. if (!node) {
  35515. return null;
  35516. }
  35517. node.splitNode(contentSize);
  35518. return node;
  35519. };
  35520. PackedRect.prototype.findNode = function (size) {
  35521. var resNode = null;
  35522. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35523. if (this.isUsed) {
  35524. if (this._leftNode) {
  35525. resNode = this._leftNode.findNode(size);
  35526. }
  35527. if (!resNode && this._rightNode) {
  35528. resNode = this._rightNode.findNode(size);
  35529. }
  35530. if (!resNode && this._bottomNode) {
  35531. resNode = this._bottomNode.findNode(size);
  35532. }
  35533. }
  35534. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35535. resNode = this;
  35536. }
  35537. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35538. resNode = this;
  35539. }
  35540. return resNode;
  35541. };
  35542. PackedRect.prototype.splitNode = function (contentSize) {
  35543. // 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)
  35544. if (!this._contentSize && this._initialSize) {
  35545. 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));
  35546. return this._leftNode.splitNode(contentSize);
  35547. }
  35548. else {
  35549. this._contentSize = contentSize.clone();
  35550. this._initialSize = contentSize.clone();
  35551. if (contentSize.width !== this._size.width) {
  35552. 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));
  35553. }
  35554. if (contentSize.height !== this._size.height) {
  35555. 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));
  35556. }
  35557. return this;
  35558. }
  35559. };
  35560. PackedRect.prototype.attemptDefrag = function () {
  35561. if (!this.isUsed && this.isRecursiveFree) {
  35562. this.clearNode();
  35563. if (this._parent) {
  35564. this._parent.attemptDefrag();
  35565. }
  35566. }
  35567. };
  35568. PackedRect.prototype.clearNode = function () {
  35569. this._initialSize = null;
  35570. this._rightNode = null;
  35571. this._bottomNode = null;
  35572. };
  35573. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35574. get: function () {
  35575. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35576. },
  35577. enumerable: true,
  35578. configurable: true
  35579. });
  35580. PackedRect.prototype.evalFreeSize = function (size) {
  35581. var levelSize = 0;
  35582. if (!this.isUsed) {
  35583. if (this._initialSize) {
  35584. levelSize = this._initialSize.surface;
  35585. }
  35586. else {
  35587. levelSize = this._size.surface;
  35588. }
  35589. }
  35590. if (this._rightNode) {
  35591. levelSize += this._rightNode.evalFreeSize(0);
  35592. }
  35593. if (this._bottomNode) {
  35594. levelSize += this._bottomNode.evalFreeSize(0);
  35595. }
  35596. return levelSize + size;
  35597. };
  35598. return PackedRect;
  35599. })();
  35600. BABYLON.PackedRect = PackedRect;
  35601. /**
  35602. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35603. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35604. * 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.
  35605. */
  35606. var RectPackingMap = (function (_super) {
  35607. __extends(RectPackingMap, _super);
  35608. /**
  35609. * Create an instance of the object with a dimension using the given size
  35610. * @param size The dimension of the rectangle that will contain all the sub ones.
  35611. */
  35612. function RectPackingMap(size) {
  35613. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35614. this._root = this;
  35615. }
  35616. /**
  35617. * Add a rectangle, finding the best location to store it into the map
  35618. * @param size the dimension of the rectangle to store
  35619. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35620. */
  35621. RectPackingMap.prototype.addRect = function (size) {
  35622. var node = this.findAndSplitNode(size);
  35623. return node;
  35624. };
  35625. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35626. /**
  35627. * Return the current space free normalized between [0;1]
  35628. * @returns {}
  35629. */
  35630. get: function () {
  35631. var freeSize = 0;
  35632. freeSize = this.evalFreeSize(freeSize);
  35633. return freeSize / (this._size.width * this._size.height);
  35634. },
  35635. enumerable: true,
  35636. configurable: true
  35637. });
  35638. return RectPackingMap;
  35639. })(PackedRect);
  35640. BABYLON.RectPackingMap = RectPackingMap;
  35641. })(BABYLON || (BABYLON = {}));
  35642. var BABYLON;
  35643. (function (BABYLON) {
  35644. var DynamicFloatArrayElementInfo = (function () {
  35645. function DynamicFloatArrayElementInfo() {
  35646. }
  35647. return DynamicFloatArrayElementInfo;
  35648. })();
  35649. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35650. /**
  35651. * 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.
  35652. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35653. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35654. * 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.
  35655. * 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.
  35656. * 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".
  35657. */
  35658. var DynamicFloatArray = (function () {
  35659. /**
  35660. * Construct an instance of the dynamic float array
  35661. * @param stride size of one element in float (i.e. not bytes!)
  35662. * @param initialElementCount the number of available entries at construction
  35663. */
  35664. function DynamicFloatArray(stride, initialElementCount) {
  35665. this.compareValueOffset = null;
  35666. this.sortingAscending = true;
  35667. this._stride = stride;
  35668. this.buffer = new Float32Array(stride * initialElementCount);
  35669. this._lastUsed = 0;
  35670. this._firstFree = 0;
  35671. this._allEntries = new Array(initialElementCount);
  35672. this._freeEntries = new Array(initialElementCount);
  35673. for (var i = 0; i < initialElementCount; i++) {
  35674. var element = new DynamicFloatArrayElementInfo();
  35675. element.offset = i * stride;
  35676. this._allEntries[i] = element;
  35677. this._freeEntries[initialElementCount - i - 1] = element;
  35678. }
  35679. }
  35680. /**
  35681. * Allocate an element in the array.
  35682. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35683. * Beware, this offset may change when you call pack()
  35684. */
  35685. DynamicFloatArray.prototype.allocElement = function () {
  35686. if (this._freeEntries.length === 0) {
  35687. this._growBuffer();
  35688. }
  35689. var el = this._freeEntries.pop();
  35690. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35691. if (el.offset === this._firstFree) {
  35692. if (this._freeEntries.length > 0) {
  35693. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35694. }
  35695. else {
  35696. this._firstFree += this._stride;
  35697. }
  35698. }
  35699. return el;
  35700. };
  35701. /**
  35702. * Free the element corresponding to the given element info
  35703. * @param elInfo the element that describe the allocated element
  35704. */
  35705. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35706. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35707. this._freeEntries.push(elInfo);
  35708. };
  35709. /**
  35710. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35711. * 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().
  35712. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35713. */
  35714. DynamicFloatArray.prototype.pack = function () {
  35715. // no free slot? no need to pack
  35716. if (this._freeEntries.length === 0) {
  35717. return this.buffer;
  35718. }
  35719. // If the buffer is already packed the last used will always be lower than the first free
  35720. // 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.
  35721. if (this._lastUsed < this._firstFree) {
  35722. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35723. return elementsBuffer_1;
  35724. }
  35725. var s = this._stride;
  35726. // 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
  35727. var lastFree = new DynamicFloatArrayElementInfo();
  35728. lastFree.offset = this.totalElementCount * s;
  35729. this._freeEntries.push(lastFree);
  35730. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35731. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35732. var firstFreeSlotOffset = sortedFree[0].offset;
  35733. var freeZoneSize = 1;
  35734. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35735. var prevOffset = sortedFree[0].offset;
  35736. for (var i = 1; i < sortedFree.length; i++) {
  35737. // 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
  35738. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35739. break;
  35740. }
  35741. var curFree = sortedFree[i];
  35742. var curOffset = curFree.offset;
  35743. // Compute the distance between this offset and the previous
  35744. var distance = curOffset - prevOffset;
  35745. // If the distance is the stride size, they are adjacent, it good, move to the next
  35746. if (distance === s) {
  35747. // Free zone is one element bigger
  35748. ++freeZoneSize;
  35749. // as we're about to iterate to the next, the cur becomes the previous...
  35750. prevOffset = curOffset;
  35751. continue;
  35752. }
  35753. // Distance is bigger, which means there's x element between the previous free and this one
  35754. var usedRange = (distance / s) - 1;
  35755. // Two cases the free zone is smaller than the data to move or bigger
  35756. // Copy what can fit in the free zone
  35757. var curMoveOffset = curOffset - s;
  35758. var copyCount = Math.min(freeZoneSize, usedRange);
  35759. for (var j = 0; j < copyCount; j++) {
  35760. var freeI = firstFreeSlotOffset / s;
  35761. var curI = curMoveOffset / s;
  35762. var moveEl = sortedAll[curI];
  35763. this._moveElement(moveEl, firstFreeSlotOffset);
  35764. var replacedEl = sortedAll[freeI];
  35765. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35766. replacedEl.offset = curMoveOffset;
  35767. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35768. sortedAll[freeI] = moveEl;
  35769. sortedAll[curI] = replacedEl;
  35770. curMoveOffset -= s;
  35771. firstFreeSlotOffset += s;
  35772. }
  35773. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35774. if (freeZoneSize <= usedRange) {
  35775. firstFreeSlotOffset = curMoveOffset + s;
  35776. freeZoneSize = 1 + copyCount;
  35777. }
  35778. else {
  35779. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35780. }
  35781. // as we're about to iterate to the next, the cur becomes the previous...
  35782. prevOffset = curOffset;
  35783. }
  35784. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35785. this._lastUsed = firstFreeSlotOffset - s;
  35786. this._firstFree = firstFreeSlotOffset;
  35787. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35788. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35789. this._allEntries = sortedAll;
  35790. return elementsBuffer;
  35791. };
  35792. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35793. for (var i = 0; i < this._stride; i++) {
  35794. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35795. }
  35796. element.offset = destOffset;
  35797. };
  35798. DynamicFloatArray.prototype._growBuffer = function () {
  35799. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35800. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35801. var newBuffer = new Float32Array(newElCount * this._stride);
  35802. newBuffer.set(this.buffer);
  35803. var curCount = this.totalElementCount;
  35804. var addedCount = newElCount - this.totalElementCount;
  35805. for (var i = 0; i < addedCount; i++) {
  35806. var element = new DynamicFloatArrayElementInfo();
  35807. element.offset = (curCount + i) * this.stride;
  35808. this._allEntries.push(element);
  35809. this._freeEntries[addedCount - i - 1] = element;
  35810. }
  35811. this._firstFree = curCount * this.stride;
  35812. this.buffer = newBuffer;
  35813. };
  35814. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35815. /**
  35816. * Get the total count of entries that can fit in the current buffer
  35817. * @returns the elements count
  35818. */
  35819. get: function () {
  35820. return this._allEntries.length;
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35826. /**
  35827. * Get the count of free entries that can still be allocated without resizing the buffer
  35828. * @returns the free elements count
  35829. */
  35830. get: function () {
  35831. return this._freeEntries.length;
  35832. },
  35833. enumerable: true,
  35834. configurable: true
  35835. });
  35836. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  35837. /**
  35838. * Get the count of allocated elements
  35839. * @returns the allocated elements count
  35840. */
  35841. get: function () {
  35842. return this._allEntries.length - this._freeEntries.length;
  35843. },
  35844. enumerable: true,
  35845. configurable: true
  35846. });
  35847. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  35848. /**
  35849. * Return the size of one element in float
  35850. * @returns the size in float
  35851. */
  35852. get: function () {
  35853. return this._stride;
  35854. },
  35855. enumerable: true,
  35856. configurable: true
  35857. });
  35858. DynamicFloatArray.prototype.sort = function () {
  35859. var _this = this;
  35860. if (!this.compareValueOffset) {
  35861. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  35862. }
  35863. var count = this.usedElementCount;
  35864. // Do we have to (re)create the sort table?
  35865. if (!this._sortTable || this._sortTable.length < count) {
  35866. // 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...
  35867. var newCount = Math.min(this.totalElementCount, count * 2);
  35868. this._sortTable = new Array(newCount);
  35869. }
  35870. if (!this._sortTable || this._sortTable.length !== count) {
  35871. this._sortedTable = new Array(count);
  35872. }
  35873. // Because, you know...
  35874. this.pack();
  35875. //let stride = this.stride;
  35876. //for (let i = 0; i < count; i++) {
  35877. // let si = this._sortTable[i];
  35878. // if (!si) {
  35879. // si = new SortInfo();
  35880. // this._sortTable[i] = si;
  35881. // }
  35882. // si.entry = this._allEntries[i];
  35883. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  35884. // si.swapedOffset = null;
  35885. // this._sortedTable[i] = si;
  35886. //}
  35887. var curOffset = 0;
  35888. var stride = this.stride;
  35889. for (var i = 0; i < count; i++, curOffset += stride) {
  35890. var si = this._sortTable[i];
  35891. if (!si) {
  35892. si = new SortInfo();
  35893. this._sortTable[i] = si;
  35894. }
  35895. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  35896. si.offset = curOffset;
  35897. si.swapedOffset = null;
  35898. this._sortedTable[i] = si;
  35899. }
  35900. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  35901. if (this.sortingAscending) {
  35902. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  35903. }
  35904. else {
  35905. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  35906. }
  35907. var swapElements = function (src, dst) {
  35908. for (var i = 0; i < stride; i++) {
  35909. var tps = _this.buffer[dst + i];
  35910. _this.buffer[dst + i] = _this.buffer[src + i];
  35911. _this.buffer[src + i] = tps;
  35912. }
  35913. };
  35914. // 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:
  35915. // 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),
  35916. // and I still want something with a good algorithm complexity.
  35917. // 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,
  35918. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  35919. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  35920. // 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
  35921. // until we find a SortInfo object without a swapedOffset which means we got the right location
  35922. // 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
  35923. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  35924. for (var i = 0; i < count; i++) {
  35925. // Get the element to move
  35926. var sourceSI = this._sortedTable[i];
  35927. var destSI = this._sortTable[i];
  35928. var sourceOff = sourceSI.offset;
  35929. // If the source changed location, find the new one
  35930. if (sourceSI.swapedOffset) {
  35931. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  35932. var curSI = sourceSI;
  35933. while (curSI.swapedOffset) {
  35934. curSI = this._sortTable[curSI.swapedOffset / stride];
  35935. }
  35936. // Finally get the right location
  35937. sourceOff = curSI.offset;
  35938. }
  35939. // Tag the element being replaced with its new location
  35940. destSI.swapedOffset = sourceOff;
  35941. // Swap elements (only if needed)
  35942. if (sourceOff !== destSI.offset) {
  35943. swapElements(sourceOff, destSI.offset);
  35944. }
  35945. // Update the offset in the corresponding DFAE
  35946. //sourceSI.entry.offset = destSI.entry.offset;
  35947. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  35948. }
  35949. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35950. return true;
  35951. };
  35952. return DynamicFloatArray;
  35953. })();
  35954. BABYLON.DynamicFloatArray = DynamicFloatArray;
  35955. var SortInfo = (function () {
  35956. function SortInfo() {
  35957. this.compareData = this.offset = this.swapedOffset = null;
  35958. }
  35959. return SortInfo;
  35960. })();
  35961. })(BABYLON || (BABYLON = {}));
  35962. var BABYLON;
  35963. (function (BABYLON) {
  35964. /**
  35965. * This class given information about a given character.
  35966. */
  35967. var CharInfo = (function () {
  35968. function CharInfo() {
  35969. }
  35970. return CharInfo;
  35971. })();
  35972. BABYLON.CharInfo = CharInfo;
  35973. var FontTexture = (function (_super) {
  35974. __extends(FontTexture, _super);
  35975. /**
  35976. * Create a new instance of the FontTexture class
  35977. * @param name the name of the texture
  35978. * @param font the font to use, use the W3C CSS notation
  35979. * @param scene the scene that owns the texture
  35980. * @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
  35981. * @param samplingMode the texture sampling mode
  35982. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  35983. */
  35984. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  35985. if (maxCharCount === void 0) { maxCharCount = 200; }
  35986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35987. if (superSample === void 0) { superSample = false; }
  35988. _super.call(this, null, scene, true, false, samplingMode);
  35989. this._charInfos = {};
  35990. this._curCharCount = 0;
  35991. this._lastUpdateCharCount = -1;
  35992. this._usedCounter = 1;
  35993. this.name = name;
  35994. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35995. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35996. this._superSample = false;
  35997. if (superSample) {
  35998. var sfont = this.getSuperSampleFont(font);
  35999. if (sfont) {
  36000. this._superSample = true;
  36001. font = sfont;
  36002. }
  36003. }
  36004. // First canvas creation to determine the size of the texture to create
  36005. this._canvas = document.createElement("canvas");
  36006. this._context = this._canvas.getContext("2d");
  36007. this._context.font = font;
  36008. this._context.fillStyle = "white";
  36009. var res = this.getFontHeight(font);
  36010. this._lineHeightSuper = res.height;
  36011. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  36012. this._offset = res.offset - 1;
  36013. var maxCharWidth = this._context.measureText("W").width;
  36014. this._spaceWidthSuper = this._context.measureText(" ").width;
  36015. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  36016. // This is an approximate size, but should always be able to fit at least the maxCharCount
  36017. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  36018. var edge = Math.sqrt(totalEstSurface);
  36019. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  36020. // Create the texture that will store the font characters
  36021. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  36022. var textureSize = this.getSize();
  36023. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  36024. this._canvas = document.createElement("canvas");
  36025. this._canvas.width = textureSize.width;
  36026. this._canvas.height = textureSize.height;
  36027. this._context = this._canvas.getContext("2d");
  36028. this._context.textBaseline = "top";
  36029. this._context.font = font;
  36030. this._context.fillStyle = "white";
  36031. this._context.imageSmoothingEnabled = false;
  36032. this._currentFreePosition = BABYLON.Vector2.Zero();
  36033. // Add the basic ASCII based characters
  36034. for (var i = 0x20; i < 0x7F; i++) {
  36035. var c = String.fromCharCode(i);
  36036. this.getChar(c);
  36037. }
  36038. this.update();
  36039. }
  36040. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  36041. get: function () {
  36042. return this._superSample;
  36043. },
  36044. enumerable: true,
  36045. configurable: true
  36046. });
  36047. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  36048. get: function () {
  36049. return this._spaceWidth;
  36050. },
  36051. enumerable: true,
  36052. configurable: true
  36053. });
  36054. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36055. get: function () {
  36056. return this._lineHeight;
  36057. },
  36058. enumerable: true,
  36059. configurable: true
  36060. });
  36061. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36062. if (supersample === void 0) { supersample = false; }
  36063. var s = scene;
  36064. if (!s.__fontTextureCache__) {
  36065. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36066. }
  36067. var dic = s.__fontTextureCache__;
  36068. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36069. var ft = dic.get(lfn);
  36070. if (ft) {
  36071. ++ft._usedCounter;
  36072. return ft;
  36073. }
  36074. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36075. dic.add(lfn, ft);
  36076. return ft;
  36077. };
  36078. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36079. if (supersample === void 0) { supersample = false; }
  36080. var s = scene;
  36081. var dic = s.__fontTextureCache__;
  36082. if (!dic) {
  36083. return;
  36084. }
  36085. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36086. var font = dic.get(lfn);
  36087. if (--font._usedCounter === 0) {
  36088. dic.remove(lfn);
  36089. font.dispose();
  36090. }
  36091. };
  36092. /**
  36093. * Make sure the given char is present in the font map.
  36094. * @param char the character to get or add
  36095. * @return the CharInfo instance corresponding to the given character
  36096. */
  36097. FontTexture.prototype.getChar = function (char) {
  36098. if (char.length !== 1) {
  36099. return null;
  36100. }
  36101. var info = this._charInfos[char];
  36102. if (info) {
  36103. return info;
  36104. }
  36105. info = new CharInfo();
  36106. var measure = this._context.measureText(char);
  36107. var textureSize = this.getSize();
  36108. // we reached the end of the current line?
  36109. var width = Math.round(measure.width);
  36110. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  36111. var yMargin = xMargin;
  36112. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  36113. this._currentFreePosition.x = 0;
  36114. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  36115. // No more room?
  36116. if (this._currentFreePosition.y > textureSize.height) {
  36117. return this.getChar("!");
  36118. }
  36119. }
  36120. // Draw the character in the texture
  36121. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  36122. // Fill the CharInfo object
  36123. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  36124. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  36125. info.charWidth = this._superSample ? (width / 2) : width;
  36126. // Add the info structure
  36127. this._charInfos[char] = info;
  36128. this._curCharCount++;
  36129. // Set the next position
  36130. this._currentFreePosition.x += width + xMargin;
  36131. return info;
  36132. };
  36133. FontTexture.prototype.measureText = function (text, tabulationSize) {
  36134. if (tabulationSize === void 0) { tabulationSize = 4; }
  36135. var maxWidth = 0;
  36136. var curWidth = 0;
  36137. var lineCount = 1;
  36138. var charxpos = 0;
  36139. // Parse each char of the string
  36140. for (var _i = 0; _i < text.length; _i++) {
  36141. var char = text[_i];
  36142. // Next line feed?
  36143. if (char === "\n") {
  36144. maxWidth = Math.max(maxWidth, curWidth);
  36145. charxpos = 0;
  36146. curWidth = 0;
  36147. ++lineCount;
  36148. continue;
  36149. }
  36150. // Tabulation ?
  36151. if (char === "\t") {
  36152. var nextPos = charxpos + tabulationSize;
  36153. nextPos = nextPos - (nextPos % tabulationSize);
  36154. curWidth += (nextPos - charxpos) * this.spaceWidth;
  36155. charxpos = nextPos;
  36156. continue;
  36157. }
  36158. if (char < " ") {
  36159. continue;
  36160. }
  36161. curWidth += this.getChar(char).charWidth;
  36162. ++charxpos;
  36163. }
  36164. maxWidth = Math.max(maxWidth, curWidth);
  36165. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  36166. };
  36167. FontTexture.prototype.getSuperSampleFont = function (font) {
  36168. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  36169. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  36170. var res = font.toLocaleLowerCase().match(regex);
  36171. if (res == null) {
  36172. return null;
  36173. }
  36174. var size = parseInt(res[4]);
  36175. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  36176. var newFont = "";
  36177. for (var j = 1; j < res.length; j++) {
  36178. if (res[j] != null) {
  36179. newFont += res[j] + " ";
  36180. }
  36181. }
  36182. return newFont;
  36183. };
  36184. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  36185. FontTexture.prototype.getFontHeight = function (font) {
  36186. var fontDraw = document.createElement("canvas");
  36187. var ctx = fontDraw.getContext('2d');
  36188. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  36189. ctx.textBaseline = 'top';
  36190. ctx.fillStyle = 'white';
  36191. ctx.font = font;
  36192. ctx.fillText('jH|', 0, 0);
  36193. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  36194. var start = -1;
  36195. var end = -1;
  36196. for (var row = 0; row < fontDraw.height; row++) {
  36197. for (var column = 0; column < fontDraw.width; column++) {
  36198. var index = (row * fontDraw.width + column) * 4;
  36199. if (pixels[index] === 0) {
  36200. if (column === fontDraw.width - 1 && start !== -1) {
  36201. end = row;
  36202. row = fontDraw.height;
  36203. break;
  36204. }
  36205. continue;
  36206. }
  36207. else {
  36208. if (start === -1) {
  36209. start = row;
  36210. }
  36211. break;
  36212. }
  36213. }
  36214. }
  36215. return { height: (end - start) + 1, offset: start - 1 };
  36216. };
  36217. Object.defineProperty(FontTexture.prototype, "canRescale", {
  36218. get: function () {
  36219. return false;
  36220. },
  36221. enumerable: true,
  36222. configurable: true
  36223. });
  36224. FontTexture.prototype.getContext = function () {
  36225. return this._context;
  36226. };
  36227. /**
  36228. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  36229. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  36230. */
  36231. FontTexture.prototype.update = function () {
  36232. // Update only if there's new char added since the previous update
  36233. if (this._lastUpdateCharCount < this._curCharCount) {
  36234. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  36235. this._lastUpdateCharCount = this._curCharCount;
  36236. }
  36237. };
  36238. // cloning should be prohibited, there's no point to duplicate this texture at all
  36239. FontTexture.prototype.clone = function () {
  36240. return null;
  36241. };
  36242. return FontTexture;
  36243. })(BABYLON.Texture);
  36244. BABYLON.FontTexture = FontTexture;
  36245. })(BABYLON || (BABYLON = {}));
  36246. var BABYLON;
  36247. (function (BABYLON) {
  36248. var MapTexture = (function (_super) {
  36249. __extends(MapTexture, _super);
  36250. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  36251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36252. if (useMipMap === void 0) { useMipMap = false; }
  36253. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  36254. this.name = name;
  36255. this._size = size;
  36256. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36257. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36258. // Create the rectPackMap that will allocate portion of the texture
  36259. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  36260. // Create the texture that will store the content
  36261. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  36262. }
  36263. /**
  36264. * Allocate a rectangle of a given size in the texture map
  36265. * @param size the size of the rectangle to allocation
  36266. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  36267. */
  36268. MapTexture.prototype.allocateRect = function (size) {
  36269. return this._rectPackingMap.addRect(size);
  36270. };
  36271. /**
  36272. * Free a given rectangle from the texture map
  36273. * @param rectInfo the instance corresponding to the rect to free.
  36274. */
  36275. MapTexture.prototype.freeRect = function (rectInfo) {
  36276. if (rectInfo) {
  36277. rectInfo.freeContent();
  36278. }
  36279. };
  36280. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  36281. /**
  36282. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  36283. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  36284. * @returns {}
  36285. */
  36286. get: function () {
  36287. return this._rectPackingMap.freeSpace;
  36288. },
  36289. enumerable: true,
  36290. configurable: true
  36291. });
  36292. /**
  36293. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  36294. * 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.
  36295. * Don't forget to call unbindTexture when you're done rendering
  36296. * @param rect the zone to render to
  36297. * @param clear true to clear the portion's color/depth data
  36298. */
  36299. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  36300. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  36301. };
  36302. /**
  36303. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  36304. * 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.
  36305. * Don't forget to call unbindTexture when you're done rendering
  36306. * @param pos the position into the texture
  36307. * @param size the portion to fit the clip space to
  36308. * @param clear true to clear the portion's color/depth data
  36309. */
  36310. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  36311. var engine = this.getScene().getEngine();
  36312. engine.bindFramebuffer(this._texture);
  36313. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  36314. if (clear) {
  36315. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  36316. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  36317. }
  36318. };
  36319. /**
  36320. * Unbind the texture map from the rendering engine.
  36321. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  36322. * @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.
  36323. */
  36324. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  36325. // Dump ?
  36326. if (dumpForDebug) {
  36327. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  36328. }
  36329. var engine = this.getScene().getEngine();
  36330. if (this._replacedViewport) {
  36331. engine.setViewport(this._replacedViewport);
  36332. this._replacedViewport = null;
  36333. }
  36334. engine.unBindFramebuffer(this._texture);
  36335. };
  36336. Object.defineProperty(MapTexture.prototype, "canRescale", {
  36337. get: function () {
  36338. return false;
  36339. },
  36340. enumerable: true,
  36341. configurable: true
  36342. });
  36343. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  36344. // Anyway, there's not much point to use this method for this kind of texture I guess
  36345. MapTexture.prototype.clone = function () {
  36346. return null;
  36347. };
  36348. return MapTexture;
  36349. })(BABYLON.Texture);
  36350. BABYLON.MapTexture = MapTexture;
  36351. })(BABYLON || (BABYLON = {}));
  36352. var BABYLON;
  36353. (function (BABYLON) {
  36354. /**
  36355. * Stores 2D Bounding Information.
  36356. * This class handles a circle area and a bounding rectangle one.
  36357. */
  36358. var BoundingInfo2D = (function () {
  36359. function BoundingInfo2D() {
  36360. this.radius = 0;
  36361. this.center = BABYLON.Vector2.Zero();
  36362. this.extent = BABYLON.Vector2.Zero();
  36363. }
  36364. /**
  36365. * Create a BoundingInfo2D object from a given size
  36366. * @param size the size that will be used to set the extend, radius will be computed from it.
  36367. */
  36368. BoundingInfo2D.CreateFromSize = function (size) {
  36369. var r = new BoundingInfo2D();
  36370. BoundingInfo2D.CreateFromSizeToRef(size, r);
  36371. return r;
  36372. };
  36373. /**
  36374. * Create a BoundingInfo2D object from a given radius
  36375. * @param radius the radius to use, the extent will be computed from it.
  36376. */
  36377. BoundingInfo2D.CreateFromRadius = function (radius) {
  36378. var r = new BoundingInfo2D();
  36379. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  36380. return r;
  36381. };
  36382. /**
  36383. * Create a BoundingInfo2D object from a list of points.
  36384. * The resulted object will be the smallest bounding area that includes all the given points.
  36385. * @param points an array of points to compute the bounding object from.
  36386. */
  36387. BoundingInfo2D.CreateFromPoints = function (points) {
  36388. var r = new BoundingInfo2D();
  36389. BoundingInfo2D.CreateFromPointsToRef(points, r);
  36390. return r;
  36391. };
  36392. /**
  36393. * Update a BoundingInfo2D object using the given Size as input
  36394. * @param size the bounding data will be computed from this size.
  36395. * @param b must be a valid/allocated object, it will contain the result of the operation
  36396. */
  36397. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  36398. if (!size) {
  36399. size = BABYLON.Size.Zero();
  36400. }
  36401. b.center.x = +size.width / 2;
  36402. b.center.y = +size.height / 2;
  36403. b.extent.x = b.center.x;
  36404. b.extent.y = b.center.y;
  36405. b.radius = b.extent.length();
  36406. };
  36407. /**
  36408. * Update a BoundingInfo2D object using the given radius as input
  36409. * @param radius the bounding data will be computed from this radius
  36410. * @param b must be a valid/allocated object, it will contain the result of the operation
  36411. */
  36412. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  36413. b.center.x = b.center.y = 0;
  36414. var r = +radius;
  36415. b.extent.x = r;
  36416. b.extent.y = r;
  36417. b.radius = r;
  36418. };
  36419. /**
  36420. * Update a BoundingInfo2D object using the given points array as input
  36421. * @param points the point array to use to update the bounding data
  36422. * @param b must be a valid/allocated object, it will contain the result of the operation
  36423. */
  36424. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  36425. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  36426. for (var _i = 0; _i < points.length; _i++) {
  36427. var p = points[_i];
  36428. xmin = Math.min(p.x, xmin);
  36429. xmax = Math.max(p.x, xmax);
  36430. ymin = Math.min(p.y, ymin);
  36431. ymax = Math.max(p.y, ymax);
  36432. }
  36433. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  36434. };
  36435. /**
  36436. * Update a BoundingInfo2D object using the given min/max values as input
  36437. * @param xmin the smallest x coordinate
  36438. * @param xmax the biggest x coordinate
  36439. * @param ymin the smallest y coordinate
  36440. * @param ymax the buggest y coordinate
  36441. * @param b must be a valid/allocated object, it will contain the result of the operation
  36442. */
  36443. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  36444. var w = xmax - xmin;
  36445. var h = ymax - ymin;
  36446. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  36447. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  36448. b.radius = b.extent.length();
  36449. };
  36450. /**
  36451. * Duplicate this instance and return a new one
  36452. * @return the duplicated instance
  36453. */
  36454. BoundingInfo2D.prototype.clone = function () {
  36455. var r = new BoundingInfo2D();
  36456. r.center = this.center.clone();
  36457. r.radius = this.radius;
  36458. r.extent = this.extent.clone();
  36459. return r;
  36460. };
  36461. BoundingInfo2D.prototype.clear = function () {
  36462. this.center.copyFromFloats(0, 0);
  36463. this.radius = 0;
  36464. this.extent.copyFromFloats(0, 0);
  36465. };
  36466. BoundingInfo2D.prototype.copyFrom = function (src) {
  36467. this.center.copyFrom(src.center);
  36468. this.radius = src.radius;
  36469. this.extent.copyFrom(src.extent);
  36470. };
  36471. /**
  36472. * return the max extend of the bounding info
  36473. */
  36474. BoundingInfo2D.prototype.max = function () {
  36475. var r = BABYLON.Vector2.Zero();
  36476. this.maxToRef(r);
  36477. return r;
  36478. };
  36479. /**
  36480. * Update a vector2 with the max extend of the bounding info
  36481. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  36482. */
  36483. BoundingInfo2D.prototype.maxToRef = function (result) {
  36484. result.x = this.center.x + this.extent.x;
  36485. result.y = this.center.y + this.extent.y;
  36486. };
  36487. /**
  36488. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  36489. * @param matrix the transformation matrix to apply
  36490. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  36491. */
  36492. BoundingInfo2D.prototype.transform = function (matrix) {
  36493. var r = new BoundingInfo2D();
  36494. this.transformToRef(matrix, r);
  36495. return r;
  36496. };
  36497. /**
  36498. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  36499. * @param other the second BoundingInfo2D to compute the union with this one
  36500. * @return a new instance containing the result of the union
  36501. */
  36502. BoundingInfo2D.prototype.union = function (other) {
  36503. var r = new BoundingInfo2D();
  36504. this.unionToRef(other, r);
  36505. return r;
  36506. };
  36507. /**
  36508. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  36509. * 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.
  36510. * @param matrix The matrix to use to compute the transformation
  36511. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  36512. */
  36513. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  36514. // Construct a bounding box based on the extent values
  36515. var p = BoundingInfo2D._transform;
  36516. p[0].x = this.center.x + this.extent.x;
  36517. p[0].y = this.center.y + this.extent.y;
  36518. p[1].x = this.center.x + this.extent.x;
  36519. p[1].y = this.center.y - this.extent.y;
  36520. p[2].x = this.center.x - this.extent.x;
  36521. p[2].y = this.center.y - this.extent.y;
  36522. p[3].x = this.center.x - this.extent.x;
  36523. p[3].y = this.center.y + this.extent.y;
  36524. // Transform the four points of the bounding box with the matrix
  36525. for (var i = 0; i < 4; i++) {
  36526. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  36527. }
  36528. BoundingInfo2D.CreateFromPointsToRef(p, result);
  36529. };
  36530. /**
  36531. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  36532. * 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.
  36533. * @param other the second object used to compute the union
  36534. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  36535. */
  36536. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  36537. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  36538. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  36539. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  36540. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  36541. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  36542. };
  36543. /**
  36544. * Check if the given point is inside the BoundingInfo.
  36545. * The test is first made on the radius, then inside the rectangle described by the extent
  36546. * @param pickPosition the position to test
  36547. * @return true if the point is inside, false otherwise
  36548. */
  36549. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  36550. // is it inside the radius?
  36551. var pickLocal = pickPosition.subtract(this.center);
  36552. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  36553. // is it inside the rectangle?
  36554. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  36555. }
  36556. return false;
  36557. };
  36558. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  36559. return BoundingInfo2D;
  36560. })();
  36561. BABYLON.BoundingInfo2D = BoundingInfo2D;
  36562. })(BABYLON || (BABYLON = {}));
  36563. var BABYLON;
  36564. (function (BABYLON) {
  36565. /**
  36566. * Base class implementing the ILocable interface.
  36567. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36568. */
  36569. var LockableBase = (function () {
  36570. function LockableBase() {
  36571. }
  36572. LockableBase.prototype.isLocked = function () {
  36573. return this._isLocked;
  36574. };
  36575. LockableBase.prototype.lock = function () {
  36576. if (this._isLocked) {
  36577. return true;
  36578. }
  36579. this.onLock();
  36580. this._isLocked = true;
  36581. return false;
  36582. };
  36583. /**
  36584. * Protected handler that will be called when the instance is about to be locked.
  36585. */
  36586. LockableBase.prototype.onLock = function () {
  36587. };
  36588. return LockableBase;
  36589. })();
  36590. BABYLON.LockableBase = LockableBase;
  36591. var SolidColorBrush2D = (function (_super) {
  36592. __extends(SolidColorBrush2D, _super);
  36593. function SolidColorBrush2D(color, lock) {
  36594. if (lock === void 0) { lock = false; }
  36595. _super.call(this);
  36596. this._color = color;
  36597. if (lock) {
  36598. {
  36599. this.lock();
  36600. }
  36601. }
  36602. }
  36603. /**
  36604. * Return true if the brush is transparent, false if it's totally opaque
  36605. */
  36606. SolidColorBrush2D.prototype.isTransparent = function () {
  36607. return this._color && this._color.a < 1.0;
  36608. };
  36609. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36610. /**
  36611. * The color used by this instance to render
  36612. * @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.
  36613. */
  36614. get: function () {
  36615. return this._color;
  36616. },
  36617. set: function (value) {
  36618. if (this.isLocked()) {
  36619. return;
  36620. }
  36621. this._color = value;
  36622. },
  36623. enumerable: true,
  36624. configurable: true
  36625. });
  36626. /**
  36627. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36628. */
  36629. SolidColorBrush2D.prototype.toString = function () {
  36630. return this._color.toHexString();
  36631. };
  36632. SolidColorBrush2D = __decorate([
  36633. BABYLON.className("SolidColorBrush2D")
  36634. ], SolidColorBrush2D);
  36635. return SolidColorBrush2D;
  36636. })(LockableBase);
  36637. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36638. var GradientColorBrush2D = (function (_super) {
  36639. __extends(GradientColorBrush2D, _super);
  36640. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36641. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36642. if (rotation === void 0) { rotation = 0; }
  36643. if (scale === void 0) { scale = 1; }
  36644. if (lock === void 0) { lock = false; }
  36645. _super.call(this);
  36646. this._color1 = color1;
  36647. this._color2 = color2;
  36648. this._translation = translation;
  36649. this._rotation = rotation;
  36650. this._scale = scale;
  36651. if (lock) {
  36652. this.lock();
  36653. }
  36654. }
  36655. /**
  36656. * Return true if the brush is transparent, false if it's totally opaque
  36657. */
  36658. GradientColorBrush2D.prototype.isTransparent = function () {
  36659. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36660. };
  36661. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36662. /**
  36663. * First color, the blend will start from this color
  36664. */
  36665. get: function () {
  36666. return this._color1;
  36667. },
  36668. set: function (value) {
  36669. if (this.isLocked()) {
  36670. return;
  36671. }
  36672. this._color1 = value;
  36673. },
  36674. enumerable: true,
  36675. configurable: true
  36676. });
  36677. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36678. /**
  36679. * Second color, the blend will end to this color
  36680. */
  36681. get: function () {
  36682. return this._color2;
  36683. },
  36684. set: function (value) {
  36685. if (this.isLocked()) {
  36686. return;
  36687. }
  36688. this._color2 = value;
  36689. },
  36690. enumerable: true,
  36691. configurable: true
  36692. });
  36693. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36694. /**
  36695. * Translation vector to apply on the blend
  36696. * Default is [0;0]
  36697. */
  36698. get: function () {
  36699. return this._translation;
  36700. },
  36701. set: function (value) {
  36702. if (this.isLocked()) {
  36703. return;
  36704. }
  36705. this._translation = value;
  36706. },
  36707. enumerable: true,
  36708. configurable: true
  36709. });
  36710. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  36711. /**
  36712. * Rotation in radian to apply to the brush
  36713. * Default direction of the brush is vertical, you can change this using this property.
  36714. * Default is 0.
  36715. */
  36716. get: function () {
  36717. return this._rotation;
  36718. },
  36719. set: function (value) {
  36720. if (this.isLocked()) {
  36721. return;
  36722. }
  36723. this._rotation = value;
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  36729. /**
  36730. * Scale factor to apply to the gradient.
  36731. * Default is 1: no scale.
  36732. */
  36733. get: function () {
  36734. return this._scale;
  36735. },
  36736. set: function (value) {
  36737. if (this.isLocked()) {
  36738. return;
  36739. }
  36740. this._scale = value;
  36741. },
  36742. enumerable: true,
  36743. configurable: true
  36744. });
  36745. /**
  36746. * Return a string describing the brush
  36747. */
  36748. GradientColorBrush2D.prototype.toString = function () {
  36749. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  36750. };
  36751. /**
  36752. * Build a unique key string for the given parameters
  36753. */
  36754. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  36755. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  36756. };
  36757. GradientColorBrush2D = __decorate([
  36758. BABYLON.className("GradientColorBrush2D")
  36759. ], GradientColorBrush2D);
  36760. return GradientColorBrush2D;
  36761. })(LockableBase);
  36762. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  36763. })(BABYLON || (BABYLON = {}));
  36764. var BABYLON;
  36765. (function (BABYLON) {
  36766. var Prim2DClassInfo = (function () {
  36767. function Prim2DClassInfo() {
  36768. }
  36769. return Prim2DClassInfo;
  36770. })();
  36771. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  36772. var Prim2DPropInfo = (function () {
  36773. function Prim2DPropInfo() {
  36774. }
  36775. Prim2DPropInfo.PROPKIND_MODEL = 1;
  36776. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  36777. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  36778. return Prim2DPropInfo;
  36779. })();
  36780. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  36781. /**
  36782. * Custom type of the propertyChanged observable
  36783. */
  36784. var PropertyChangedInfo = (function () {
  36785. function PropertyChangedInfo() {
  36786. }
  36787. return PropertyChangedInfo;
  36788. })();
  36789. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  36790. var ClassTreeInfo = (function () {
  36791. function ClassTreeInfo(baseClass, type, classContentFactory) {
  36792. this._baseClass = baseClass;
  36793. this._type = type;
  36794. this._subClasses = new Array();
  36795. this._levelContent = new BABYLON.StringDictionary();
  36796. this._classContentFactory = classContentFactory;
  36797. }
  36798. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  36799. get: function () {
  36800. if (!this._classContent) {
  36801. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  36802. }
  36803. return this._classContent;
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  36809. get: function () {
  36810. return this._type;
  36811. },
  36812. enumerable: true,
  36813. configurable: true
  36814. });
  36815. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  36816. get: function () {
  36817. return this._levelContent;
  36818. },
  36819. enumerable: true,
  36820. configurable: true
  36821. });
  36822. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  36823. get: function () {
  36824. if (!this._fullContent) {
  36825. var dic = new BABYLON.StringDictionary();
  36826. var curLevel = this;
  36827. while (curLevel) {
  36828. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  36829. curLevel = curLevel._baseClass;
  36830. }
  36831. this._fullContent = dic;
  36832. }
  36833. return this._fullContent;
  36834. },
  36835. enumerable: true,
  36836. configurable: true
  36837. });
  36838. ClassTreeInfo.prototype.getLevelOf = function (type) {
  36839. // Are we already there?
  36840. if (type === this._type) {
  36841. return this;
  36842. }
  36843. var baseProto = Object.getPrototypeOf(type);
  36844. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  36845. if (!curProtoContent) {
  36846. this.getLevelOf(baseProto);
  36847. }
  36848. return this.getOrAddType(baseProto, type);
  36849. };
  36850. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  36851. // Are we at the level corresponding to the baseType?
  36852. // If so, get or add the level we're looking for
  36853. if (baseType === this._type) {
  36854. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  36855. var subType = _a[_i];
  36856. if (subType.type === type) {
  36857. return subType.node;
  36858. }
  36859. }
  36860. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  36861. var info = { type: type, node: node };
  36862. this._subClasses.push(info);
  36863. return info.node;
  36864. }
  36865. // Recurse down to keep looking for the node corresponding to the baseTypeName
  36866. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  36867. var subType = _c[_b];
  36868. var info = subType.node.getOrAddType(baseType, type);
  36869. if (info) {
  36870. return info;
  36871. }
  36872. }
  36873. return null;
  36874. };
  36875. ClassTreeInfo.get = function (type) {
  36876. var dic = type["__classTreeInfo"];
  36877. if (!dic) {
  36878. return null;
  36879. }
  36880. return dic.getLevelOf(type);
  36881. };
  36882. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  36883. var dic = type["__classTreeInfo"];
  36884. if (!dic) {
  36885. dic = new ClassTreeInfo(null, type, classContentFactory);
  36886. type["__classTreeInfo"] = dic;
  36887. }
  36888. return dic;
  36889. };
  36890. return ClassTreeInfo;
  36891. })();
  36892. BABYLON.ClassTreeInfo = ClassTreeInfo;
  36893. var SmartPropertyPrim = (function () {
  36894. function SmartPropertyPrim() {
  36895. this._flags = 0;
  36896. this._modelKey = null;
  36897. this._instanceDirtyFlags = 0;
  36898. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  36899. this.animations = new Array();
  36900. }
  36901. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  36902. /**
  36903. * Check if the object is disposed or not.
  36904. * @returns true if the object is dispose, false otherwise.
  36905. */
  36906. get: function () {
  36907. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  36908. },
  36909. enumerable: true,
  36910. configurable: true
  36911. });
  36912. /**
  36913. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  36914. * @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.
  36915. */
  36916. SmartPropertyPrim.prototype.dispose = function () {
  36917. if (this.isDisposed) {
  36918. return false;
  36919. }
  36920. // Don't set to null, it may upset somebody...
  36921. this.animations.splice(0);
  36922. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  36923. return true;
  36924. };
  36925. /**
  36926. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  36927. * Look at Sprite2D for more information
  36928. */
  36929. SmartPropertyPrim.prototype.getAnimatables = function () {
  36930. return new Array();
  36931. };
  36932. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  36933. /**
  36934. * Property giving the Model Key associated to the property.
  36935. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  36936. * @returns the model key string.
  36937. */
  36938. get: function () {
  36939. var _this = this;
  36940. // No need to compute it?
  36941. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  36942. return this._modelKey;
  36943. }
  36944. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  36945. var propDic = this.propDic;
  36946. propDic.forEach(function (k, v) {
  36947. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36948. var propVal = _this[v.name];
  36949. // 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
  36950. if (propVal && propVal.constructor === Array) {
  36951. var firstVal = propVal[0];
  36952. if (!firstVal) {
  36953. propVal = 0;
  36954. }
  36955. else {
  36956. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  36957. }
  36958. }
  36959. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  36960. }
  36961. });
  36962. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  36963. this._modelKey = modelKey;
  36964. return modelKey;
  36965. },
  36966. enumerable: true,
  36967. configurable: true
  36968. });
  36969. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  36970. /**
  36971. * States if the Primitive is dirty and should be rendered again next time.
  36972. * @returns true is dirty, false otherwise
  36973. */
  36974. get: function () {
  36975. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  36976. },
  36977. enumerable: true,
  36978. configurable: true
  36979. });
  36980. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  36981. /**
  36982. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  36983. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  36984. */
  36985. get: function () {
  36986. if (!this._propInfo) {
  36987. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  36988. if (!cti) {
  36989. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  36990. }
  36991. this._propInfo = cti.fullContent;
  36992. }
  36993. return this._propInfo;
  36994. },
  36995. enumerable: true,
  36996. configurable: true
  36997. });
  36998. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  36999. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  37000. var node = dic.getLevelOf(target);
  37001. var propInfo = node.levelContent.get(propId.toString());
  37002. if (propInfo) {
  37003. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  37004. }
  37005. // Create, setup and add the PropInfo object to our prop dictionary
  37006. propInfo = new Prim2DPropInfo();
  37007. propInfo.id = propId;
  37008. propInfo.flagId = Math.pow(2, propId);
  37009. propInfo.kind = kind;
  37010. propInfo.name = propName;
  37011. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  37012. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  37013. propInfo.typeLevelCompare = typeLevelCompare;
  37014. node.levelContent.add(propName, propInfo);
  37015. return propInfo;
  37016. };
  37017. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  37018. // Nothing to nothing: nothing to do!
  37019. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  37020. return true;
  37021. }
  37022. // Check value unchanged
  37023. if ((curValue != null) && (newValue != null)) {
  37024. if (typeof (curValue.equals) == "function") {
  37025. if (curValue.equals(newValue)) {
  37026. return true;
  37027. }
  37028. }
  37029. else {
  37030. if (curValue === newValue) {
  37031. return true;
  37032. }
  37033. }
  37034. }
  37035. return false;
  37036. };
  37037. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  37038. if (this.isDisposed) {
  37039. return;
  37040. }
  37041. var i = propertyName.indexOf(".");
  37042. if (i !== -1) {
  37043. propertyName = propertyName.substr(0, i);
  37044. }
  37045. var propInfo = this.propDic.get(propertyName);
  37046. if (!propInfo) {
  37047. return;
  37048. }
  37049. var newValue = this[propertyName];
  37050. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  37051. };
  37052. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  37053. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37054. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  37055. if (this instanceof BABYLON.Prim2DBase) {
  37056. var curprim = this;
  37057. while (curprim) {
  37058. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  37059. if (curprim.isSizeAuto) {
  37060. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  37061. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  37062. }
  37063. if (curprim instanceof BABYLON.Group2D) {
  37064. if (curprim.isRenderableGroup) {
  37065. break;
  37066. }
  37067. }
  37068. curprim = curprim.parent;
  37069. }
  37070. }
  37071. };
  37072. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37073. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37074. if (propInfo.dirtyBoundingInfo) {
  37075. this._boundingBoxDirty();
  37076. }
  37077. else if (propInfo.dirtyParentBoundingInfo) {
  37078. var p = this._parent;
  37079. if (p != null) {
  37080. p._boundingBoxDirty();
  37081. }
  37082. }
  37083. // Trigger property changed
  37084. var info = SmartPropertyPrim.propChangedInfo;
  37085. info.oldValue = curValue;
  37086. info.newValue = newValue;
  37087. info.propertyName = propName;
  37088. var propMask = propInfo.flagId;
  37089. this.propertyChanged.notifyObservers(info, propMask);
  37090. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37091. if (this instanceof BABYLON.Group2D) {
  37092. this.handleGroupChanged(propInfo);
  37093. }
  37094. // Check for parent layout dirty
  37095. if (this instanceof BABYLON.Prim2DBase) {
  37096. var p = this._parent;
  37097. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  37098. p._setLayoutDirty();
  37099. }
  37100. }
  37101. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  37102. var instanceDirty = false;
  37103. if (typeLevelCompare && curValue != null && newValue != null) {
  37104. var cvProto = curValue.__proto__;
  37105. var nvProto = newValue.__proto__;
  37106. instanceDirty = (cvProto === nvProto);
  37107. }
  37108. // Set the dirty flags
  37109. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  37110. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  37111. }
  37112. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  37113. this.onPrimitivePropertyDirty(propMask);
  37114. }
  37115. };
  37116. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  37117. if (!this.isDirty) {
  37118. this.onPrimBecomesDirty();
  37119. }
  37120. this._instanceDirtyFlags |= propFlagId;
  37121. };
  37122. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  37123. };
  37124. /**
  37125. * Check if a given set of properties are dirty or not.
  37126. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37127. * @return true if at least one property is dirty, false if none of them are.
  37128. */
  37129. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  37130. return (this._instanceDirtyFlags & flags) !== 0;
  37131. };
  37132. /**
  37133. * Clear a given set of properties.
  37134. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37135. * @return the new set of property still marked as dirty
  37136. */
  37137. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  37138. this._instanceDirtyFlags &= ~flags;
  37139. return this._instanceDirtyFlags;
  37140. };
  37141. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  37142. this._instanceDirtyFlags = 0;
  37143. };
  37144. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  37145. /**
  37146. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  37147. */
  37148. get: function () {
  37149. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  37150. this.updateLevelBoundingInfo();
  37151. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37152. }
  37153. return this._levelBoundingInfo;
  37154. },
  37155. enumerable: true,
  37156. configurable: true
  37157. });
  37158. /**
  37159. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  37160. */
  37161. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  37162. };
  37163. /**
  37164. * Property method called when the Primitive becomes dirty
  37165. */
  37166. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  37167. };
  37168. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  37169. return function (target, propName, descriptor) {
  37170. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  37171. if (piStore) {
  37172. piStore(propInfo);
  37173. }
  37174. var getter = descriptor.get, setter = descriptor.set;
  37175. // Overload the property setter implementation to add our own logic
  37176. descriptor.set = function (val) {
  37177. // check for disposed first, do nothing
  37178. if (this.isDisposed) {
  37179. return;
  37180. }
  37181. var curVal = getter.call(this);
  37182. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  37183. return;
  37184. }
  37185. // Cast the object we're working one
  37186. var prim = this;
  37187. // Change the value
  37188. setter.call(this, val);
  37189. // Notify change, dirty flags update
  37190. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  37191. };
  37192. };
  37193. };
  37194. /**
  37195. * Add an externally attached data from its key.
  37196. * This method call will fail and return false, if such key already exists.
  37197. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  37198. * @param key the unique key that identifies the data
  37199. * @param data the data object to associate to the key for this Engine instance
  37200. * @return true if no such key were already present and the data was added successfully, false otherwise
  37201. */
  37202. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  37203. if (!this._externalData) {
  37204. this._externalData = new BABYLON.StringDictionary();
  37205. }
  37206. return this._externalData.add(key, data);
  37207. };
  37208. /**
  37209. * Get an externally attached data from its key
  37210. * @param key the unique key that identifies the data
  37211. * @return the associated data, if present (can be null), or undefined if not present
  37212. */
  37213. SmartPropertyPrim.prototype.getExternalData = function (key) {
  37214. if (!this._externalData) {
  37215. return null;
  37216. }
  37217. return this._externalData.get(key);
  37218. };
  37219. /**
  37220. * Get an externally attached data from its key, create it using a factory if it's not already present
  37221. * @param key the unique key that identifies the data
  37222. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  37223. * @return the associated data, can be null if the factory returned null.
  37224. */
  37225. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  37226. if (!this._externalData) {
  37227. this._externalData = new BABYLON.StringDictionary();
  37228. }
  37229. return this._externalData.getOrAddWithFactory(key, factory);
  37230. };
  37231. /**
  37232. * Remove an externally attached data from the Engine instance
  37233. * @param key the unique key that identifies the data
  37234. * @return true if the data was successfully removed, false if it doesn't exist
  37235. */
  37236. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  37237. if (!this._externalData) {
  37238. return false;
  37239. }
  37240. return this._externalData.remove(key);
  37241. };
  37242. /**
  37243. * Check if a given flag is set
  37244. * @param flag the flag value
  37245. * @return true if set, false otherwise
  37246. */
  37247. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  37248. return (this._flags & flag) !== 0;
  37249. };
  37250. /**
  37251. * Check if all given flags are set
  37252. * @param flags the flags ORed
  37253. * @return true if all the flags are set, false otherwise
  37254. */
  37255. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  37256. return (this._flags & flags) === flags;
  37257. };
  37258. /**
  37259. * Check if at least one flag of the given flags is set
  37260. * @param flags the flags ORed
  37261. * @return true if at least one flag is set, false otherwise
  37262. */
  37263. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  37264. return (this._flags & flags) !== 0;
  37265. };
  37266. /**
  37267. * Clear the given flags
  37268. * @param flags the flags to clear
  37269. */
  37270. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  37271. this._flags &= ~flags;
  37272. };
  37273. /**
  37274. * Set the given flags to true state
  37275. * @param flags the flags ORed to set
  37276. * @return the flags state before this call
  37277. */
  37278. SmartPropertyPrim.prototype._setFlags = function (flags) {
  37279. var cur = this._flags;
  37280. this._flags |= flags;
  37281. return cur;
  37282. };
  37283. /**
  37284. * Change the state of the given flags
  37285. * @param flags the flags ORed to change
  37286. * @param state true to set them, false to clear them
  37287. */
  37288. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  37289. if (state) {
  37290. this._flags |= flags;
  37291. }
  37292. else {
  37293. this._flags &= ~flags;
  37294. }
  37295. };
  37296. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  37297. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  37298. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  37299. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  37300. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  37301. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  37302. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  37303. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  37304. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  37305. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  37306. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  37307. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  37308. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  37309. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  37310. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  37311. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  37312. SmartPropertyPrim = __decorate([
  37313. BABYLON.className("SmartPropertyPrim")
  37314. ], SmartPropertyPrim);
  37315. return SmartPropertyPrim;
  37316. })();
  37317. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  37318. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37319. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37320. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37321. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37322. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  37323. }
  37324. BABYLON.modelLevelProperty = modelLevelProperty;
  37325. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37326. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37327. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37328. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37329. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  37330. }
  37331. BABYLON.instanceLevelProperty = instanceLevelProperty;
  37332. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37333. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37334. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37335. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37336. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  37337. }
  37338. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  37339. })(BABYLON || (BABYLON = {}));
  37340. var BABYLON;
  37341. (function (BABYLON) {
  37342. var PrepareRender2DContext = (function () {
  37343. function PrepareRender2DContext() {
  37344. this.forceRefreshPrimitive = false;
  37345. }
  37346. return PrepareRender2DContext;
  37347. })();
  37348. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  37349. var Render2DContext = (function () {
  37350. function Render2DContext(renderMode) {
  37351. this._renderMode = renderMode;
  37352. this.useInstancing = false;
  37353. this.groupInfoPartData = null;
  37354. this.partDataStartIndex = this.partDataEndIndex = null;
  37355. this.instancedBuffers = null;
  37356. }
  37357. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  37358. /**
  37359. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  37360. */
  37361. get: function () {
  37362. return this._renderMode;
  37363. },
  37364. enumerable: true,
  37365. configurable: true
  37366. });
  37367. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  37368. /**
  37369. * The set of primitives to render is opaque.
  37370. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  37371. */
  37372. get: function () {
  37373. return Render2DContext._renderModeOpaque;
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  37379. /**
  37380. * The set of primitives to render is using Alpha Test (aka masking).
  37381. * 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.
  37382. */
  37383. get: function () {
  37384. return Render2DContext._renderModeAlphaTest;
  37385. },
  37386. enumerable: true,
  37387. configurable: true
  37388. });
  37389. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  37390. /**
  37391. * The set of primitives to render is transparent.
  37392. * 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.
  37393. */
  37394. get: function () {
  37395. return Render2DContext._renderModeTransparent;
  37396. },
  37397. enumerable: true,
  37398. configurable: true
  37399. });
  37400. Render2DContext._renderModeOpaque = 1;
  37401. Render2DContext._renderModeAlphaTest = 2;
  37402. Render2DContext._renderModeTransparent = 3;
  37403. return Render2DContext;
  37404. })();
  37405. BABYLON.Render2DContext = Render2DContext;
  37406. /**
  37407. * This class store information for the pointerEventObservable Observable.
  37408. * 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.
  37409. */
  37410. var PrimitivePointerInfo = (function () {
  37411. function PrimitivePointerInfo() {
  37412. this.primitivePointerPos = BABYLON.Vector2.Zero();
  37413. this.tilt = BABYLON.Vector2.Zero();
  37414. this.cancelBubble = false;
  37415. }
  37416. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  37417. // 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.
  37418. /**
  37419. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  37420. * Bubbles: yes
  37421. */
  37422. get: function () {
  37423. return PrimitivePointerInfo._pointerOver;
  37424. },
  37425. enumerable: true,
  37426. configurable: true
  37427. });
  37428. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  37429. /**
  37430. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  37431. * Bubbles: no
  37432. */
  37433. get: function () {
  37434. return PrimitivePointerInfo._pointerEnter;
  37435. },
  37436. enumerable: true,
  37437. configurable: true
  37438. });
  37439. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  37440. /**
  37441. * 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.
  37442. * Bubbles: yes
  37443. */
  37444. get: function () {
  37445. return PrimitivePointerInfo._pointerDown;
  37446. },
  37447. enumerable: true,
  37448. configurable: true
  37449. });
  37450. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  37451. /**
  37452. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  37453. * Bubbles: yes
  37454. */
  37455. get: function () {
  37456. return PrimitivePointerInfo._pointerMouseWheel;
  37457. },
  37458. enumerable: true,
  37459. configurable: true
  37460. });
  37461. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  37462. /**
  37463. * 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.
  37464. * Bubbles: yes
  37465. */
  37466. get: function () {
  37467. return PrimitivePointerInfo._pointerMove;
  37468. },
  37469. enumerable: true,
  37470. configurable: true
  37471. });
  37472. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  37473. /**
  37474. * 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.
  37475. * Bubbles: yes
  37476. */
  37477. get: function () {
  37478. return PrimitivePointerInfo._pointerUp;
  37479. },
  37480. enumerable: true,
  37481. configurable: true
  37482. });
  37483. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  37484. /**
  37485. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  37486. * Bubbles: yes
  37487. */
  37488. get: function () {
  37489. return PrimitivePointerInfo._pointerOut;
  37490. },
  37491. enumerable: true,
  37492. configurable: true
  37493. });
  37494. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  37495. /**
  37496. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  37497. * Bubbles: no
  37498. */
  37499. get: function () {
  37500. return PrimitivePointerInfo._pointerLeave;
  37501. },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  37506. /**
  37507. * 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.
  37508. * Bubbles: yes
  37509. */
  37510. get: function () {
  37511. return PrimitivePointerInfo._pointerGotCapture;
  37512. },
  37513. enumerable: true,
  37514. configurable: true
  37515. });
  37516. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  37517. /**
  37518. * This event type is raised after pointer capture is released for a pointer.
  37519. * Bubbles: yes
  37520. */
  37521. get: function () {
  37522. return PrimitivePointerInfo._pointerLostCapture;
  37523. },
  37524. enumerable: true,
  37525. configurable: true
  37526. });
  37527. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  37528. get: function () {
  37529. return PrimitivePointerInfo._mouseWheelPrecision;
  37530. },
  37531. enumerable: true,
  37532. configurable: true
  37533. });
  37534. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  37535. this.relatedTarget = prim;
  37536. this.relatedTargetPointerPos = primPointerPos;
  37537. };
  37538. PrimitivePointerInfo.getEventTypeName = function (mask) {
  37539. switch (mask) {
  37540. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  37541. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  37542. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  37543. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  37544. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  37545. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  37546. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  37547. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  37548. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  37549. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  37550. }
  37551. };
  37552. PrimitivePointerInfo._pointerOver = 0x0001;
  37553. PrimitivePointerInfo._pointerEnter = 0x0002;
  37554. PrimitivePointerInfo._pointerDown = 0x0004;
  37555. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  37556. PrimitivePointerInfo._pointerMove = 0x0010;
  37557. PrimitivePointerInfo._pointerUp = 0x0020;
  37558. PrimitivePointerInfo._pointerOut = 0x0040;
  37559. PrimitivePointerInfo._pointerLeave = 0x0080;
  37560. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  37561. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  37562. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  37563. return PrimitivePointerInfo;
  37564. })();
  37565. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  37566. /**
  37567. * Defines the horizontal and vertical alignment information for a Primitive.
  37568. */
  37569. var PrimitiveAlignment = (function () {
  37570. function PrimitiveAlignment(changeCallback) {
  37571. this._changedCallback = changeCallback;
  37572. this._horizontal = PrimitiveAlignment.AlignLeft;
  37573. this._vertical = PrimitiveAlignment.AlignBottom;
  37574. }
  37575. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  37576. /**
  37577. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  37578. */
  37579. get: function () { return PrimitiveAlignment._AlignLeft; },
  37580. enumerable: true,
  37581. configurable: true
  37582. });
  37583. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37584. /**
  37585. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37586. */
  37587. get: function () { return PrimitiveAlignment._AlignTop; },
  37588. enumerable: true,
  37589. configurable: true
  37590. });
  37591. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37592. /**
  37593. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37594. */
  37595. get: function () { return PrimitiveAlignment._AlignRight; },
  37596. enumerable: true,
  37597. configurable: true
  37598. });
  37599. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37600. /**
  37601. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37602. */
  37603. get: function () { return PrimitiveAlignment._AlignBottom; },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37608. /**
  37609. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37610. */
  37611. get: function () { return PrimitiveAlignment._AlignCenter; },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37616. /**
  37617. * The content is stretched toward the opposite edges of the Primitive
  37618. */
  37619. get: function () { return PrimitiveAlignment._AlignStretch; },
  37620. enumerable: true,
  37621. configurable: true
  37622. });
  37623. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37624. /**
  37625. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37626. */
  37627. get: function () {
  37628. return this._horizontal;
  37629. },
  37630. set: function (value) {
  37631. if (this._horizontal === value) {
  37632. return;
  37633. }
  37634. this._horizontal = value;
  37635. this._changedCallback();
  37636. },
  37637. enumerable: true,
  37638. configurable: true
  37639. });
  37640. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37641. /**
  37642. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37643. */
  37644. get: function () {
  37645. return this._vertical;
  37646. },
  37647. set: function (value) {
  37648. if (this._vertical === value) {
  37649. return;
  37650. }
  37651. this._vertical = value;
  37652. this._changedCallback();
  37653. },
  37654. enumerable: true,
  37655. configurable: true
  37656. });
  37657. /**
  37658. * Set the horizontal alignment from a string value.
  37659. * @param text can be either: 'left','right','center','stretch'
  37660. */
  37661. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37662. var v = text.trim().toLocaleLowerCase();
  37663. switch (v) {
  37664. case "left":
  37665. this.horizontal = PrimitiveAlignment.AlignLeft;
  37666. return;
  37667. case "right":
  37668. this.horizontal = PrimitiveAlignment.AlignRight;
  37669. return;
  37670. case "center":
  37671. this.horizontal = PrimitiveAlignment.AlignCenter;
  37672. return;
  37673. case "stretch":
  37674. this.horizontal = PrimitiveAlignment.AlignStretch;
  37675. return;
  37676. }
  37677. };
  37678. /**
  37679. * Set the vertical alignment from a string value.
  37680. * @param text can be either: 'top','bottom','center','stretch'
  37681. */
  37682. PrimitiveAlignment.prototype.setVertical = function (text) {
  37683. var v = text.trim().toLocaleLowerCase();
  37684. switch (v) {
  37685. case "top":
  37686. this.vertical = PrimitiveAlignment.AlignTop;
  37687. return;
  37688. case "bottom":
  37689. this.vertical = PrimitiveAlignment.AlignBottom;
  37690. return;
  37691. case "center":
  37692. this.vertical = PrimitiveAlignment.AlignCenter;
  37693. return;
  37694. case "stretch":
  37695. this.vertical = PrimitiveAlignment.AlignStretch;
  37696. return;
  37697. }
  37698. };
  37699. /**
  37700. * Set the horizontal and or vertical alignments from a string value.
  37701. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  37702. */
  37703. PrimitiveAlignment.prototype.fromString = function (value) {
  37704. var m = value.trim().split(",");
  37705. for (var _i = 0; _i < m.length; _i++) {
  37706. var v = m[_i];
  37707. v = v.toLocaleLowerCase().trim();
  37708. // Horizontal
  37709. var i = v.indexOf("h:");
  37710. if (i === -1) {
  37711. i = v.indexOf("horizontal:");
  37712. }
  37713. if (i !== -1) {
  37714. v = v.substr(v.indexOf(":") + 1);
  37715. this.setHorizontal(v);
  37716. continue;
  37717. }
  37718. // Vertical
  37719. i = v.indexOf("v:");
  37720. if (i === -1) {
  37721. i = v.indexOf("vertical:");
  37722. }
  37723. if (i !== -1) {
  37724. v = v.substr(v.indexOf(":") + 1);
  37725. this.setVertical(v);
  37726. continue;
  37727. }
  37728. }
  37729. };
  37730. PrimitiveAlignment._AlignLeft = 1;
  37731. PrimitiveAlignment._AlignTop = 1; // Same as left
  37732. PrimitiveAlignment._AlignRight = 2;
  37733. PrimitiveAlignment._AlignBottom = 2; // Same as right
  37734. PrimitiveAlignment._AlignCenter = 3;
  37735. PrimitiveAlignment._AlignStretch = 4;
  37736. return PrimitiveAlignment;
  37737. })();
  37738. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  37739. /**
  37740. * Stores information about a Primitive that was intersected
  37741. */
  37742. var PrimitiveIntersectedInfo = (function () {
  37743. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  37744. this.prim = prim;
  37745. this.intersectionLocation = intersectionLocation;
  37746. }
  37747. return PrimitiveIntersectedInfo;
  37748. })();
  37749. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  37750. /**
  37751. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  37752. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  37753. */
  37754. var PrimitiveThickness = (function () {
  37755. function PrimitiveThickness(parentAccess, changedCallback) {
  37756. this._parentAccess = parentAccess;
  37757. this._changedCallback = changedCallback;
  37758. this._pixels = new Array(4);
  37759. this._percentages = new Array(4);
  37760. this._setType(0, PrimitiveThickness.Auto);
  37761. this._setType(1, PrimitiveThickness.Auto);
  37762. this._setType(2, PrimitiveThickness.Auto);
  37763. this._setType(3, PrimitiveThickness.Auto);
  37764. this._pixels[0] = 0;
  37765. this._pixels[1] = 0;
  37766. this._pixels[2] = 0;
  37767. this._pixels[3] = 0;
  37768. }
  37769. /**
  37770. * Set the thickness from a string value
  37771. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  37772. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37773. */
  37774. PrimitiveThickness.prototype.fromString = function (thickness) {
  37775. this._clear();
  37776. var m = thickness.trim().split(",");
  37777. // Special case, one value to apply to all edges
  37778. if (m.length === 1 && thickness.indexOf(":") === -1) {
  37779. this._setStringValue(m[0], 0, false);
  37780. this._setStringValue(m[0], 1, false);
  37781. this._setStringValue(m[0], 2, false);
  37782. this._setStringValue(m[0], 3, false);
  37783. this._changedCallback();
  37784. return;
  37785. }
  37786. var res = false;
  37787. for (var _i = 0; _i < m.length; _i++) {
  37788. var cm = m[_i];
  37789. res = this._extractString(cm, false) || res;
  37790. }
  37791. if (!res) {
  37792. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  37793. }
  37794. // Check the margin that weren't set and set them in auto
  37795. if ((this._flags & 0x000F) === 0)
  37796. this._flags |= PrimitiveThickness.Pixel << 0;
  37797. if ((this._flags & 0x00F0) === 0)
  37798. this._flags |= PrimitiveThickness.Pixel << 4;
  37799. if ((this._flags & 0x0F00) === 0)
  37800. this._flags |= PrimitiveThickness.Pixel << 8;
  37801. if ((this._flags & 0xF000) === 0)
  37802. this._flags |= PrimitiveThickness.Pixel << 12;
  37803. this._changedCallback();
  37804. };
  37805. /**
  37806. * Set the thickness from multiple string
  37807. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  37808. * @param top the top thickness to set
  37809. * @param left the left thickness to set
  37810. * @param right the right thickness to set
  37811. * @param bottom the bottom thickness to set
  37812. */
  37813. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  37814. this._clear();
  37815. this._setStringValue(top, 0, false);
  37816. this._setStringValue(left, 1, false);
  37817. this._setStringValue(right, 2, false);
  37818. this._setStringValue(bottom, 3, false);
  37819. this._changedCallback();
  37820. return this;
  37821. };
  37822. /**
  37823. * Set the thickness from pixel values
  37824. * @param top the top thickness in pixels to set
  37825. * @param left the left thickness in pixels to set
  37826. * @param right the right thickness in pixels to set
  37827. * @param bottom the bottom thickness in pixels to set
  37828. */
  37829. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  37830. this._clear();
  37831. this._pixels[0] = top;
  37832. this._pixels[1] = left;
  37833. this._pixels[2] = right;
  37834. this._pixels[3] = bottom;
  37835. this._changedCallback();
  37836. return this;
  37837. };
  37838. /**
  37839. * Apply the same pixel value to all edges
  37840. * @param margin the value to set, in pixels.
  37841. */
  37842. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  37843. this._clear();
  37844. this._pixels[0] = margin;
  37845. this._pixels[1] = margin;
  37846. this._pixels[2] = margin;
  37847. this._pixels[3] = margin;
  37848. this._changedCallback();
  37849. return this;
  37850. };
  37851. /**
  37852. * Set all edges in auto
  37853. */
  37854. PrimitiveThickness.prototype.auto = function () {
  37855. this._clear();
  37856. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  37857. this._pixels[0] = 0;
  37858. this._pixels[1] = 0;
  37859. this._pixels[2] = 0;
  37860. this._pixels[3] = 0;
  37861. this._changedCallback();
  37862. return this;
  37863. };
  37864. PrimitiveThickness.prototype._clear = function () {
  37865. this._flags = 0;
  37866. this._pixels[0] = 0;
  37867. this._pixels[1] = 0;
  37868. this._pixels[2] = 0;
  37869. this._pixels[3] = 0;
  37870. this._percentages[0] = null;
  37871. this._percentages[1] = null;
  37872. this._percentages[2] = null;
  37873. this._percentages[3] = null;
  37874. };
  37875. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  37876. var v = value.trim().toLocaleLowerCase();
  37877. if (v.indexOf("top:") === 0) {
  37878. v = v.substr(4).trim();
  37879. return this._setStringValue(v, 0, emitChanged);
  37880. }
  37881. if (v.indexOf("left:") === 0) {
  37882. v = v.substr(5).trim();
  37883. return this._setStringValue(v, 1, emitChanged);
  37884. }
  37885. if (v.indexOf("right:") === 0) {
  37886. v = v.substr(6).trim();
  37887. return this._setStringValue(v, 2, emitChanged);
  37888. }
  37889. if (v.indexOf("bottom:") === 0) {
  37890. v = v.substr(7).trim();
  37891. return this._setStringValue(v, 3, emitChanged);
  37892. }
  37893. return false;
  37894. };
  37895. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  37896. // Check for auto
  37897. var v = value.trim().toLocaleLowerCase();
  37898. if (v === "auto") {
  37899. if (this._isType(index, PrimitiveThickness.Auto)) {
  37900. return true;
  37901. }
  37902. this._setType(index, PrimitiveThickness.Auto);
  37903. this._pixels[index] = 0;
  37904. if (emitChanged) {
  37905. this._changedCallback();
  37906. }
  37907. }
  37908. else if (v === "inherit") {
  37909. if (this._isType(index, PrimitiveThickness.Inherit)) {
  37910. return true;
  37911. }
  37912. this._setType(index, PrimitiveThickness.Inherit);
  37913. this._pixels[index] = null;
  37914. if (emitChanged) {
  37915. this._changedCallback();
  37916. }
  37917. }
  37918. else {
  37919. var pI = v.indexOf("%");
  37920. // Check for percentage
  37921. if (pI !== -1) {
  37922. var n_1 = v.substr(0, pI);
  37923. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  37924. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  37925. return true;
  37926. }
  37927. this._setType(index, PrimitiveThickness.Percentage);
  37928. if (isNaN(number_1)) {
  37929. return false;
  37930. }
  37931. this._percentages[index] = number_1;
  37932. if (emitChanged) {
  37933. this._changedCallback();
  37934. }
  37935. return true;
  37936. }
  37937. // Check for pixel
  37938. var n;
  37939. pI = v.indexOf("px");
  37940. if (pI !== -1) {
  37941. n = v.substr(0, pI).trim();
  37942. }
  37943. else {
  37944. n = v;
  37945. }
  37946. var number = Number(n);
  37947. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  37948. return true;
  37949. }
  37950. if (isNaN(number)) {
  37951. return false;
  37952. }
  37953. this._pixels[index] = number;
  37954. this._setType(index, PrimitiveThickness.Pixel);
  37955. if (emitChanged) {
  37956. this._changedCallback();
  37957. }
  37958. return true;
  37959. }
  37960. };
  37961. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  37962. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  37963. value = Math.round(value);
  37964. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  37965. return;
  37966. }
  37967. this._setType(index, PrimitiveThickness.Pixel);
  37968. this._pixels[index] = value;
  37969. if (emitChanged) {
  37970. this._changedCallback();
  37971. }
  37972. };
  37973. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  37974. // Clip Value to bounds
  37975. value = Math.min(1, value);
  37976. value = Math.max(0, value);
  37977. value = Math.round(value * 100) / 100; // 0.01 precision
  37978. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  37979. return;
  37980. }
  37981. this._setType(index, PrimitiveThickness.Percentage);
  37982. this._percentages[index] = value;
  37983. if (emitChanged) {
  37984. this._changedCallback();
  37985. }
  37986. };
  37987. PrimitiveThickness.prototype._getStringValue = function (index) {
  37988. var f = (this._flags >> (index * 4)) & 0xF;
  37989. switch (f) {
  37990. case PrimitiveThickness.Auto:
  37991. return "auto";
  37992. case PrimitiveThickness.Pixel:
  37993. return this._pixels[index] + "px";
  37994. case PrimitiveThickness.Percentage:
  37995. return this._percentages[index] * 100 + "%";
  37996. case PrimitiveThickness.Inherit:
  37997. return "inherit";
  37998. }
  37999. return "";
  38000. };
  38001. PrimitiveThickness.prototype._isType = function (index, type) {
  38002. var f = (this._flags >> (index * 4)) & 0xF;
  38003. return f === type;
  38004. };
  38005. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  38006. var t = (this._flags >> (index * 4)) & 0xF;
  38007. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  38008. var p = this._parentAccess();
  38009. if (p) {
  38010. return p._getType(index, true);
  38011. }
  38012. return PrimitiveThickness.Auto;
  38013. }
  38014. return t;
  38015. };
  38016. PrimitiveThickness.prototype._setType = function (index, type) {
  38017. this._flags &= ~(0xF << (index * 4));
  38018. this._flags |= type << (index * 4);
  38019. };
  38020. PrimitiveThickness.prototype.setTop = function (value) {
  38021. if (typeof value === "string") {
  38022. this._setStringValue(value, 0, true);
  38023. }
  38024. else {
  38025. this.topPixels = value;
  38026. }
  38027. };
  38028. PrimitiveThickness.prototype.setLeft = function (value) {
  38029. if (typeof value === "string") {
  38030. this._setStringValue(value, 1, true);
  38031. }
  38032. else {
  38033. this.leftPixels = value;
  38034. }
  38035. };
  38036. PrimitiveThickness.prototype.setRight = function (value) {
  38037. if (typeof value === "string") {
  38038. this._setStringValue(value, 2, true);
  38039. }
  38040. else {
  38041. this.rightPixels = value;
  38042. }
  38043. };
  38044. PrimitiveThickness.prototype.setBottom = function (value) {
  38045. if (typeof value === "string") {
  38046. this._setStringValue(value, 3, true);
  38047. }
  38048. else {
  38049. this.bottomPixels = value;
  38050. }
  38051. };
  38052. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  38053. /**
  38054. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38055. */
  38056. get: function () {
  38057. return this._getStringValue(0);
  38058. },
  38059. set: function (value) {
  38060. this._setStringValue(value, 0, true);
  38061. },
  38062. enumerable: true,
  38063. configurable: true
  38064. });
  38065. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  38066. /**
  38067. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38068. */
  38069. get: function () {
  38070. return this._getStringValue(1);
  38071. },
  38072. set: function (value) {
  38073. this._setStringValue(value, 1, true);
  38074. },
  38075. enumerable: true,
  38076. configurable: true
  38077. });
  38078. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  38079. /**
  38080. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38081. */
  38082. get: function () {
  38083. return this._getStringValue(2);
  38084. },
  38085. set: function (value) {
  38086. this._setStringValue(value, 2, true);
  38087. },
  38088. enumerable: true,
  38089. configurable: true
  38090. });
  38091. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38092. /**
  38093. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38094. */
  38095. get: function () {
  38096. return this._getStringValue(3);
  38097. },
  38098. set: function (value) {
  38099. this._setStringValue(value, 3, true);
  38100. },
  38101. enumerable: true,
  38102. configurable: true
  38103. });
  38104. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  38105. /**
  38106. * Get/set the top thickness in pixel.
  38107. */
  38108. get: function () {
  38109. return this._pixels[0];
  38110. },
  38111. set: function (value) {
  38112. this._setPixels(value, 0, true);
  38113. },
  38114. enumerable: true,
  38115. configurable: true
  38116. });
  38117. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  38118. /**
  38119. * Get/set the left thickness in pixel.
  38120. */
  38121. get: function () {
  38122. return this._pixels[1];
  38123. },
  38124. set: function (value) {
  38125. this._setPixels(value, 1, true);
  38126. },
  38127. enumerable: true,
  38128. configurable: true
  38129. });
  38130. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  38131. /**
  38132. * Get/set the right thickness in pixel.
  38133. */
  38134. get: function () {
  38135. return this._pixels[2];
  38136. },
  38137. set: function (value) {
  38138. this._setPixels(value, 2, true);
  38139. },
  38140. enumerable: true,
  38141. configurable: true
  38142. });
  38143. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  38144. /**
  38145. * Get/set the bottom thickness in pixel.
  38146. */
  38147. get: function () {
  38148. return this._pixels[3];
  38149. },
  38150. set: function (value) {
  38151. this._setPixels(value, 3, true);
  38152. },
  38153. enumerable: true,
  38154. configurable: true
  38155. });
  38156. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  38157. /**
  38158. * Get/set the top thickness in percentage.
  38159. * The get will return a valid value only if the edge type is percentage.
  38160. * The Set will change the edge mode if needed
  38161. */
  38162. get: function () {
  38163. return this._percentages[0];
  38164. },
  38165. set: function (value) {
  38166. this._setPercentage(value, 0, true);
  38167. },
  38168. enumerable: true,
  38169. configurable: true
  38170. });
  38171. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  38172. /**
  38173. * Get/set the left thickness in percentage.
  38174. * The get will return a valid value only if the edge mode is percentage.
  38175. * The Set will change the edge mode if needed
  38176. */
  38177. get: function () {
  38178. return this._percentages[1];
  38179. },
  38180. set: function (value) {
  38181. this._setPercentage(value, 1, true);
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  38187. /**
  38188. * Get/set the right thickness in percentage.
  38189. * The get will return a valid value only if the edge mode is percentage.
  38190. * The Set will change the edge mode if needed
  38191. */
  38192. get: function () {
  38193. return this._percentages[2];
  38194. },
  38195. set: function (value) {
  38196. this._setPercentage(value, 2, true);
  38197. },
  38198. enumerable: true,
  38199. configurable: true
  38200. });
  38201. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  38202. /**
  38203. * Get/set the bottom thickness in percentage.
  38204. * The get will return a valid value only if the edge mode is percentage.
  38205. * The Set will change the edge mode if needed
  38206. */
  38207. get: function () {
  38208. return this._percentages[3];
  38209. },
  38210. set: function (value) {
  38211. this._setPercentage(value, 3, true);
  38212. },
  38213. enumerable: true,
  38214. configurable: true
  38215. });
  38216. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  38217. /**
  38218. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  38219. */
  38220. get: function () {
  38221. return this._getType(0, false);
  38222. },
  38223. set: function (mode) {
  38224. this._setType(0, mode);
  38225. },
  38226. enumerable: true,
  38227. configurable: true
  38228. });
  38229. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  38230. /**
  38231. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  38232. */
  38233. get: function () {
  38234. return this._getType(1, false);
  38235. },
  38236. set: function (mode) {
  38237. this._setType(1, mode);
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  38243. /**
  38244. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  38245. */
  38246. get: function () {
  38247. return this._getType(2, false);
  38248. },
  38249. set: function (mode) {
  38250. this._setType(2, mode);
  38251. },
  38252. enumerable: true,
  38253. configurable: true
  38254. });
  38255. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  38256. /**
  38257. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  38258. */
  38259. get: function () {
  38260. return this._getType(3, false);
  38261. },
  38262. set: function (mode) {
  38263. this._setType(3, mode);
  38264. },
  38265. enumerable: true,
  38266. configurable: true
  38267. });
  38268. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  38269. var type = this._getType(index, false);
  38270. if (type === PrimitiveThickness.Inherit) {
  38271. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  38272. return;
  38273. }
  38274. if (type !== PrimitiveThickness.Percentage) {
  38275. return;
  38276. }
  38277. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  38278. this._pixels[index] = pixels;
  38279. if (emitChanged) {
  38280. this._changedCallback();
  38281. }
  38282. };
  38283. /**
  38284. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  38285. * @param sourceArea the source area
  38286. * @param contentSize the content size to position/resize
  38287. * @param alignment the alignment setting
  38288. * @param dstOffset the position of the content
  38289. * @param dstArea the new size of the content
  38290. */
  38291. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  38292. // Fetch some data
  38293. var topType = this._getType(0, true);
  38294. var leftType = this._getType(1, true);
  38295. var rightType = this._getType(2, true);
  38296. var bottomType = this._getType(3, true);
  38297. var hasWidth = contentSize && (contentSize.width != null);
  38298. var hasHeight = contentSize && (contentSize.height != null);
  38299. var width = hasWidth ? contentSize.width : 0;
  38300. var height = hasHeight ? contentSize.height : 0;
  38301. var isTopAuto = topType === PrimitiveThickness.Auto;
  38302. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  38303. var isRightAuto = rightType === PrimitiveThickness.Auto;
  38304. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  38305. switch (alignment.horizontal) {
  38306. case PrimitiveAlignment.AlignLeft:
  38307. {
  38308. if (isLeftAuto) {
  38309. dstOffset.x = 0;
  38310. }
  38311. else {
  38312. this._computePixels(1, sourceArea, true);
  38313. dstOffset.x = this.leftPixels;
  38314. }
  38315. dstArea.width = width;
  38316. break;
  38317. }
  38318. case PrimitiveAlignment.AlignRight:
  38319. {
  38320. if (isRightAuto) {
  38321. dstOffset.x = Math.round(sourceArea.width - width);
  38322. }
  38323. else {
  38324. this._computePixels(2, sourceArea, true);
  38325. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  38326. }
  38327. dstArea.width = width;
  38328. break;
  38329. }
  38330. case PrimitiveAlignment.AlignStretch:
  38331. {
  38332. if (isLeftAuto) {
  38333. dstOffset.x = 0;
  38334. }
  38335. else {
  38336. this._computePixels(1, sourceArea, true);
  38337. dstOffset.x = this.leftPixels;
  38338. }
  38339. var right = 0;
  38340. if (!isRightAuto) {
  38341. this._computePixels(2, sourceArea, true);
  38342. right = this.rightPixels;
  38343. }
  38344. dstArea.width = sourceArea.width - (dstOffset.x + right);
  38345. break;
  38346. }
  38347. case PrimitiveAlignment.AlignCenter:
  38348. {
  38349. if (!isLeftAuto) {
  38350. this._computePixels(1, sourceArea, true);
  38351. }
  38352. if (!isRightAuto) {
  38353. this._computePixels(2, sourceArea, true);
  38354. }
  38355. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  38356. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  38357. dstArea.width = width;
  38358. break;
  38359. }
  38360. }
  38361. switch (alignment.vertical) {
  38362. case PrimitiveAlignment.AlignTop:
  38363. {
  38364. if (isTopAuto) {
  38365. dstOffset.y = sourceArea.height - height;
  38366. }
  38367. else {
  38368. this._computePixels(0, sourceArea, true);
  38369. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  38370. }
  38371. dstArea.height = height;
  38372. break;
  38373. }
  38374. case PrimitiveAlignment.AlignBottom:
  38375. {
  38376. if (isBottomAuto) {
  38377. dstOffset.y = 0;
  38378. }
  38379. else {
  38380. this._computePixels(3, sourceArea, true);
  38381. dstOffset.y = this.bottomPixels;
  38382. }
  38383. dstArea.height = height;
  38384. break;
  38385. }
  38386. case PrimitiveAlignment.AlignStretch:
  38387. {
  38388. if (isBottomAuto) {
  38389. dstOffset.y = 0;
  38390. }
  38391. else {
  38392. this._computePixels(3, sourceArea, true);
  38393. dstOffset.y = this.bottomPixels;
  38394. }
  38395. var top_1 = 0;
  38396. if (!isTopAuto) {
  38397. this._computePixels(0, sourceArea, true);
  38398. top_1 = this.topPixels;
  38399. }
  38400. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  38401. break;
  38402. }
  38403. case PrimitiveAlignment.AlignCenter:
  38404. {
  38405. if (!isTopAuto) {
  38406. this._computePixels(0, sourceArea, true);
  38407. }
  38408. if (!isBottomAuto) {
  38409. this._computePixels(3, sourceArea, true);
  38410. }
  38411. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  38412. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  38413. dstArea.height = height;
  38414. break;
  38415. }
  38416. }
  38417. };
  38418. /**
  38419. * Compute an area and its position considering this thickness properties based on a given source area
  38420. * @param sourceArea the source area
  38421. * @param dstOffset the position of the resulting area
  38422. * @param dstArea the size of the resulting area
  38423. */
  38424. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  38425. this._computePixels(0, sourceArea, true);
  38426. this._computePixels(1, sourceArea, true);
  38427. this._computePixels(2, sourceArea, true);
  38428. this._computePixels(3, sourceArea, true);
  38429. dstOffset.x = this.leftPixels;
  38430. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  38431. dstOffset.y = this.bottomPixels;
  38432. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  38433. };
  38434. /**
  38435. * Compute an area considering this thickness properties based on a given source area
  38436. * @param sourceArea the source area
  38437. * @param result the resulting area
  38438. */
  38439. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  38440. this._computePixels(0, sourceArea, true);
  38441. this._computePixels(1, sourceArea, true);
  38442. this._computePixels(2, sourceArea, true);
  38443. this._computePixels(3, sourceArea, true);
  38444. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  38445. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  38446. };
  38447. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  38448. this._computePixels(0, sourceArea, true);
  38449. this._computePixels(1, sourceArea, true);
  38450. this._computePixels(2, sourceArea, true);
  38451. this._computePixels(3, sourceArea, true);
  38452. dstOffset.x = this.leftPixels;
  38453. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  38454. dstOffset.y = this.bottomPixels;
  38455. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  38456. };
  38457. PrimitiveThickness.Auto = 0x1;
  38458. PrimitiveThickness.Inherit = 0x2;
  38459. PrimitiveThickness.Percentage = 0x4;
  38460. PrimitiveThickness.Pixel = 0x8;
  38461. return PrimitiveThickness;
  38462. })();
  38463. BABYLON.PrimitiveThickness = PrimitiveThickness;
  38464. /**
  38465. * Main class used for the Primitive Intersection API
  38466. */
  38467. var IntersectInfo2D = (function () {
  38468. function IntersectInfo2D() {
  38469. this.findFirstOnly = false;
  38470. this.intersectHidden = false;
  38471. this.pickPosition = BABYLON.Vector2.Zero();
  38472. }
  38473. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  38474. /**
  38475. * true if at least one primitive intersected during the test
  38476. */
  38477. get: function () {
  38478. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  38479. },
  38480. enumerable: true,
  38481. configurable: true
  38482. });
  38483. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  38484. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  38485. var cur = _a[_i];
  38486. if (cur.prim === prim) {
  38487. return cur.intersectionLocation;
  38488. }
  38489. }
  38490. return null;
  38491. };
  38492. // Internals, don't use
  38493. IntersectInfo2D.prototype._exit = function (firstLevel) {
  38494. if (firstLevel) {
  38495. this._globalPickPosition = null;
  38496. }
  38497. };
  38498. return IntersectInfo2D;
  38499. })();
  38500. BABYLON.IntersectInfo2D = IntersectInfo2D;
  38501. var Prim2DBase = (function (_super) {
  38502. __extends(Prim2DBase, _super);
  38503. function Prim2DBase(settings) {
  38504. // Avoid checking every time if the object exists
  38505. if (settings == null) {
  38506. settings = {};
  38507. }
  38508. // BASE CLASS CALL
  38509. _super.call(this);
  38510. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  38511. var owner;
  38512. var parent;
  38513. if (Prim2DBase._isCanvasInit) {
  38514. owner = this;
  38515. parent = null;
  38516. this._canvasPreInit(settings);
  38517. }
  38518. else {
  38519. if (settings.parent != null) {
  38520. parent = settings.parent;
  38521. owner = settings.parent.owner;
  38522. if (!owner) {
  38523. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  38524. }
  38525. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  38526. 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");
  38527. }
  38528. }
  38529. }
  38530. // Fields initialization
  38531. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38532. this._size = null; //Size.Zero();
  38533. this._actualSize = null;
  38534. this._boundingSize = BABYLON.Size.Zero();
  38535. this._layoutArea = BABYLON.Size.Zero();
  38536. this._layoutAreaPos = BABYLON.Vector2.Zero();
  38537. this._marginOffset = BABYLON.Vector2.Zero();
  38538. this._paddingOffset = BABYLON.Vector2.Zero();
  38539. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  38540. this._parentContentArea = BABYLON.Size.Zero();
  38541. this._lastAutoSizeArea = BABYLON.Size.Zero();
  38542. this._contentArea = new BABYLON.Size(null, null);
  38543. this._pointerEventObservable = new BABYLON.Observable();
  38544. this._boundingInfo = new BABYLON.BoundingInfo2D();
  38545. this._owner = owner;
  38546. this._parent = null;
  38547. this._margin = null;
  38548. this._padding = null;
  38549. this._marginAlignment = null;
  38550. this._id = settings.id;
  38551. this.propertyChanged = new BABYLON.Observable();
  38552. this._children = new Array();
  38553. this._localTransform = new BABYLON.Matrix();
  38554. this._globalTransform = null;
  38555. this._invGlobalTransform = null;
  38556. this._globalTransformProcessStep = 0;
  38557. this._globalTransformStep = 0;
  38558. this._renderGroup = null;
  38559. this._primLinearPosition = 0;
  38560. this._manualZOrder = null;
  38561. this._zOrder = 0;
  38562. this._zMax = 0;
  38563. this._firstZDirtyIndex = Prim2DBase._bigInt;
  38564. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  38565. if (settings.opacity != null) {
  38566. this._opacity = settings.opacity;
  38567. }
  38568. else {
  38569. this._opacity = 1;
  38570. }
  38571. if (settings.childrenFlatZOrder) {
  38572. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  38573. }
  38574. // If the parent is given, initialize the hierarchy/owner related data
  38575. if (parent != null) {
  38576. parent.addChild(this);
  38577. this._patchHierarchy(parent.owner);
  38578. }
  38579. // If it's a group, detect its own states
  38580. if (this.owner && this instanceof BABYLON.Group2D) {
  38581. var group = this;
  38582. group.detectGroupStates();
  38583. }
  38584. // Time to insert children if some are specified
  38585. if (settings.children != null) {
  38586. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  38587. var child = _a[_i];
  38588. this.addChild(child);
  38589. // Good time to patch the hierarchy, it won't go very far if there's no need to
  38590. child._patchHierarchy(this.owner);
  38591. }
  38592. }
  38593. // Set the model related properties
  38594. if (settings.position != null) {
  38595. this.position = settings.position;
  38596. }
  38597. else if (settings.x != null || settings.y != null) {
  38598. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  38599. }
  38600. else {
  38601. this._position = null;
  38602. }
  38603. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  38604. this.scale = (settings.scale == null) ? 1 : settings.scale;
  38605. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  38606. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  38607. // Layout Engine
  38608. if (settings.layoutEngine != null) {
  38609. if (typeof settings.layoutEngine === "string") {
  38610. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  38611. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  38612. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38613. }
  38614. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  38615. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38616. }
  38617. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38618. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38619. }
  38620. }
  38621. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38622. this.layoutEngine = settings.layoutEngine;
  38623. }
  38624. }
  38625. // Set the layout/margin stuffs
  38626. if (settings.marginTop) {
  38627. this.margin.setTop(settings.marginTop);
  38628. }
  38629. if (settings.marginLeft) {
  38630. this.margin.setLeft(settings.marginLeft);
  38631. }
  38632. if (settings.marginRight) {
  38633. this.margin.setRight(settings.marginRight);
  38634. }
  38635. if (settings.marginBottom) {
  38636. this.margin.setBottom(settings.marginBottom);
  38637. }
  38638. if (settings.margin) {
  38639. if (typeof settings.margin === "string") {
  38640. this.margin.fromString(settings.margin);
  38641. }
  38642. else {
  38643. this.margin.fromUniformPixels(settings.margin);
  38644. }
  38645. }
  38646. if (settings.marginHAlignment) {
  38647. this.marginAlignment.horizontal = settings.marginHAlignment;
  38648. }
  38649. if (settings.marginVAlignment) {
  38650. this.marginAlignment.vertical = settings.marginVAlignment;
  38651. }
  38652. if (settings.marginAlignment) {
  38653. this.marginAlignment.fromString(settings.marginAlignment);
  38654. }
  38655. if (settings.paddingTop) {
  38656. this.padding.setTop(settings.paddingTop);
  38657. }
  38658. if (settings.paddingLeft) {
  38659. this.padding.setLeft(settings.paddingLeft);
  38660. }
  38661. if (settings.paddingRight) {
  38662. this.padding.setRight(settings.paddingRight);
  38663. }
  38664. if (settings.paddingBottom) {
  38665. this.padding.setBottom(settings.paddingBottom);
  38666. }
  38667. if (settings.padding) {
  38668. this.padding.fromString(settings.padding);
  38669. }
  38670. // Dirty layout and positioning
  38671. this._parentLayoutDirty();
  38672. this._positioningDirty();
  38673. }
  38674. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  38675. get: function () {
  38676. if (!this._actionManager) {
  38677. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  38678. }
  38679. return this._actionManager;
  38680. },
  38681. enumerable: true,
  38682. configurable: true
  38683. });
  38684. /**
  38685. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  38686. * @param predicate the predicate to test on each parent
  38687. * @return the first primitive where the predicate was successful
  38688. */
  38689. Prim2DBase.prototype.traverseUp = function (predicate) {
  38690. var p = this;
  38691. while (p != null) {
  38692. if (predicate(p)) {
  38693. return p;
  38694. }
  38695. p = p._parent;
  38696. }
  38697. return null;
  38698. };
  38699. Object.defineProperty(Prim2DBase.prototype, "owner", {
  38700. /**
  38701. * Retrieve the owner Canvas2D
  38702. */
  38703. get: function () {
  38704. return this._owner;
  38705. },
  38706. enumerable: true,
  38707. configurable: true
  38708. });
  38709. Object.defineProperty(Prim2DBase.prototype, "parent", {
  38710. /**
  38711. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  38712. */
  38713. get: function () {
  38714. return this._parent;
  38715. },
  38716. enumerable: true,
  38717. configurable: true
  38718. });
  38719. Object.defineProperty(Prim2DBase.prototype, "children", {
  38720. /**
  38721. * The array of direct children primitives
  38722. */
  38723. get: function () {
  38724. return this._children;
  38725. },
  38726. enumerable: true,
  38727. configurable: true
  38728. });
  38729. Object.defineProperty(Prim2DBase.prototype, "id", {
  38730. /**
  38731. * The identifier of this primitive, may not be unique, it's for information purpose only
  38732. */
  38733. get: function () {
  38734. return this._id;
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  38740. get: function () {
  38741. if (this._actualPosition != null) {
  38742. return this._actualPosition;
  38743. }
  38744. if (this._position != null) {
  38745. return this._position;
  38746. }
  38747. // At least return 0,0, we can't return null on actualPosition
  38748. return Prim2DBase._nullPosition;
  38749. },
  38750. /**
  38751. * DO NOT INVOKE for internal purpose only
  38752. */
  38753. set: function (val) {
  38754. this._actualPosition = val;
  38755. },
  38756. enumerable: true,
  38757. configurable: true
  38758. });
  38759. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  38760. /**
  38761. * Shortcut to actualPosition.x
  38762. */
  38763. get: function () {
  38764. return this.actualPosition.x;
  38765. },
  38766. enumerable: true,
  38767. configurable: true
  38768. });
  38769. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  38770. /**
  38771. * Shortcut to actualPosition.y
  38772. */
  38773. get: function () {
  38774. return this.actualPosition.y;
  38775. },
  38776. enumerable: true,
  38777. configurable: true
  38778. });
  38779. Object.defineProperty(Prim2DBase.prototype, "position", {
  38780. /**
  38781. * Position of the primitive, relative to its parent.
  38782. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  38783. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  38784. * Setting this property may have no effect is specific alignment are in effect.
  38785. */
  38786. get: function () {
  38787. return this._position || Prim2DBase._nullPosition;
  38788. },
  38789. set: function (value) {
  38790. if (!this._checkPositionChange()) {
  38791. return;
  38792. }
  38793. this._position = value;
  38794. this.markAsDirty("actualPosition");
  38795. },
  38796. enumerable: true,
  38797. configurable: true
  38798. });
  38799. Object.defineProperty(Prim2DBase.prototype, "x", {
  38800. /**
  38801. * Direct access to the position.x value of the primitive
  38802. * Use this property when you only want to change one component of the position property
  38803. */
  38804. get: function () {
  38805. if (!this._position) {
  38806. return null;
  38807. }
  38808. return this._position.x;
  38809. },
  38810. set: function (value) {
  38811. if (!this._checkPositionChange()) {
  38812. return;
  38813. }
  38814. if (!this._position) {
  38815. this._position = BABYLON.Vector2.Zero();
  38816. }
  38817. if (this._position.x === value) {
  38818. return;
  38819. }
  38820. this._position.x = value;
  38821. this.markAsDirty("position");
  38822. this.markAsDirty("actualPosition");
  38823. },
  38824. enumerable: true,
  38825. configurable: true
  38826. });
  38827. Object.defineProperty(Prim2DBase.prototype, "y", {
  38828. /**
  38829. * Direct access to the position.y value of the primitive
  38830. * Use this property when you only want to change one component of the position property
  38831. */
  38832. get: function () {
  38833. if (!this._position) {
  38834. return null;
  38835. }
  38836. return this._position.y;
  38837. },
  38838. set: function (value) {
  38839. if (!this._checkPositionChange()) {
  38840. return;
  38841. }
  38842. if (!this._position) {
  38843. this._position = BABYLON.Vector2.Zero();
  38844. }
  38845. if (this._position.y === value) {
  38846. return;
  38847. }
  38848. this._position.y = value;
  38849. this.markAsDirty("position");
  38850. this.markAsDirty("actualPosition");
  38851. },
  38852. enumerable: true,
  38853. configurable: true
  38854. });
  38855. Object.defineProperty(Prim2DBase.prototype, "size", {
  38856. /**
  38857. * Size of the primitive or its bounding area
  38858. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  38859. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  38860. */
  38861. get: function () {
  38862. if (!this._size || this._size.width == null || this._size.height == null) {
  38863. if (Prim2DBase.boundinbBoxReentrency) {
  38864. return Prim2DBase.nullSize;
  38865. }
  38866. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  38867. return this._boundingSize;
  38868. }
  38869. Prim2DBase.boundinbBoxReentrency = true;
  38870. var b = this.boundingInfo;
  38871. Prim2DBase.boundinbBoxReentrency = false;
  38872. return this._boundingSize;
  38873. }
  38874. return this._size;
  38875. },
  38876. set: function (value) {
  38877. this._size = value;
  38878. },
  38879. enumerable: true,
  38880. configurable: true
  38881. });
  38882. Object.defineProperty(Prim2DBase.prototype, "width", {
  38883. /**
  38884. * Direct access to the size.width value of the primitive
  38885. * Use this property when you only want to change one component of the size property
  38886. */
  38887. get: function () {
  38888. if (!this.size) {
  38889. return null;
  38890. }
  38891. return this.size.width;
  38892. },
  38893. set: function (value) {
  38894. if (!this.size) {
  38895. this.size = new BABYLON.Size(value, 0);
  38896. return;
  38897. }
  38898. if (this.size.width === value) {
  38899. return;
  38900. }
  38901. this.size.width = value;
  38902. this.markAsDirty("size");
  38903. this._positioningDirty();
  38904. },
  38905. enumerable: true,
  38906. configurable: true
  38907. });
  38908. Object.defineProperty(Prim2DBase.prototype, "height", {
  38909. /**
  38910. * Direct access to the size.height value of the primitive
  38911. * Use this property when you only want to change one component of the size property
  38912. */
  38913. get: function () {
  38914. if (!this.size) {
  38915. return null;
  38916. }
  38917. return this.size.height;
  38918. },
  38919. set: function (value) {
  38920. if (!this.size) {
  38921. this.size = new BABYLON.Size(0, value);
  38922. return;
  38923. }
  38924. if (this.size.height === value) {
  38925. return;
  38926. }
  38927. this.size.height = value;
  38928. this.markAsDirty("size");
  38929. this._positioningDirty();
  38930. },
  38931. enumerable: true,
  38932. configurable: true
  38933. });
  38934. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  38935. get: function () {
  38936. return this._rotation;
  38937. },
  38938. set: function (value) {
  38939. this._rotation = value;
  38940. },
  38941. enumerable: true,
  38942. configurable: true
  38943. });
  38944. Object.defineProperty(Prim2DBase.prototype, "scale", {
  38945. get: function () {
  38946. return this._scale;
  38947. },
  38948. set: function (value) {
  38949. this._scale = value;
  38950. },
  38951. enumerable: true,
  38952. configurable: true
  38953. });
  38954. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  38955. /**
  38956. * Return the size of the primitive as it's being rendered into the target.
  38957. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  38958. * BEWARE: don't use the setter, it's for internal purpose only
  38959. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  38960. */
  38961. get: function () {
  38962. if (this._actualSize) {
  38963. return this._actualSize;
  38964. }
  38965. return this._size;
  38966. },
  38967. set: function (value) {
  38968. if (this._actualSize.equals(value)) {
  38969. return;
  38970. }
  38971. this._actualSize = value;
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  38977. get: function () {
  38978. if (this._manualZOrder != null) {
  38979. return this._manualZOrder;
  38980. }
  38981. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  38982. this._updateZOrder();
  38983. }
  38984. return (1 - this._zOrder);
  38985. },
  38986. enumerable: true,
  38987. configurable: true
  38988. });
  38989. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  38990. /**
  38991. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  38992. * The Primitive's size won't be less than specified.
  38993. * The default value depends of the Primitive type
  38994. */
  38995. get: function () {
  38996. return this._minSize;
  38997. },
  38998. set: function (value) {
  38999. if (this._minSize && value && this._minSize.equals(value)) {
  39000. return;
  39001. }
  39002. this._minSize = value;
  39003. this._parentLayoutDirty();
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  39009. /**
  39010. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  39011. * The Primitive's size won't be more than specified.
  39012. * The default value depends of the Primitive type
  39013. */
  39014. get: function () {
  39015. return this._maxSize;
  39016. },
  39017. set: function (value) {
  39018. if (this._maxSize && value && this._maxSize.equals(value)) {
  39019. return;
  39020. }
  39021. this._maxSize = value;
  39022. this._parentLayoutDirty();
  39023. },
  39024. enumerable: true,
  39025. configurable: true
  39026. });
  39027. Object.defineProperty(Prim2DBase.prototype, "origin", {
  39028. /**
  39029. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  39030. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  39031. * For instance:
  39032. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  39033. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  39034. * 0,1 means the center is top/left
  39035. * @returns The normalized center.
  39036. */
  39037. get: function () {
  39038. return this._origin;
  39039. },
  39040. set: function (value) {
  39041. this._origin = value;
  39042. },
  39043. enumerable: true,
  39044. configurable: true
  39045. });
  39046. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  39047. get: function () {
  39048. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  39049. },
  39050. set: function (value) {
  39051. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  39052. },
  39053. enumerable: true,
  39054. configurable: true
  39055. });
  39056. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  39057. get: function () {
  39058. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  39059. },
  39060. set: function (value) {
  39061. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  39062. },
  39063. enumerable: true,
  39064. configurable: true
  39065. });
  39066. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  39067. get: function () {
  39068. return this._manualZOrder;
  39069. },
  39070. set: function (value) {
  39071. if (this._manualZOrder === value) {
  39072. return;
  39073. }
  39074. this._manualZOrder = value;
  39075. this.onZOrderChanged();
  39076. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  39077. this._actualZOrderChangedObservable.notifyObservers(value);
  39078. }
  39079. },
  39080. enumerable: true,
  39081. configurable: true
  39082. });
  39083. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  39084. get: function () {
  39085. return this._manualZOrder != null;
  39086. },
  39087. enumerable: true,
  39088. configurable: true
  39089. });
  39090. Object.defineProperty(Prim2DBase.prototype, "margin", {
  39091. get: function () {
  39092. var _this = this;
  39093. if (!this._margin) {
  39094. this._margin = new PrimitiveThickness(function () {
  39095. if (!_this.parent) {
  39096. return null;
  39097. }
  39098. return _this.parent.margin;
  39099. }, function () { return _this._positioningDirty(); });
  39100. }
  39101. return this._margin;
  39102. },
  39103. enumerable: true,
  39104. configurable: true
  39105. });
  39106. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  39107. get: function () {
  39108. return (this._margin !== null) || (this._marginAlignment !== null);
  39109. },
  39110. enumerable: true,
  39111. configurable: true
  39112. });
  39113. Object.defineProperty(Prim2DBase.prototype, "padding", {
  39114. get: function () {
  39115. var _this = this;
  39116. if (!this._padding) {
  39117. this._padding = new PrimitiveThickness(function () {
  39118. if (!_this.parent) {
  39119. return null;
  39120. }
  39121. return _this.parent.padding;
  39122. }, function () { return _this._positioningDirty(); });
  39123. }
  39124. return this._padding;
  39125. },
  39126. enumerable: true,
  39127. configurable: true
  39128. });
  39129. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  39130. get: function () {
  39131. return this._padding !== null;
  39132. },
  39133. enumerable: true,
  39134. configurable: true
  39135. });
  39136. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  39137. get: function () {
  39138. var _this = this;
  39139. if (!this._marginAlignment) {
  39140. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  39141. }
  39142. return this._marginAlignment;
  39143. },
  39144. enumerable: true,
  39145. configurable: true
  39146. });
  39147. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  39148. get: function () {
  39149. return this._opacity;
  39150. },
  39151. set: function (value) {
  39152. if (value < 0) {
  39153. value = 0;
  39154. }
  39155. else if (value > 1) {
  39156. value = 1;
  39157. }
  39158. if (this._opacity === value) {
  39159. return;
  39160. }
  39161. this._opacity = value;
  39162. this._updateRenderMode();
  39163. this._spreadActualOpacityChanged();
  39164. },
  39165. enumerable: true,
  39166. configurable: true
  39167. });
  39168. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  39169. get: function () {
  39170. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  39171. var cur = this.parent;
  39172. var op = this.opacity;
  39173. while (cur) {
  39174. op *= cur.opacity;
  39175. cur = cur.parent;
  39176. }
  39177. this._actualOpacity = op;
  39178. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39179. }
  39180. return this._actualOpacity;
  39181. },
  39182. enumerable: true,
  39183. configurable: true
  39184. });
  39185. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  39186. /**
  39187. * Get/set the layout engine to use for this primitive.
  39188. * The default layout engine is the CanvasLayoutEngine.
  39189. */
  39190. get: function () {
  39191. if (!this._layoutEngine) {
  39192. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39193. }
  39194. return this._layoutEngine;
  39195. },
  39196. set: function (value) {
  39197. if (this._layoutEngine === value) {
  39198. return;
  39199. }
  39200. this._changeLayoutEngine(value);
  39201. },
  39202. enumerable: true,
  39203. configurable: true
  39204. });
  39205. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  39206. /**
  39207. * Get/set the layout are of this primitive.
  39208. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  39209. * The setter should only be called by a Layout Engine class.
  39210. */
  39211. get: function () {
  39212. return this._layoutArea;
  39213. },
  39214. set: function (val) {
  39215. if (this._layoutArea.equals(val)) {
  39216. return;
  39217. }
  39218. this._positioningDirty();
  39219. this._layoutArea = val;
  39220. },
  39221. enumerable: true,
  39222. configurable: true
  39223. });
  39224. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  39225. /**
  39226. * Get/set the layout area position (relative to the parent primitive).
  39227. * The setter should only be called by a Layout Engine class.
  39228. */
  39229. get: function () {
  39230. return this._layoutAreaPos;
  39231. },
  39232. set: function (val) {
  39233. if (this._layoutAreaPos.equals(val)) {
  39234. return;
  39235. }
  39236. this._positioningDirty();
  39237. this._layoutAreaPos = val;
  39238. },
  39239. enumerable: true,
  39240. configurable: true
  39241. });
  39242. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  39243. /**
  39244. * Define if the Primitive can be subject to intersection test or not (default is true)
  39245. */
  39246. get: function () {
  39247. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  39248. },
  39249. set: function (value) {
  39250. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  39251. },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  39256. /**
  39257. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  39258. */
  39259. get: function () {
  39260. return this._hierarchyDepth;
  39261. },
  39262. enumerable: true,
  39263. configurable: true
  39264. });
  39265. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  39266. /**
  39267. * Retrieve the Group that is responsible to render this primitive
  39268. */
  39269. get: function () {
  39270. return this._renderGroup;
  39271. },
  39272. enumerable: true,
  39273. configurable: true
  39274. });
  39275. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  39276. /**
  39277. * Get the global transformation matrix of the primitive
  39278. */
  39279. get: function () {
  39280. return this._globalTransform;
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. /**
  39286. * return the global position of the primitive, relative to its canvas
  39287. */
  39288. Prim2DBase.prototype.getGlobalPosition = function () {
  39289. var v = new BABYLON.Vector2(0, 0);
  39290. this.getGlobalPositionByRef(v);
  39291. return v;
  39292. };
  39293. /**
  39294. * return the global position of the primitive, relative to its canvas
  39295. * @param v the valid Vector2 object where the global position will be stored
  39296. */
  39297. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  39298. v.x = this.globalTransform.m[12];
  39299. v.y = this.globalTransform.m[13];
  39300. };
  39301. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  39302. /**
  39303. * Get invert of the global transformation matrix of the primitive
  39304. */
  39305. get: function () {
  39306. return this._invGlobalTransform;
  39307. },
  39308. enumerable: true,
  39309. configurable: true
  39310. });
  39311. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  39312. /**
  39313. * Get the local transformation of the primitive
  39314. */
  39315. get: function () {
  39316. this._updateLocalTransform();
  39317. return this._localTransform;
  39318. },
  39319. enumerable: true,
  39320. configurable: true
  39321. });
  39322. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  39323. /**
  39324. * Get the boundingInfo associated to the primitive and its children.
  39325. * The value is supposed to be always up to date
  39326. */
  39327. get: function () {
  39328. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39329. if (this.owner) {
  39330. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  39331. }
  39332. if (this.isSizedByContent) {
  39333. this._boundingInfo.clear();
  39334. }
  39335. else {
  39336. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  39337. }
  39338. var bi = this._boundingInfo;
  39339. var tps = new BABYLON.BoundingInfo2D();
  39340. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39341. var curChild = _a[_i];
  39342. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  39343. bi.unionToRef(tps, bi);
  39344. }
  39345. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  39346. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  39347. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  39348. }
  39349. return this._boundingInfo;
  39350. },
  39351. enumerable: true,
  39352. configurable: true
  39353. });
  39354. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  39355. /**
  39356. * Determine if the size is automatically computed or fixed because manually specified.
  39357. * Use the actualSize property to get the final/real size of the primitive
  39358. * @returns true if the size is automatically computed, false if it were manually specified.
  39359. */
  39360. get: function () {
  39361. return this._size == null;
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  39367. /**
  39368. * Return true if this prim has an auto size which is set by the children's global bounding box
  39369. */
  39370. get: function () {
  39371. return (this._size == null) && (this._children.length > 0);
  39372. },
  39373. enumerable: true,
  39374. configurable: true
  39375. });
  39376. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  39377. /**
  39378. * Determine if the position is automatically computed or fixed because manually specified.
  39379. * Use the actualPosition property to get the final/real position of the primitive
  39380. * @returns true if the position is automatically computed, false if it were manually specified.
  39381. */
  39382. get: function () {
  39383. return this._position == null;
  39384. },
  39385. enumerable: true,
  39386. configurable: true
  39387. });
  39388. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  39389. /**
  39390. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  39391. */
  39392. get: function () {
  39393. return this._pointerEventObservable;
  39394. },
  39395. enumerable: true,
  39396. configurable: true
  39397. });
  39398. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  39399. get: function () {
  39400. if (!this._actualZOrderChangedObservable) {
  39401. this._actualZOrderChangedObservable = new BABYLON.Observable();
  39402. }
  39403. return this._actualZOrderChangedObservable;
  39404. },
  39405. enumerable: true,
  39406. configurable: true
  39407. });
  39408. Prim2DBase.prototype.findById = function (id) {
  39409. if (this._id === id) {
  39410. return this;
  39411. }
  39412. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39413. var child = _a[_i];
  39414. var r = child.findById(id);
  39415. if (r != null) {
  39416. return r;
  39417. }
  39418. }
  39419. };
  39420. Prim2DBase.prototype.onZOrderChanged = function () {
  39421. };
  39422. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  39423. return false;
  39424. };
  39425. /**
  39426. * Capture all the Events of the given PointerId for this primitive.
  39427. * Don't forget to call releasePointerEventsCapture when done.
  39428. * @param pointerId the Id of the pointer to capture the events from.
  39429. */
  39430. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  39431. return this.owner._setPointerCapture(pointerId, this);
  39432. };
  39433. /**
  39434. * Release a captured pointer made with setPointerEventCapture.
  39435. * @param pointerId the Id of the pointer to release the capture from.
  39436. */
  39437. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  39438. return this.owner._releasePointerCapture(pointerId, this);
  39439. };
  39440. /**
  39441. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  39442. * @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.
  39443. */
  39444. Prim2DBase.prototype.intersect = function (intersectInfo) {
  39445. if (!intersectInfo) {
  39446. return false;
  39447. }
  39448. // If this is null it means this method is call for the first level, initialize stuffs
  39449. var firstLevel = !intersectInfo._globalPickPosition;
  39450. if (firstLevel) {
  39451. // 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).
  39452. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  39453. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  39454. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  39455. intersectInfo.intersectedPrimitives = new Array();
  39456. intersectInfo.topMostIntersectedPrimitive = null;
  39457. }
  39458. if (!intersectInfo.intersectHidden && !this.isVisible) {
  39459. return false;
  39460. }
  39461. // Fast rejection test with boundingInfo
  39462. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  39463. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  39464. intersectInfo._exit(firstLevel);
  39465. return false;
  39466. }
  39467. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  39468. var levelIntersectRes = false;
  39469. if (this.isPickable) {
  39470. levelIntersectRes = this.levelIntersect(intersectInfo);
  39471. if (levelIntersectRes) {
  39472. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  39473. intersectInfo.intersectedPrimitives.push(pii);
  39474. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  39475. intersectInfo.topMostIntersectedPrimitive = pii;
  39476. }
  39477. // If we must stop at the first intersection, we're done, quit!
  39478. if (intersectInfo.findFirstOnly) {
  39479. intersectInfo._exit(firstLevel);
  39480. return true;
  39481. }
  39482. }
  39483. }
  39484. // Recurse to children if needed
  39485. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  39486. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39487. var curChild = _a[_i];
  39488. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  39489. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  39490. continue;
  39491. }
  39492. // Must compute the localPickLocation for the children level
  39493. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  39494. // If we got an intersection with the child and we only need to find the first one, quit!
  39495. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  39496. intersectInfo._exit(firstLevel);
  39497. return true;
  39498. }
  39499. }
  39500. }
  39501. intersectInfo._exit(firstLevel);
  39502. return intersectInfo.isIntersected;
  39503. };
  39504. Prim2DBase.prototype.moveChild = function (child, previous) {
  39505. if (child.parent !== this) {
  39506. return false;
  39507. }
  39508. var childIndex = this._children.indexOf(child);
  39509. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  39510. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  39511. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39512. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  39513. }
  39514. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  39515. };
  39516. Prim2DBase.prototype.addChild = function (child) {
  39517. child._parent = this;
  39518. this._boundingBoxDirty();
  39519. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39520. if (flat) {
  39521. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39522. child._setZOrder(this._zOrder, true);
  39523. child._zMax = this._zOrder;
  39524. }
  39525. else {
  39526. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39527. }
  39528. var length = this._children.push(child);
  39529. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  39530. };
  39531. /**
  39532. * Dispose the primitive, remove it from its parent.
  39533. */
  39534. Prim2DBase.prototype.dispose = function () {
  39535. if (!_super.prototype.dispose.call(this)) {
  39536. return false;
  39537. }
  39538. if (this._actionManager) {
  39539. this._actionManager.dispose();
  39540. this._actionManager = null;
  39541. }
  39542. // If there's a parent, remove this object from its parent list
  39543. if (this._parent) {
  39544. var i = this._parent._children.indexOf(this);
  39545. if (i !== undefined) {
  39546. this._parent._children.splice(i, 1);
  39547. }
  39548. this._parent = null;
  39549. }
  39550. // Recurse dispose to children
  39551. if (this._children) {
  39552. while (this._children.length > 0) {
  39553. this._children[this._children.length - 1].dispose();
  39554. }
  39555. }
  39556. return true;
  39557. };
  39558. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  39559. if (this._renderGroup) {
  39560. this._renderGroup._addPrimToDirtyList(this);
  39561. }
  39562. };
  39563. Prim2DBase.prototype._needPrepare = function () {
  39564. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  39565. };
  39566. Prim2DBase.prototype._prepareRender = function (context) {
  39567. this._prepareRenderPre(context);
  39568. this._prepareRenderPost(context);
  39569. };
  39570. Prim2DBase.prototype._prepareRenderPre = function (context) {
  39571. };
  39572. Prim2DBase.prototype._prepareRenderPost = function (context) {
  39573. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  39574. if (this instanceof BABYLON.Group2D) {
  39575. var self = this;
  39576. if (self.isRenderableGroup) {
  39577. return;
  39578. }
  39579. }
  39580. // Check if we need to recurse the prepare to children primitives
  39581. // - must have children
  39582. // - the global transform of this level have changed, or
  39583. // - the visible state of primitive has changed
  39584. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  39585. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  39586. this._children.forEach(function (c) {
  39587. // As usual stop the recursion if we meet a renderable group
  39588. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  39589. c._prepareRender(context);
  39590. }
  39591. });
  39592. }
  39593. // Finally reset the dirty flags as we've processed everything
  39594. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39595. this._instanceDirtyFlags = 0;
  39596. };
  39597. Prim2DBase.prototype._canvasPreInit = function (settings) {
  39598. };
  39599. Prim2DBase.CheckParent = function (parent) {
  39600. //if (!Prim2DBase._isCanvasInit && !parent) {
  39601. // 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)");
  39602. //}
  39603. };
  39604. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  39605. for (var _i = 0; _i < list.length; _i++) {
  39606. var cur = list[_i];
  39607. cur.updateCachedStates(recurse);
  39608. }
  39609. };
  39610. Prim2DBase.prototype._parentLayoutDirty = function () {
  39611. if (!this._parent || this._parent.isDisposed) {
  39612. return;
  39613. }
  39614. this._parent._setLayoutDirty();
  39615. };
  39616. Prim2DBase.prototype._setLayoutDirty = function () {
  39617. if (!this.isDirty) {
  39618. this.onPrimBecomesDirty();
  39619. }
  39620. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39621. };
  39622. Prim2DBase.prototype._checkPositionChange = function () {
  39623. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  39624. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  39625. return false;
  39626. }
  39627. return true;
  39628. };
  39629. Prim2DBase.prototype._positioningDirty = function () {
  39630. if (!this.isDirty) {
  39631. this.onPrimBecomesDirty();
  39632. }
  39633. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39634. };
  39635. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  39636. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39637. var child = _a[_i];
  39638. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39639. child._spreadActualOpacityChanged();
  39640. }
  39641. };
  39642. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  39643. this._layoutEngine = engine;
  39644. };
  39645. Prim2DBase.prototype._updateLocalTransform = function () {
  39646. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  39647. if (this.checkPropertiesDirty(tflags)) {
  39648. if (this.owner) {
  39649. this.owner.addupdateLocalTransformCounter(1);
  39650. }
  39651. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  39652. var local;
  39653. var pos = this.position;
  39654. if (this._origin.x === 0 && this._origin.y === 0) {
  39655. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  39656. this._localTransform = local;
  39657. }
  39658. else {
  39659. // -Origin offset
  39660. var as = this.actualSize;
  39661. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  39662. // -Origin * rotation
  39663. rot.toRotationMatrix(Prim2DBase._t1);
  39664. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  39665. // -Origin * rotation * scale
  39666. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  39667. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  39668. // -Origin * rotation * scale * (Origin + Position)
  39669. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  39670. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  39671. }
  39672. this.clearPropertiesDirty(tflags);
  39673. return true;
  39674. }
  39675. return false;
  39676. };
  39677. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  39678. if (this.isDisposed) {
  39679. return;
  39680. }
  39681. this.owner.addCachedGroupRenderCounter(1);
  39682. // Check if the parent is synced
  39683. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  39684. this._parent.updateCachedStates(false);
  39685. }
  39686. // Update Z-Order if needed
  39687. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39688. this._updateZOrder();
  39689. }
  39690. // Update actualSize only if there' not positioning to recompute and the size changed
  39691. // Otherwise positioning will take care of it.
  39692. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39693. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  39694. var size = this.size;
  39695. if (size) {
  39696. if (this.size.width != null) {
  39697. this.actualSize.width = this.size.width;
  39698. }
  39699. if (this.size.height != null) {
  39700. this.actualSize.height = this.size.height;
  39701. }
  39702. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39703. }
  39704. }
  39705. // Check for layout update
  39706. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39707. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  39708. this.owner.addUpdateLayoutCounter(1);
  39709. this._layoutEngine.updateLayout(this);
  39710. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39711. }
  39712. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39713. var autoContentChanged = false;
  39714. if (this.isSizeAuto) {
  39715. if (!this._lastAutoSizeArea) {
  39716. autoContentChanged = this.size !== null;
  39717. }
  39718. else {
  39719. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  39720. }
  39721. }
  39722. // Check for positioning update
  39723. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  39724. this._updatePositioning();
  39725. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39726. if (sizeDirty) {
  39727. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39728. }
  39729. positioningComputed = true;
  39730. }
  39731. if (positioningComputed && this._parent) {
  39732. this._parentContentArea.copyFrom(this._parent.contentArea);
  39733. }
  39734. // Check if we must update this prim
  39735. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  39736. this.owner.addUpdateGlobalTransformCounter(1);
  39737. var curVisibleState = this.isVisible;
  39738. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  39739. // Detect a change of visibility
  39740. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  39741. // Get/compute the localTransform
  39742. var localDirty = this._updateLocalTransform();
  39743. var parentPaddingChanged = false;
  39744. var parentPaddingOffset = Prim2DBase._v0;
  39745. if (this._parent) {
  39746. parentPaddingOffset = this._parent._paddingOffset;
  39747. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  39748. }
  39749. // Check if there are changes in the parent that will force us to update the global matrix
  39750. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  39751. // Check if we have to update the globalTransform
  39752. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  39753. var globalTransform = this._parent ? this._parent._globalTransform : null;
  39754. var localTransform;
  39755. Prim2DBase._transMtx.copyFrom(this._localTransform);
  39756. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  39757. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  39758. localTransform = Prim2DBase._transMtx;
  39759. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  39760. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  39761. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  39762. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  39763. }
  39764. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  39765. }
  39766. if (recurse) {
  39767. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39768. var child = _a[_i];
  39769. // Stop the recursion if we meet a renderable group
  39770. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  39771. }
  39772. }
  39773. };
  39774. Prim2DBase.prototype._updatePositioning = function () {
  39775. if (this.owner) {
  39776. this.owner.addUpdatePositioningCounter(1);
  39777. }
  39778. // From this point we assume that the primitive layoutArea is computed and up to date.
  39779. // We know have to :
  39780. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  39781. // 2. Determine the contentArea based on the padding property.
  39782. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  39783. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  39784. if (this.actualSize.width == null) {
  39785. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  39786. }
  39787. if (this.actualSize.height == null) {
  39788. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  39789. }
  39790. }
  39791. // Apply margin
  39792. if (this._hasMargin) {
  39793. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  39794. this.actualSize = Prim2DBase._size.clone();
  39795. }
  39796. var isSizeAuto = this.isSizeAuto;
  39797. if (this._hasPadding) {
  39798. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  39799. if (isSizeAuto) {
  39800. var content = this.size.clone();
  39801. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  39802. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  39803. this._contentArea.copyFrom(content);
  39804. this.actualSize = Prim2DBase._size.clone();
  39805. // Changing the padding has resize the prim, which forces us to recompute margin again
  39806. if (this._hasMargin) {
  39807. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  39808. }
  39809. }
  39810. else {
  39811. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39812. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39813. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39814. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  39815. this._paddingOffset.x += Prim2DBase._icPos.x;
  39816. this._paddingOffset.y += Prim2DBase._icPos.y;
  39817. this._contentArea.copyFrom(Prim2DBase._size);
  39818. }
  39819. }
  39820. else {
  39821. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  39822. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  39823. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  39824. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  39825. this._contentArea.copyFrom(Prim2DBase._icArea);
  39826. }
  39827. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  39828. this.actualPosition = aPos;
  39829. if (isSizeAuto) {
  39830. this._lastAutoSizeArea = this.size;
  39831. }
  39832. };
  39833. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  39834. /**
  39835. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  39836. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  39837. */
  39838. get: function () {
  39839. // Check for positioning update
  39840. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  39841. this._updatePositioning();
  39842. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39843. }
  39844. return this._contentArea;
  39845. },
  39846. enumerable: true,
  39847. configurable: true
  39848. });
  39849. Prim2DBase.prototype._patchHierarchy = function (owner) {
  39850. this._owner = owner;
  39851. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  39852. if (this._renderGroup != null) {
  39853. return;
  39854. }
  39855. if (this instanceof BABYLON.Group2D) {
  39856. var group = this;
  39857. group.detectGroupStates();
  39858. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  39859. group.owner._registerTrackedNode(this);
  39860. }
  39861. }
  39862. if (this._parent) {
  39863. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  39864. this._parentLayoutDirty();
  39865. }
  39866. // Make sure the prim is in the dirtyList if it should be
  39867. if (this._renderGroup && this.isDirty) {
  39868. var list = this._renderGroup._renderableData._primDirtyList;
  39869. var i = list.indexOf(this);
  39870. if (i === -1) {
  39871. list.push(this);
  39872. }
  39873. }
  39874. // Recurse
  39875. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39876. var child = _a[_i];
  39877. child._hierarchyDepth = this._hierarchyDepth + 1;
  39878. child._patchHierarchy(owner);
  39879. }
  39880. };
  39881. Prim2DBase.prototype._updateZOrder = function () {
  39882. var prevLinPos = this._primLinearPosition;
  39883. var startI = 0;
  39884. var startZ = this._zOrder;
  39885. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  39886. var childrenCount = this._children.length;
  39887. if (this._firstZDirtyIndex > 0) {
  39888. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  39889. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  39890. prevLinPos = prevPrim._primLinearPosition;
  39891. startI = this._firstZDirtyIndex - 1;
  39892. startZ = prevPrim._zOrder;
  39893. }
  39894. }
  39895. var startPos = prevLinPos;
  39896. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  39897. Prim2DBase._totalCount = 0;
  39898. for (var i = startI; i < childrenCount; i++) {
  39899. var child = this._children[i];
  39900. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  39901. }
  39902. // Compute the new Z-Order for all the primitives
  39903. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  39904. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  39905. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  39906. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  39907. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  39908. if (Prim2DBase._zRebuildReentrency) {
  39909. var p = this._parent;
  39910. if (p == null) {
  39911. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  39912. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  39913. Prim2DBase._zRebuildReentrency = false;
  39914. return;
  39915. }
  39916. p._firstZDirtyIndex = 0;
  39917. return p._updateZOrder();
  39918. }
  39919. Prim2DBase._zRebuildReentrency = true;
  39920. this._firstZDirtyIndex = 0;
  39921. this._updateZOrder();
  39922. Prim2DBase._zRebuildReentrency = false;
  39923. }
  39924. for (var i = startI; i < childrenCount; i++) {
  39925. var child = this._children[i];
  39926. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  39927. }
  39928. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  39929. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  39930. var p = _a[_i];
  39931. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  39932. }
  39933. Prim2DBase._zOrderChangedNotifList.splice(0);
  39934. this._firstZDirtyIndex = Prim2DBase._bigInt;
  39935. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39936. };
  39937. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  39938. if (this.isManualZOrder) {
  39939. return prevLinPos;
  39940. }
  39941. this._primLinearPosition = ++prevLinPos;
  39942. Prim2DBase._totalCount++;
  39943. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  39944. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  39945. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39946. var child = _a[_i];
  39947. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  39948. }
  39949. }
  39950. return prevLinPos;
  39951. };
  39952. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  39953. if (this.isManualZOrder) {
  39954. return null;
  39955. }
  39956. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  39957. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39958. this._setZOrder(newZ, false);
  39959. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39960. this._firstZDirtyIndex = Prim2DBase._bigInt;
  39961. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39962. }
  39963. var curZ = newZ;
  39964. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  39965. if (isFlat) {
  39966. if (this._children.length > 0) {
  39967. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  39968. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39969. var child = _a[_i];
  39970. child._updatePrimitiveFlatZOrder(this._zOrder);
  39971. }
  39972. }
  39973. }
  39974. else {
  39975. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  39976. var child = _c[_b];
  39977. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  39978. if (r != null) {
  39979. curZ = r;
  39980. }
  39981. }
  39982. }
  39983. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  39984. return curZ;
  39985. };
  39986. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  39987. if (this.isManualZOrder) {
  39988. return;
  39989. }
  39990. this._setZOrder(newZ, false);
  39991. this._zMax = newZ;
  39992. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39993. this._firstZDirtyIndex = Prim2DBase._bigInt;
  39994. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39995. }
  39996. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39997. var child = _a[_i];
  39998. child._updatePrimitiveFlatZOrder(newZ);
  39999. }
  40000. };
  40001. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  40002. if (newZ !== this._zOrder) {
  40003. this._zOrder = newZ;
  40004. if (!this.isDirty) {
  40005. this.onPrimBecomesDirty();
  40006. }
  40007. this.onZOrderChanged();
  40008. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40009. if (directEmit) {
  40010. this._actualZOrderChangedObservable.notifyObservers(newZ);
  40011. }
  40012. else {
  40013. Prim2DBase._zOrderChangedNotifList.push(this);
  40014. }
  40015. }
  40016. }
  40017. };
  40018. Prim2DBase.prototype._updateRenderMode = function () {
  40019. };
  40020. /**
  40021. * This method is used to alter the contentArea of the Primitive before margin is applied.
  40022. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  40023. * @param primSize the current size of the primitive
  40024. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  40025. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  40026. */
  40027. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  40028. initialContentArea.copyFrom(primSize);
  40029. initialContentPosition.x = initialContentPosition.y = 0;
  40030. };
  40031. /**
  40032. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  40033. * Check the Rectangle2D implementation for a concrete application.
  40034. * @param primSize the current size of the primitive
  40035. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  40036. */
  40037. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  40038. newPrimSize.copyFrom(primSize);
  40039. };
  40040. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  40041. Prim2DBase._bigInt = Math.pow(2, 30);
  40042. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  40043. Prim2DBase.boundinbBoxReentrency = false;
  40044. Prim2DBase.nullSize = BABYLON.Size.Zero();
  40045. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  40046. Prim2DBase._isCanvasInit = false;
  40047. Prim2DBase._t0 = new BABYLON.Matrix();
  40048. Prim2DBase._t1 = new BABYLON.Matrix();
  40049. Prim2DBase._t2 = new BABYLON.Matrix();
  40050. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  40051. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  40052. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  40053. Prim2DBase._icArea = BABYLON.Size.Zero();
  40054. Prim2DBase._size = BABYLON.Size.Zero();
  40055. Prim2DBase._zOrderChangedNotifList = new Array();
  40056. Prim2DBase._zRebuildReentrency = false;
  40057. Prim2DBase._totalCount = 0;
  40058. __decorate([
  40059. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  40060. ], Prim2DBase.prototype, "actualPosition", null);
  40061. __decorate([
  40062. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  40063. ], Prim2DBase.prototype, "position", null);
  40064. __decorate([
  40065. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  40066. ], Prim2DBase.prototype, "size", null);
  40067. __decorate([
  40068. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  40069. ], Prim2DBase.prototype, "rotation", null);
  40070. __decorate([
  40071. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  40072. ], Prim2DBase.prototype, "scale", null);
  40073. __decorate([
  40074. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  40075. ], Prim2DBase.prototype, "origin", null);
  40076. __decorate([
  40077. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  40078. ], Prim2DBase.prototype, "levelVisible", null);
  40079. __decorate([
  40080. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  40081. ], Prim2DBase.prototype, "isVisible", null);
  40082. __decorate([
  40083. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  40084. ], Prim2DBase.prototype, "zOrder", null);
  40085. __decorate([
  40086. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  40087. ], Prim2DBase.prototype, "margin", null);
  40088. __decorate([
  40089. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  40090. ], Prim2DBase.prototype, "padding", null);
  40091. __decorate([
  40092. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  40093. ], Prim2DBase.prototype, "marginAlignment", null);
  40094. __decorate([
  40095. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  40096. ], Prim2DBase.prototype, "opacity", null);
  40097. Prim2DBase = __decorate([
  40098. BABYLON.className("Prim2DBase")
  40099. ], Prim2DBase);
  40100. return Prim2DBase;
  40101. })(BABYLON.SmartPropertyPrim);
  40102. BABYLON.Prim2DBase = Prim2DBase;
  40103. })(BABYLON || (BABYLON = {}));
  40104. var BABYLON;
  40105. (function (BABYLON) {
  40106. var GroupInstanceInfo = (function () {
  40107. function GroupInstanceInfo(owner, mrc, partCount) {
  40108. this._partCount = partCount;
  40109. this.owner = owner;
  40110. this.modelRenderCache = mrc;
  40111. this.modelRenderCache.addRef();
  40112. this.partIndexFromId = new BABYLON.StringDictionary();
  40113. this._usedShaderCategories = new Array(partCount);
  40114. this._strides = new Array(partCount);
  40115. this._opaqueData = null;
  40116. this._alphaTestData = null;
  40117. this._transparentData = null;
  40118. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  40119. }
  40120. GroupInstanceInfo.prototype.dispose = function () {
  40121. if (this._isDisposed) {
  40122. return false;
  40123. }
  40124. if (this.modelRenderCache) {
  40125. this.modelRenderCache.dispose();
  40126. }
  40127. var engine = this.owner.owner.engine;
  40128. if (this.opaqueData) {
  40129. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  40130. this.opaqueData = null;
  40131. }
  40132. this.partIndexFromId = null;
  40133. this._isDisposed = true;
  40134. return true;
  40135. };
  40136. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  40137. get: function () {
  40138. return this._opaqueData != null;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  40144. get: function () {
  40145. return this._alphaTestData != null;
  40146. },
  40147. enumerable: true,
  40148. configurable: true
  40149. });
  40150. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  40151. get: function () {
  40152. return this._transparentData != null;
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  40158. get: function () {
  40159. if (!this._opaqueData) {
  40160. this._opaqueData = new Array(this._partCount);
  40161. for (var i = 0; i < this._partCount; i++) {
  40162. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  40163. }
  40164. }
  40165. return this._opaqueData;
  40166. },
  40167. enumerable: true,
  40168. configurable: true
  40169. });
  40170. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  40171. get: function () {
  40172. if (!this._alphaTestData) {
  40173. this._alphaTestData = new Array(this._partCount);
  40174. for (var i = 0; i < this._partCount; i++) {
  40175. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  40176. }
  40177. }
  40178. return this._alphaTestData;
  40179. },
  40180. enumerable: true,
  40181. configurable: true
  40182. });
  40183. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  40184. get: function () {
  40185. if (!this._transparentData) {
  40186. this._transparentData = new Array(this._partCount);
  40187. for (var i = 0; i < this._partCount; i++) {
  40188. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  40189. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  40190. }
  40191. }
  40192. return this._transparentData;
  40193. },
  40194. enumerable: true,
  40195. configurable: true
  40196. });
  40197. GroupInstanceInfo.prototype.sortTransparentData = function () {
  40198. if (!this.transparentOrderDirty) {
  40199. return;
  40200. }
  40201. for (var i = 0; i < this._transparentData.length; i++) {
  40202. var td = this._transparentData[i];
  40203. td._partData.sort();
  40204. }
  40205. this.transparentOrderDirty = false;
  40206. };
  40207. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  40208. get: function () {
  40209. return this._usedShaderCategories;
  40210. },
  40211. enumerable: true,
  40212. configurable: true
  40213. });
  40214. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  40215. get: function () {
  40216. return this._strides;
  40217. },
  40218. enumerable: true,
  40219. configurable: true
  40220. });
  40221. return GroupInstanceInfo;
  40222. })();
  40223. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  40224. var TransparentSegment = (function () {
  40225. function TransparentSegment() {
  40226. this.groupInsanceInfo = null;
  40227. this.startZ = 0;
  40228. this.endZ = 0;
  40229. this.startDataIndex = 0;
  40230. this.endDataIndex = 0;
  40231. this.partBuffers = null;
  40232. }
  40233. TransparentSegment.prototype.dispose = function (engine) {
  40234. if (this.partBuffers) {
  40235. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  40236. this.partBuffers.splice(0);
  40237. this.partBuffers = null;
  40238. }
  40239. };
  40240. return TransparentSegment;
  40241. })();
  40242. BABYLON.TransparentSegment = TransparentSegment;
  40243. var GroupInfoPartData = (function () {
  40244. function GroupInfoPartData(stride) {
  40245. this._partData = null;
  40246. this._partBuffer = null;
  40247. this._partBufferSize = 0;
  40248. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  40249. this._isDisposed = false;
  40250. }
  40251. GroupInfoPartData.prototype.dispose = function (engine) {
  40252. if (this._isDisposed) {
  40253. return false;
  40254. }
  40255. if (this._partBuffer) {
  40256. engine._releaseBuffer(this._partBuffer);
  40257. this._partBuffer = null;
  40258. }
  40259. this._partData = null;
  40260. this._isDisposed = true;
  40261. };
  40262. return GroupInfoPartData;
  40263. })();
  40264. BABYLON.GroupInfoPartData = GroupInfoPartData;
  40265. var TransparentGroupInfoPartData = (function (_super) {
  40266. __extends(TransparentGroupInfoPartData, _super);
  40267. function TransparentGroupInfoPartData(stride, zoff) {
  40268. _super.call(this, stride);
  40269. this._partData.compareValueOffset = zoff;
  40270. this._partData.sortingAscending = false;
  40271. }
  40272. return TransparentGroupInfoPartData;
  40273. })(GroupInfoPartData);
  40274. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  40275. var ModelRenderCache = (function () {
  40276. function ModelRenderCache(engine, modelKey) {
  40277. this._engine = engine;
  40278. this._modelKey = modelKey;
  40279. this._nextKey = 1;
  40280. this._refCounter = 1;
  40281. this._instancesData = new BABYLON.StringDictionary();
  40282. this._partData = null;
  40283. }
  40284. ModelRenderCache.prototype.dispose = function () {
  40285. if (--this._refCounter !== 0) {
  40286. return false;
  40287. }
  40288. // Remove the Model Render Cache from the global dictionary
  40289. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  40290. if (edata) {
  40291. edata.DisposeModelRenderCache(this);
  40292. }
  40293. return true;
  40294. };
  40295. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  40296. get: function () {
  40297. return this._refCounter <= 0;
  40298. },
  40299. enumerable: true,
  40300. configurable: true
  40301. });
  40302. ModelRenderCache.prototype.addRef = function () {
  40303. return ++this._refCounter;
  40304. };
  40305. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  40306. get: function () {
  40307. return this._modelKey;
  40308. },
  40309. enumerable: true,
  40310. configurable: true
  40311. });
  40312. /**
  40313. * Render the model instances
  40314. * @param instanceInfo
  40315. * @param context
  40316. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  40317. */
  40318. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  40319. return true;
  40320. };
  40321. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  40322. var key = this._nextKey.toString();
  40323. if (!this._instancesData.add(key, data)) {
  40324. throw Error("Key: " + key + " is already allocated");
  40325. }
  40326. ++this._nextKey;
  40327. return key;
  40328. };
  40329. ModelRenderCache.prototype.removeInstanceData = function (key) {
  40330. this._instancesData.remove(key);
  40331. };
  40332. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  40333. for (var i = 0; i < this._partData.length; i++) {
  40334. if (this._partData[i]._partId === partId) {
  40335. return i;
  40336. }
  40337. }
  40338. return null;
  40339. };
  40340. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  40341. var i = this.getPartIndexFromId(partId);
  40342. if (i === null) {
  40343. return null;
  40344. }
  40345. var ci = this._partsClassInfo[i];
  40346. var categories = this._partData[i]._partUsedCategories;
  40347. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  40348. return res;
  40349. };
  40350. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  40351. var pd = this._partData[partIndex];
  40352. var offset = (pd._partDataStride / 4) * elementCount;
  40353. var pci = this._partsClassInfo[partIndex];
  40354. var self = this;
  40355. pci.fullContent.forEach(function (k, v) {
  40356. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  40357. switch (v.dataType) {
  40358. case 4 /* float */:
  40359. {
  40360. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40361. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  40362. break;
  40363. }
  40364. case 0 /* Vector2 */:
  40365. {
  40366. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40367. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  40368. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  40369. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  40370. break;
  40371. }
  40372. case 5 /* Color3 */:
  40373. case 1 /* Vector3 */:
  40374. {
  40375. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40376. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  40377. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  40378. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  40379. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  40380. break;
  40381. }
  40382. case 6 /* Color4 */:
  40383. case 2 /* Vector4 */:
  40384. {
  40385. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40386. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  40387. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  40388. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  40389. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  40390. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  40391. break;
  40392. }
  40393. default:
  40394. }
  40395. }
  40396. });
  40397. };
  40398. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  40399. // let i = this.getPartIndexFromId(partId);
  40400. // if (i === null) {
  40401. // return null;
  40402. // }
  40403. // let pci = this._partsClassInfo[i];
  40404. // pci.fullContent.forEach((k, v) => {
  40405. // if (uniforms.indexOf(v.attributeName) !== -1) {
  40406. // v.uniformLocation = effect.getUniform(v.attributeName);
  40407. // }
  40408. // });
  40409. //}
  40410. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  40411. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  40412. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  40413. return ModelRenderCache;
  40414. })();
  40415. BABYLON.ModelRenderCache = ModelRenderCache;
  40416. var ModelRenderCachePartData = (function () {
  40417. function ModelRenderCachePartData() {
  40418. }
  40419. return ModelRenderCachePartData;
  40420. })();
  40421. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  40422. })(BABYLON || (BABYLON = {}));
  40423. var BABYLON;
  40424. (function (BABYLON) {
  40425. var InstanceClassInfo = (function () {
  40426. function InstanceClassInfo(base) {
  40427. this._baseInfo = base;
  40428. this._nextOffset = new BABYLON.StringDictionary();
  40429. this._attributes = new Array();
  40430. }
  40431. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  40432. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  40433. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  40434. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  40435. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  40436. if (push) {
  40437. this._attributes.push(propInfo);
  40438. }
  40439. };
  40440. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  40441. var catInline = ";" + categories.join(";") + ";";
  40442. var res = new Array();
  40443. var curInfo = this;
  40444. while (curInfo) {
  40445. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40446. var attrib = _a[_i];
  40447. // 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
  40448. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40449. var index = effect.getAttributeLocationByName(attrib.attributeName);
  40450. var iai = new BABYLON.InstancingAttributeInfo();
  40451. iai.index = index;
  40452. 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)
  40453. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  40454. iai.attributeName = attrib.attributeName;
  40455. res.push(iai);
  40456. }
  40457. }
  40458. curInfo = curInfo._baseInfo;
  40459. }
  40460. return res;
  40461. };
  40462. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  40463. var res = new Array();
  40464. var curInfo = this;
  40465. while (curInfo) {
  40466. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40467. var attrib = _a[_i];
  40468. // 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
  40469. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40470. res.push(attrib.attributeName);
  40471. }
  40472. }
  40473. curInfo = curInfo._baseInfo;
  40474. }
  40475. return res;
  40476. };
  40477. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  40478. var curOffset = 0;
  40479. var curBase = this._baseInfo;
  40480. while (curBase) {
  40481. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  40482. curBase = curBase._baseInfo;
  40483. }
  40484. return curOffset;
  40485. };
  40486. return InstanceClassInfo;
  40487. })();
  40488. BABYLON.InstanceClassInfo = InstanceClassInfo;
  40489. var InstancePropInfo = (function () {
  40490. function InstancePropInfo() {
  40491. this.instanceOffset = new BABYLON.StringDictionary();
  40492. }
  40493. InstancePropInfo.prototype.setSize = function (val) {
  40494. if (val instanceof BABYLON.Vector2) {
  40495. this.size = 8;
  40496. this.dataType = 0 /* Vector2 */;
  40497. return;
  40498. }
  40499. if (val instanceof BABYLON.Vector3) {
  40500. this.size = 12;
  40501. this.dataType = 1 /* Vector3 */;
  40502. return;
  40503. }
  40504. if (val instanceof BABYLON.Vector4) {
  40505. this.size = 16;
  40506. this.dataType = 2 /* Vector4 */;
  40507. return;
  40508. }
  40509. if (val instanceof BABYLON.Matrix) {
  40510. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  40511. }
  40512. if (typeof (val) === "number") {
  40513. this.size = 4;
  40514. this.dataType = 4 /* float */;
  40515. return;
  40516. }
  40517. if (val instanceof BABYLON.Color3) {
  40518. this.size = 12;
  40519. this.dataType = 5 /* Color3 */;
  40520. return;
  40521. }
  40522. if (val instanceof BABYLON.Color4) {
  40523. this.size = 16;
  40524. this.dataType = 6 /* Color4 */;
  40525. return;
  40526. }
  40527. if (val instanceof BABYLON.Size) {
  40528. this.size = 8;
  40529. this.dataType = 7 /* Size */;
  40530. return;
  40531. }
  40532. return;
  40533. };
  40534. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  40535. switch (this.dataType) {
  40536. case 0 /* Vector2 */:
  40537. {
  40538. var v = val;
  40539. array[offset + 0] = v.x;
  40540. array[offset + 1] = v.y;
  40541. break;
  40542. }
  40543. case 1 /* Vector3 */:
  40544. {
  40545. var v = val;
  40546. array[offset + 0] = v.x;
  40547. array[offset + 1] = v.y;
  40548. array[offset + 2] = v.z;
  40549. break;
  40550. }
  40551. case 2 /* Vector4 */:
  40552. {
  40553. var v = val;
  40554. array[offset + 0] = v.x;
  40555. array[offset + 1] = v.y;
  40556. array[offset + 2] = v.z;
  40557. array[offset + 3] = v.w;
  40558. break;
  40559. }
  40560. case 5 /* Color3 */:
  40561. {
  40562. var v = val;
  40563. array[offset + 0] = v.r;
  40564. array[offset + 1] = v.g;
  40565. array[offset + 2] = v.b;
  40566. break;
  40567. }
  40568. case 6 /* Color4 */:
  40569. {
  40570. var v = val;
  40571. array[offset + 0] = v.r;
  40572. array[offset + 1] = v.g;
  40573. array[offset + 2] = v.b;
  40574. array[offset + 3] = v.a;
  40575. break;
  40576. }
  40577. case 4 /* float */:
  40578. {
  40579. var v = val;
  40580. array[offset] = v;
  40581. break;
  40582. }
  40583. case 3 /* Matrix */:
  40584. {
  40585. var v = val;
  40586. for (var i = 0; i < 16; i++) {
  40587. array[offset + i] = v.m[i];
  40588. }
  40589. break;
  40590. }
  40591. case 7 /* Size */:
  40592. {
  40593. var s = val;
  40594. array[offset + 0] = s.width;
  40595. array[offset + 1] = s.height;
  40596. break;
  40597. }
  40598. }
  40599. };
  40600. return InstancePropInfo;
  40601. })();
  40602. BABYLON.InstancePropInfo = InstancePropInfo;
  40603. function instanceData(category, shaderAttributeName) {
  40604. return function (target, propName, descriptor) {
  40605. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  40606. var node = dic.getLevelOf(target);
  40607. var instanceDataName = propName;
  40608. shaderAttributeName = shaderAttributeName || instanceDataName;
  40609. var info = node.levelContent.get(instanceDataName);
  40610. if (info) {
  40611. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  40612. }
  40613. info = new InstancePropInfo();
  40614. info.attributeName = shaderAttributeName;
  40615. info.category = category || null;
  40616. if (info.category) {
  40617. info.delimitedCategory = ";" + info.category + ";";
  40618. }
  40619. node.levelContent.add(instanceDataName, info);
  40620. descriptor.get = function () {
  40621. return null;
  40622. };
  40623. descriptor.set = function (val) {
  40624. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  40625. // Quit if it's the case, otherwise we could overwrite data somewhere...
  40626. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  40627. return;
  40628. }
  40629. if (!info.size) {
  40630. info.setSize(val);
  40631. node.classContent.mapProperty(info, true);
  40632. }
  40633. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  40634. node.classContent.mapProperty(info, false);
  40635. }
  40636. var obj = this;
  40637. if (obj.dataBuffer && obj.dataElements) {
  40638. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  40639. info.writeData(obj.dataBuffer.buffer, offset, val);
  40640. }
  40641. };
  40642. };
  40643. }
  40644. BABYLON.instanceData = instanceData;
  40645. var InstanceDataBase = (function () {
  40646. function InstanceDataBase(partId, dataElementCount) {
  40647. this.id = partId;
  40648. this.curElement = 0;
  40649. this.dataElementCount = dataElementCount;
  40650. this.renderMode = 0;
  40651. this.arrayLengthChanged = false;
  40652. }
  40653. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  40654. get: function () {
  40655. return null;
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  40661. get: function () {
  40662. return null;
  40663. },
  40664. enumerable: true,
  40665. configurable: true
  40666. });
  40667. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  40668. get: function () {
  40669. return null;
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  40675. get: function () {
  40676. return null;
  40677. },
  40678. enumerable: true,
  40679. configurable: true
  40680. });
  40681. InstanceDataBase.prototype.getClassTreeInfo = function () {
  40682. if (!this.typeInfo) {
  40683. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  40684. }
  40685. return this.typeInfo;
  40686. };
  40687. InstanceDataBase.prototype.allocElements = function () {
  40688. if (!this.dataBuffer) {
  40689. return;
  40690. }
  40691. var res = new Array(this.dataElementCount);
  40692. for (var i = 0; i < this.dataElementCount; i++) {
  40693. res[i] = this.dataBuffer.allocElement();
  40694. }
  40695. this.dataElements = res;
  40696. };
  40697. InstanceDataBase.prototype.freeElements = function () {
  40698. if (!this.dataElements) {
  40699. return;
  40700. }
  40701. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  40702. var ei = _a[_i];
  40703. this.dataBuffer.freeElement(ei);
  40704. }
  40705. this.dataElements = null;
  40706. };
  40707. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  40708. get: function () {
  40709. return this._dataElementCount;
  40710. },
  40711. set: function (value) {
  40712. if (value === this._dataElementCount) {
  40713. return;
  40714. }
  40715. this.arrayLengthChanged = true;
  40716. this.freeElements();
  40717. this._dataElementCount = value;
  40718. this.allocElements();
  40719. },
  40720. enumerable: true,
  40721. configurable: true
  40722. });
  40723. __decorate([
  40724. instanceData()
  40725. ], InstanceDataBase.prototype, "zBias", null);
  40726. __decorate([
  40727. instanceData()
  40728. ], InstanceDataBase.prototype, "transformX", null);
  40729. __decorate([
  40730. instanceData()
  40731. ], InstanceDataBase.prototype, "transformY", null);
  40732. __decorate([
  40733. instanceData()
  40734. ], InstanceDataBase.prototype, "opacity", null);
  40735. return InstanceDataBase;
  40736. })();
  40737. BABYLON.InstanceDataBase = InstanceDataBase;
  40738. var RenderablePrim2D = (function (_super) {
  40739. __extends(RenderablePrim2D, _super);
  40740. function RenderablePrim2D(settings) {
  40741. _super.call(this, settings);
  40742. this._isTransparent = false;
  40743. this._isAlphaTest = false;
  40744. this._transparentPrimitiveInfo = null;
  40745. }
  40746. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  40747. get: function () {
  40748. return this._isAlphaTest;
  40749. },
  40750. set: function (value) {
  40751. if (this._isAlphaTest === value) {
  40752. return;
  40753. }
  40754. this._isAlphaTest = value;
  40755. this._updateRenderMode();
  40756. },
  40757. enumerable: true,
  40758. configurable: true
  40759. });
  40760. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  40761. get: function () {
  40762. return this._isTransparent || (this._opacity < 1);
  40763. },
  40764. set: function (value) {
  40765. if (this._isTransparent === value) {
  40766. return;
  40767. }
  40768. this._isTransparent = value;
  40769. this._updateRenderMode();
  40770. },
  40771. enumerable: true,
  40772. configurable: true
  40773. });
  40774. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  40775. get: function () {
  40776. return this._renderMode;
  40777. },
  40778. enumerable: true,
  40779. configurable: true
  40780. });
  40781. /**
  40782. * Dispose the primitive and its resources, remove it from its parent
  40783. */
  40784. RenderablePrim2D.prototype.dispose = function () {
  40785. if (!_super.prototype.dispose.call(this)) {
  40786. return false;
  40787. }
  40788. if (this._transparentPrimitiveInfo) {
  40789. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  40790. this._transparentPrimitiveInfo = null;
  40791. }
  40792. if (this._modelRenderInstanceID) {
  40793. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  40794. this._modelRenderInstanceID = null;
  40795. }
  40796. if (this._modelRenderCache) {
  40797. this._modelRenderCache.dispose();
  40798. this._modelRenderCache = null;
  40799. }
  40800. if (this._instanceDataParts) {
  40801. this._instanceDataParts.forEach(function (p) {
  40802. p.freeElements();
  40803. });
  40804. this._instanceDataParts = null;
  40805. }
  40806. return true;
  40807. };
  40808. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  40809. _super.prototype._prepareRenderPre.call(this, context);
  40810. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  40811. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  40812. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  40813. this._modelRenderInstanceID = null;
  40814. }
  40815. // Need to create the model?
  40816. var setupModelRenderCache = false;
  40817. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  40818. setupModelRenderCache = this._createModelRenderCache();
  40819. }
  40820. var gii = null;
  40821. var newInstance = false;
  40822. // Need to create the instance data parts?
  40823. if (!this._modelRenderInstanceID) {
  40824. // Yes, flag it for later, more processing will have to be done
  40825. newInstance = true;
  40826. gii = this._createModelDataParts();
  40827. }
  40828. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  40829. if (setupModelRenderCache) {
  40830. this.setupModelRenderCache(this._modelRenderCache);
  40831. }
  40832. // 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.
  40833. // 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.
  40834. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  40835. this._updateInstanceDataParts(gii);
  40836. }
  40837. };
  40838. RenderablePrim2D.prototype._createModelRenderCache = function () {
  40839. var _this = this;
  40840. var setupModelRenderCache = false;
  40841. if (this._modelRenderCache) {
  40842. this._modelRenderCache.dispose();
  40843. }
  40844. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  40845. var mrc = _this.createModelRenderCache(key);
  40846. setupModelRenderCache = true;
  40847. return mrc;
  40848. });
  40849. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  40850. // if this is still false it means the MRC already exists, so we add a reference to it
  40851. if (!setupModelRenderCache) {
  40852. this._modelRenderCache.addRef();
  40853. }
  40854. return setupModelRenderCache;
  40855. };
  40856. RenderablePrim2D.prototype._createModelDataParts = function () {
  40857. var _this = this;
  40858. // Create the instance data parts of the primitive and store them
  40859. var parts = this.createInstanceDataParts();
  40860. this._instanceDataParts = parts;
  40861. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  40862. if (!this._modelRenderCache._partData) {
  40863. this._setupModelRenderCache(parts);
  40864. }
  40865. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  40866. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  40867. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  40868. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  40869. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  40870. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  40871. var part = _this._instanceDataParts[j];
  40872. res.partIndexFromId.add(part.id.toString(), j);
  40873. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  40874. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  40875. }
  40876. return res;
  40877. });
  40878. // Get the GroupInfoDataPart corresponding to the render category of the part
  40879. var rm = 0;
  40880. var gipd = null;
  40881. if (this.isTransparent) {
  40882. gipd = gii.transparentData;
  40883. rm = BABYLON.Render2DContext.RenderModeTransparent;
  40884. }
  40885. else if (this.isAlphaTest) {
  40886. gipd = gii.alphaTestData;
  40887. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  40888. }
  40889. else {
  40890. gipd = gii.opaqueData;
  40891. rm = BABYLON.Render2DContext.RenderModeOpaque;
  40892. }
  40893. // For each instance data part of the primitive, allocate the instanced element it needs for render
  40894. for (var i = 0; i < parts.length; i++) {
  40895. var part = parts[i];
  40896. part.dataBuffer = gipd[i]._partData;
  40897. part.allocElements();
  40898. part.renderMode = rm;
  40899. }
  40900. // 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
  40901. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  40902. return gii;
  40903. };
  40904. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  40905. var ctiArray = new Array();
  40906. this._modelRenderCache._partData = new Array();
  40907. for (var _i = 0; _i < parts.length; _i++) {
  40908. var dataPart = parts[_i];
  40909. var pd = new BABYLON.ModelRenderCachePartData();
  40910. this._modelRenderCache._partData.push(pd);
  40911. var cat = this.getUsedShaderCategories(dataPart);
  40912. var cti = dataPart.getClassTreeInfo();
  40913. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  40914. var curVisible = this.isVisible;
  40915. this.isVisible = true;
  40916. // 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.
  40917. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  40918. var joinCat = ";" + cat.join(";") + ";";
  40919. pd._partJoinedUsedCategories = joinCat;
  40920. InstanceClassInfo._CurCategories = joinCat;
  40921. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  40922. this.refreshInstanceDataPart(dataPart);
  40923. this.afterRefreshForLayoutConstruction(dataPart, obj);
  40924. this.isVisible = curVisible;
  40925. var size = 0;
  40926. cti.fullContent.forEach(function (k, v) {
  40927. if (!v.category || cat.indexOf(v.category) !== -1) {
  40928. if (v.attributeName === "zBias") {
  40929. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  40930. }
  40931. if (!v.size) {
  40932. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  40933. }
  40934. else {
  40935. size += v.size;
  40936. }
  40937. }
  40938. });
  40939. pd._partDataStride = size;
  40940. pd._partUsedCategories = cat;
  40941. pd._partId = dataPart.id;
  40942. ctiArray.push(cti);
  40943. }
  40944. this._modelRenderCache._partsClassInfo = ctiArray;
  40945. };
  40946. RenderablePrim2D.prototype.onZOrderChanged = function () {
  40947. if (this.isTransparent && this._transparentPrimitiveInfo) {
  40948. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  40949. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  40950. // Flag the transparentData dirty has will have to sort it again
  40951. gii.transparentOrderDirty = true;
  40952. }
  40953. };
  40954. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  40955. // Fetch the GroupInstanceInfo if we don't already have it
  40956. var rd = this.renderGroup._renderableData;
  40957. if (!gii) {
  40958. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  40959. }
  40960. var isTransparent = this.isTransparent;
  40961. var isAlphaTest = this.isAlphaTest;
  40962. var wereTransparent = false;
  40963. // Check a render mode change
  40964. var rmChanged = false;
  40965. if (this._instanceDataParts.length > 0) {
  40966. var firstPart = this._instanceDataParts[0];
  40967. var partRM = firstPart.renderMode;
  40968. var curRM = this.renderMode;
  40969. if (partRM !== curRM) {
  40970. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  40971. rmChanged = true;
  40972. var gipd;
  40973. switch (curRM) {
  40974. case BABYLON.Render2DContext.RenderModeTransparent:
  40975. gipd = gii.transparentData;
  40976. break;
  40977. case BABYLON.Render2DContext.RenderModeAlphaTest:
  40978. gipd = gii.alphaTestData;
  40979. break;
  40980. default:
  40981. gipd = gii.opaqueData;
  40982. }
  40983. for (var i = 0; i < this._instanceDataParts.length; i++) {
  40984. var part = this._instanceDataParts[i];
  40985. part.freeElements();
  40986. part.dataBuffer = gipd[i]._partData;
  40987. part.renderMode = curRM;
  40988. }
  40989. }
  40990. }
  40991. // Handle changes related to ZOffset
  40992. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  40993. if (isTransparent || wereTransparent) {
  40994. // Handle visibility change, which is also triggered when the primitive just got created
  40995. if (visChanged || rmChanged) {
  40996. if (this.isVisible && !wereTransparent) {
  40997. if (!this._transparentPrimitiveInfo) {
  40998. // Add the primitive to the list of transparent ones in the group that render is
  40999. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  41000. }
  41001. }
  41002. else {
  41003. if (this._transparentPrimitiveInfo) {
  41004. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41005. this._transparentPrimitiveInfo = null;
  41006. }
  41007. }
  41008. gii.transparentOrderDirty = true;
  41009. }
  41010. }
  41011. var rebuildTrans = false;
  41012. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  41013. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41014. var part = _a[_i];
  41015. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  41016. if ((visChanged && !part.dataElements) || rmChanged) {
  41017. part.allocElements();
  41018. }
  41019. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  41020. // Will return false if the instance should not be rendered (not visible or other any reasons)
  41021. part.arrayLengthChanged = false;
  41022. if (!this.refreshInstanceDataPart(part)) {
  41023. // Free the data element
  41024. if (part.dataElements) {
  41025. part.freeElements();
  41026. }
  41027. }
  41028. rebuildTrans = rebuildTrans || part.arrayLengthChanged;
  41029. }
  41030. this._instanceDirtyFlags = 0;
  41031. // Make the appropriate data dirty
  41032. if (isTransparent) {
  41033. gii.transparentDirty = true;
  41034. if (rebuildTrans) {
  41035. rd._transparentListChanged = true;
  41036. }
  41037. }
  41038. else if (isAlphaTest) {
  41039. gii.alphaTestDirty = true;
  41040. }
  41041. else {
  41042. gii.opaqueDirty = true;
  41043. }
  41044. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  41045. };
  41046. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  41047. var minOff = BABYLON.Prim2DBase._bigInt;
  41048. var maxOff = 0;
  41049. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41050. var part = _a[_i];
  41051. if (part) {
  41052. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41053. var el = _c[_b];
  41054. minOff = Math.min(minOff, el.offset);
  41055. maxOff = Math.max(maxOff, el.offset);
  41056. }
  41057. ts.startDataIndex = minOff / part.dataBuffer.stride;
  41058. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41059. }
  41060. }
  41061. };
  41062. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  41063. var maxOff = 0;
  41064. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41065. var part = _a[_i];
  41066. if (part) {
  41067. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41068. var el = _c[_b];
  41069. maxOff = Math.max(maxOff, el.offset);
  41070. }
  41071. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41072. }
  41073. }
  41074. };
  41075. // This internal method is mainly used for transparency processing
  41076. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  41077. var length = this._instanceDataParts.length;
  41078. for (var i = 0; i < length; i++) {
  41079. var part = this._instanceDataParts[i];
  41080. if (part) {
  41081. var stride = part.dataBuffer.stride;
  41082. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  41083. // check if it's the last in the DFA
  41084. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  41085. return null;
  41086. }
  41087. // Return the Z of the next primitive that lies in the DFA
  41088. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41089. }
  41090. }
  41091. return null;
  41092. };
  41093. // This internal method is mainly used for transparency processing
  41094. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  41095. var length = this._instanceDataParts.length;
  41096. for (var i = 0; i < length; i++) {
  41097. var part = this._instanceDataParts[i];
  41098. if (part) {
  41099. var stride = part.dataBuffer.stride;
  41100. var firstElementOffset = part.dataElements[0].offset;
  41101. // check if it's the first in the DFA
  41102. if (firstElementOffset === 0) {
  41103. return null;
  41104. }
  41105. // Return the Z of the previous primitive that lies in the DFA
  41106. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41107. }
  41108. }
  41109. return null;
  41110. };
  41111. /**
  41112. * Transform a given point using the Primitive's origin setting.
  41113. * This method requires the Primitive's actualSize to be accurate
  41114. * @param p the point to transform
  41115. * @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.
  41116. * @param res an allocated Vector2 that will receive the transformed content
  41117. */
  41118. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  41119. var actualSize = this.actualSize;
  41120. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  41121. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  41122. };
  41123. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  41124. this.transformPointWithOriginByRef(p, originOffset, res);
  41125. return res;
  41126. };
  41127. /**
  41128. * Get the info for a given effect based on the dataPart metadata
  41129. * @param dataPartId partId in part list to get the info
  41130. * @param vertexBufferAttributes vertex buffer attributes to manually add
  41131. * @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
  41132. */
  41133. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  41134. if (useInstanced === void 0) { useInstanced = null; }
  41135. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  41136. if (!dataPart) {
  41137. return null;
  41138. }
  41139. var instancedArray = this.owner.supportInstancedArray;
  41140. if (useInstanced != null) {
  41141. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  41142. if (useInstanced && instancedArray === false) {
  41143. return null;
  41144. }
  41145. // Use the caller's setting
  41146. instancedArray = useInstanced;
  41147. }
  41148. var cti = dataPart.getClassTreeInfo();
  41149. var categories = this.getUsedShaderCategories(dataPart);
  41150. var att = cti.classContent.getShaderAttributes(categories);
  41151. var defines = "";
  41152. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  41153. if (instancedArray) {
  41154. defines += "#define Instanced\n";
  41155. }
  41156. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  41157. };
  41158. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  41159. get: function () {
  41160. return this._modelRenderCache;
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  41166. return null;
  41167. };
  41168. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41169. };
  41170. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  41171. return null;
  41172. };
  41173. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  41174. return [];
  41175. };
  41176. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  41177. };
  41178. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  41179. };
  41180. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  41181. if (!this.isVisible) {
  41182. return false;
  41183. }
  41184. part.isVisible = this.isVisible;
  41185. // 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)
  41186. if (part.dataElementCount === 1) {
  41187. part.curElement = 0;
  41188. this.updateInstanceDataPart(part);
  41189. }
  41190. return true;
  41191. };
  41192. /**
  41193. * Update the instanceDataBase level properties of a part
  41194. * @param part the part to update
  41195. * @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).
  41196. */
  41197. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  41198. if (positionOffset === void 0) { positionOffset = null; }
  41199. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  41200. var size = this.renderGroup.viewportSize;
  41201. var zBias = this.actualZOffset;
  41202. var offX = 0;
  41203. var offY = 0;
  41204. // If there's an offset, apply the global transformation matrix on it to get a global offset
  41205. if (positionOffset) {
  41206. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  41207. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  41208. }
  41209. // 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
  41210. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  41211. // So for X:
  41212. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  41213. // - 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].
  41214. var w = size.width;
  41215. var h = size.height;
  41216. var invZBias = 1 / zBias;
  41217. 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);
  41218. 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);
  41219. part.transformX = tx;
  41220. part.transformY = ty;
  41221. part.opacity = this.actualOpacity;
  41222. // 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)
  41223. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  41224. };
  41225. RenderablePrim2D.prototype._updateRenderMode = function () {
  41226. if (this.isTransparent) {
  41227. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  41228. }
  41229. else if (this.isAlphaTest) {
  41230. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  41231. }
  41232. else {
  41233. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  41234. }
  41235. };
  41236. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41237. __decorate([
  41238. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  41239. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  41240. __decorate([
  41241. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  41242. ], RenderablePrim2D.prototype, "isTransparent", null);
  41243. RenderablePrim2D = __decorate([
  41244. BABYLON.className("RenderablePrim2D")
  41245. ], RenderablePrim2D);
  41246. return RenderablePrim2D;
  41247. })(BABYLON.Prim2DBase);
  41248. BABYLON.RenderablePrim2D = RenderablePrim2D;
  41249. })(BABYLON || (BABYLON = {}));
  41250. var BABYLON;
  41251. (function (BABYLON) {
  41252. var Shape2D = (function (_super) {
  41253. __extends(Shape2D, _super);
  41254. function Shape2D(settings) {
  41255. _super.call(this, settings);
  41256. if (!settings) {
  41257. settings = {};
  41258. }
  41259. var borderBrush = null;
  41260. if (settings.border) {
  41261. if (typeof (settings.border) === "string") {
  41262. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  41263. }
  41264. else {
  41265. borderBrush = settings.border;
  41266. }
  41267. }
  41268. var fillBrush = null;
  41269. if (settings.fill) {
  41270. if (typeof (settings.fill) === "string") {
  41271. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  41272. }
  41273. else {
  41274. fillBrush = settings.fill;
  41275. }
  41276. }
  41277. this.border = borderBrush;
  41278. this.fill = fillBrush;
  41279. this.borderThickness = settings.borderThickness;
  41280. }
  41281. Object.defineProperty(Shape2D.prototype, "border", {
  41282. get: function () {
  41283. return this._border;
  41284. },
  41285. set: function (value) {
  41286. this._border = value;
  41287. this._updateTransparencyStatus();
  41288. },
  41289. enumerable: true,
  41290. configurable: true
  41291. });
  41292. Object.defineProperty(Shape2D.prototype, "fill", {
  41293. /**
  41294. * Get/set the brush to render the Fill part of the Primitive
  41295. */
  41296. get: function () {
  41297. return this._fill;
  41298. },
  41299. set: function (value) {
  41300. this._fill = value;
  41301. this._updateTransparencyStatus();
  41302. },
  41303. enumerable: true,
  41304. configurable: true
  41305. });
  41306. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  41307. get: function () {
  41308. return this._borderThickness;
  41309. },
  41310. set: function (value) {
  41311. this._borderThickness = value;
  41312. },
  41313. enumerable: true,
  41314. configurable: true
  41315. });
  41316. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  41317. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  41318. // Fill Part
  41319. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  41320. var fill = this.fill;
  41321. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41322. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  41323. }
  41324. if (fill instanceof BABYLON.GradientColorBrush2D) {
  41325. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  41326. }
  41327. }
  41328. // Border Part
  41329. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41330. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  41331. var border = this.border;
  41332. if (border instanceof BABYLON.SolidColorBrush2D) {
  41333. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  41334. }
  41335. if (border instanceof BABYLON.GradientColorBrush2D) {
  41336. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  41337. }
  41338. }
  41339. return cat;
  41340. };
  41341. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  41342. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  41343. return false;
  41344. }
  41345. // Fill Part
  41346. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  41347. var d = part;
  41348. if (this.fill) {
  41349. var fill = this.fill;
  41350. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41351. d.fillSolidColor = fill.color;
  41352. }
  41353. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  41354. d.fillGradientColor1 = fill.color1;
  41355. d.fillGradientColor2 = fill.color2;
  41356. 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));
  41357. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41358. d.fillGradientTY = ty;
  41359. }
  41360. }
  41361. }
  41362. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41363. var d = part;
  41364. if (this.border) {
  41365. d.borderThickness = this.borderThickness;
  41366. var border = this.border;
  41367. if (border instanceof BABYLON.SolidColorBrush2D) {
  41368. d.borderSolidColor = border.color;
  41369. }
  41370. else if (border instanceof BABYLON.GradientColorBrush2D) {
  41371. d.borderGradientColor1 = border.color1;
  41372. d.borderGradientColor2 = border.color2;
  41373. 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));
  41374. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41375. d.borderGradientTY = ty;
  41376. }
  41377. }
  41378. }
  41379. return true;
  41380. };
  41381. Shape2D.prototype._updateTransparencyStatus = function () {
  41382. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  41383. };
  41384. Shape2D.SHAPE2D_BORDERPARTID = 1;
  41385. Shape2D.SHAPE2D_FILLPARTID = 2;
  41386. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  41387. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  41388. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  41389. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  41390. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  41391. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  41392. __decorate([
  41393. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  41394. ], Shape2D.prototype, "border", null);
  41395. __decorate([
  41396. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  41397. ], Shape2D.prototype, "fill", null);
  41398. __decorate([
  41399. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  41400. ], Shape2D.prototype, "borderThickness", null);
  41401. Shape2D = __decorate([
  41402. BABYLON.className("Shape2D")
  41403. ], Shape2D);
  41404. return Shape2D;
  41405. })(BABYLON.RenderablePrim2D);
  41406. BABYLON.Shape2D = Shape2D;
  41407. var Shape2DInstanceData = (function (_super) {
  41408. __extends(Shape2DInstanceData, _super);
  41409. function Shape2DInstanceData() {
  41410. _super.apply(this, arguments);
  41411. }
  41412. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  41413. // FILL ATTRIBUTES
  41414. get: function () {
  41415. return null;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  41421. get: function () {
  41422. return null;
  41423. },
  41424. enumerable: true,
  41425. configurable: true
  41426. });
  41427. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  41428. get: function () {
  41429. return null;
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  41435. get: function () {
  41436. return null;
  41437. },
  41438. enumerable: true,
  41439. configurable: true
  41440. });
  41441. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  41442. // BORDER ATTRIBUTES
  41443. get: function () {
  41444. return null;
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  41450. get: function () {
  41451. return null;
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  41457. get: function () {
  41458. return null;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  41464. get: function () {
  41465. return null;
  41466. },
  41467. enumerable: true,
  41468. configurable: true
  41469. });
  41470. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  41471. get: function () {
  41472. return null;
  41473. },
  41474. enumerable: true,
  41475. configurable: true
  41476. });
  41477. __decorate([
  41478. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  41479. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  41480. __decorate([
  41481. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41482. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  41483. __decorate([
  41484. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41485. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  41486. __decorate([
  41487. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41488. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  41489. __decorate([
  41490. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  41491. ], Shape2DInstanceData.prototype, "borderThickness", null);
  41492. __decorate([
  41493. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  41494. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  41495. __decorate([
  41496. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41497. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  41498. __decorate([
  41499. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41500. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  41501. __decorate([
  41502. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41503. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  41504. return Shape2DInstanceData;
  41505. })(BABYLON.InstanceDataBase);
  41506. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  41507. })(BABYLON || (BABYLON = {}));
  41508. var BABYLON;
  41509. (function (BABYLON) {
  41510. var Group2D = (function (_super) {
  41511. __extends(Group2D, _super);
  41512. /**
  41513. * Create an Logical or Renderable Group.
  41514. * @param settings a combination of settings, possible ones are
  41515. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  41516. * - children: an array of direct children
  41517. * - id a text identifier, for information purpose
  41518. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41519. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41520. * - scale: the initial scale of the primitive. default is 1
  41521. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  41522. * - origin: define the normalized origin point location, default [0.5;0.5]
  41523. * - 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.
  41524. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  41525. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  41526. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  41527. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  41528. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41529. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41530. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41531. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41532. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41533. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41534. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41535. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41536. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41537. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41538. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41539. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41540. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41541. */
  41542. function Group2D(settings) {
  41543. if (settings == null) {
  41544. settings = {};
  41545. }
  41546. if (settings.origin == null) {
  41547. settings.origin = new BABYLON.Vector2(0, 0);
  41548. }
  41549. _super.call(this, settings);
  41550. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  41551. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  41552. if (this._trackedNode && this.owner) {
  41553. this.owner._registerTrackedNode(this);
  41554. }
  41555. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  41556. this.size = size;
  41557. this._viewportPosition = BABYLON.Vector2.Zero();
  41558. }
  41559. Group2D._createCachedCanvasGroup = function (owner) {
  41560. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  41561. return g;
  41562. };
  41563. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  41564. this._bindCacheTarget();
  41565. if (vertexData) {
  41566. var uv = vertexData.uvs;
  41567. var nodeuv = this._renderableData._cacheNodeUVs;
  41568. for (var i = 0; i < 4; i++) {
  41569. uv[i * 2 + 0] = nodeuv[i].x;
  41570. uv[i * 2 + 1] = nodeuv[i].y;
  41571. }
  41572. }
  41573. if (material) {
  41574. material.diffuseTexture = this._renderableData._cacheTexture;
  41575. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41576. }
  41577. this._renderableData._cacheTexture.hasAlpha = true;
  41578. this._unbindCacheTarget();
  41579. };
  41580. Object.defineProperty(Group2D.prototype, "cachedRect", {
  41581. /**
  41582. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  41583. * 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 Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  41584. */
  41585. get: function () {
  41586. if (!this._renderableData) {
  41587. return null;
  41588. }
  41589. return this._renderableData._cacheNode;
  41590. },
  41591. enumerable: true,
  41592. configurable: true
  41593. });
  41594. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  41595. /**
  41596. * The UVs into the MapTexture that map the cached group
  41597. */
  41598. get: function () {
  41599. if (!this._renderableData) {
  41600. return null;
  41601. }
  41602. return this._renderableData._cacheNodeUVs;
  41603. },
  41604. enumerable: true,
  41605. configurable: true
  41606. });
  41607. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  41608. get: function () {
  41609. if (!this._renderableData) {
  41610. return null;
  41611. }
  41612. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  41613. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  41614. }
  41615. return this._renderableData._cacheNodeUVsChangedObservable;
  41616. },
  41617. enumerable: true,
  41618. configurable: true
  41619. });
  41620. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  41621. /**
  41622. * Access the texture that maintains a cached version of the Group2D.
  41623. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  41624. */
  41625. get: function () {
  41626. if (!this._renderableData) {
  41627. return null;
  41628. }
  41629. return this._renderableData._cacheTexture;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. /**
  41635. * Call this method to remove this Group and its children from the Canvas
  41636. */
  41637. Group2D.prototype.dispose = function () {
  41638. if (!_super.prototype.dispose.call(this)) {
  41639. return false;
  41640. }
  41641. if (this._trackedNode != null) {
  41642. this.owner._unregisterTrackedNode(this);
  41643. this._trackedNode = null;
  41644. }
  41645. if (this._renderableData) {
  41646. this._renderableData.dispose(this.owner.engine);
  41647. this._renderableData = null;
  41648. }
  41649. return true;
  41650. };
  41651. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  41652. /**
  41653. * @returns Returns true if the Group render content, false if it's a logical group only
  41654. */
  41655. get: function () {
  41656. return this._isRenderableGroup;
  41657. },
  41658. enumerable: true,
  41659. configurable: true
  41660. });
  41661. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  41662. /**
  41663. * @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
  41664. */
  41665. get: function () {
  41666. return this._isCachedGroup;
  41667. },
  41668. enumerable: true,
  41669. configurable: true
  41670. });
  41671. Object.defineProperty(Group2D.prototype, "size", {
  41672. get: function () {
  41673. return this._size;
  41674. },
  41675. /**
  41676. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  41677. * 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.
  41678. */
  41679. set: function (val) {
  41680. this._size = val;
  41681. },
  41682. enumerable: true,
  41683. configurable: true
  41684. });
  41685. Object.defineProperty(Group2D.prototype, "viewportSize", {
  41686. get: function () {
  41687. return this._viewportSize;
  41688. },
  41689. enumerable: true,
  41690. configurable: true
  41691. });
  41692. Object.defineProperty(Group2D.prototype, "actualSize", {
  41693. get: function () {
  41694. // The computed size will be floor on both width and height
  41695. var actualSize;
  41696. // Return the size if set by the user
  41697. if (this._size) {
  41698. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  41699. }
  41700. else {
  41701. var m = this.boundingInfo.max();
  41702. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  41703. }
  41704. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  41705. if (!actualSize.equals(this._actualSize)) {
  41706. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  41707. this._actualSize = actualSize;
  41708. this.handleGroupChanged(Group2D.actualSizeProperty);
  41709. }
  41710. return actualSize;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  41716. /**
  41717. * 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.
  41718. * 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.
  41719. */
  41720. get: function () {
  41721. return this._cacheBehavior;
  41722. },
  41723. enumerable: true,
  41724. configurable: true
  41725. });
  41726. Group2D.prototype._addPrimToDirtyList = function (prim) {
  41727. this._renderableData._primDirtyList.push(prim);
  41728. };
  41729. Group2D.prototype._renderCachedCanvas = function () {
  41730. this.owner._addGroupRenderCount(1);
  41731. this.updateCachedStates(true);
  41732. var context = new BABYLON.PrepareRender2DContext();
  41733. this._prepareGroupRender(context);
  41734. this._groupRender();
  41735. };
  41736. Object.defineProperty(Group2D.prototype, "trackedNode", {
  41737. /**
  41738. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  41739. */
  41740. get: function () {
  41741. return this._trackedNode;
  41742. },
  41743. set: function (val) {
  41744. if (val != null) {
  41745. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41746. this.owner._registerTrackedNode(this);
  41747. }
  41748. this._trackedNode = val;
  41749. }
  41750. else {
  41751. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41752. this.owner._unregisterTrackedNode(this);
  41753. }
  41754. this._trackedNode = null;
  41755. }
  41756. },
  41757. enumerable: true,
  41758. configurable: true
  41759. });
  41760. Group2D.prototype.levelIntersect = function (intersectInfo) {
  41761. // 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
  41762. return true;
  41763. };
  41764. Group2D.prototype.updateLevelBoundingInfo = function () {
  41765. var size;
  41766. // If the size is set by the user, the boundingInfo is computed from this value
  41767. if (this.size) {
  41768. size = this.size;
  41769. }
  41770. else {
  41771. size = new BABYLON.Size(0, 0);
  41772. }
  41773. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  41774. };
  41775. // Method called only on renderable groups to prepare the rendering
  41776. Group2D.prototype._prepareGroupRender = function (context) {
  41777. var sortedDirtyList = null;
  41778. // Update the Global Transformation and visibility status of the changed primitives
  41779. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  41780. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  41781. this.updateCachedStatesOf(sortedDirtyList, true);
  41782. }
  41783. // Setup the size of the rendering viewport
  41784. // 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
  41785. if (!this._isCachedGroup) {
  41786. // Compute the WebGL viewport's location/size
  41787. var t = this._globalTransform.getTranslation();
  41788. var s = this.actualSize.clone();
  41789. var rs = this.owner._renderingSize;
  41790. s.height = Math.min(s.height, rs.height - t.y);
  41791. s.width = Math.min(s.width, rs.width - t.x);
  41792. var x = t.x;
  41793. var y = t.y;
  41794. // 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
  41795. this._viewportPosition.x = x;
  41796. this._viewportPosition.y = y;
  41797. var vw = s.width;
  41798. var vh = s.height;
  41799. if (!this._viewportSize) {
  41800. this._viewportSize = new BABYLON.Size(vw, vh);
  41801. }
  41802. else {
  41803. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  41804. context.forceRefreshPrimitive = true;
  41805. }
  41806. this._viewportSize.width = vw;
  41807. this._viewportSize.height = vh;
  41808. }
  41809. }
  41810. else {
  41811. var newSize = this.actualSize.clone();
  41812. if (!newSize.equals(this._viewportSize)) {
  41813. context.forceRefreshPrimitive = true;
  41814. }
  41815. this._viewportSize = newSize;
  41816. }
  41817. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  41818. // If the group is cached, set the dirty flag to true because of the incoming changes
  41819. this._cacheGroupDirty = this._isCachedGroup;
  41820. // If it's a force refresh, prepare all the children
  41821. if (context.forceRefreshPrimitive) {
  41822. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41823. var p = _a[_i];
  41824. p._prepareRender(context);
  41825. }
  41826. }
  41827. else {
  41828. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  41829. // the hierarchyDepth in order to prepare primitives from top to bottom
  41830. if (!sortedDirtyList) {
  41831. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  41832. }
  41833. sortedDirtyList.forEach(function (p) {
  41834. // 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.
  41835. // 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.
  41836. if (!p.isDisposed && p._needPrepare()) {
  41837. p._prepareRender(context);
  41838. }
  41839. });
  41840. // Everything is updated, clear the dirty list
  41841. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  41842. this._renderableData._primDirtyList.splice(0);
  41843. }
  41844. }
  41845. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  41846. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  41847. g._prepareGroupRender(context);
  41848. });
  41849. };
  41850. Group2D.prototype._groupRender = function () {
  41851. var _this = this;
  41852. var engine = this.owner.engine;
  41853. var failedCount = 0;
  41854. // First recurse to children render group to render them (in their cache or on screen)
  41855. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  41856. var childGroup = _a[_i];
  41857. childGroup._groupRender();
  41858. }
  41859. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  41860. if (!this.isCachedGroup || this._cacheGroupDirty) {
  41861. this.owner._addGroupRenderCount(1);
  41862. if (this.isCachedGroup) {
  41863. this._bindCacheTarget();
  41864. }
  41865. else {
  41866. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  41867. }
  41868. var curAlphaTest = engine.getAlphaTesting() === true;
  41869. var curDepthWrite = engine.getDepthWrite() === true;
  41870. // ===================================================================
  41871. // First pass, update the InstancedArray and render Opaque primitives
  41872. // Disable Alpha Testing, Enable Depth Write
  41873. engine.setAlphaTesting(false);
  41874. engine.setDepthWrite(true);
  41875. // For each different model of primitive to render
  41876. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  41877. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  41878. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  41879. var renderCount = _this._prepareContext(engine, context, v);
  41880. // If null is returned, there's no opaque data to render
  41881. if (renderCount === null) {
  41882. return;
  41883. }
  41884. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  41885. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  41886. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  41887. var renderFailed = !v.modelRenderCache.render(v, context);
  41888. // Update dirty flag/related
  41889. v.opaqueDirty = renderFailed;
  41890. failedCount += renderFailed ? 1 : 0;
  41891. }
  41892. });
  41893. // =======================================================================
  41894. // Second pass, update the InstancedArray and render AlphaTest primitives
  41895. // Enable Alpha Testing, Enable Depth Write
  41896. engine.setAlphaTesting(true);
  41897. engine.setDepthWrite(true);
  41898. // For each different model of primitive to render
  41899. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  41900. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  41901. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  41902. var renderCount = _this._prepareContext(engine, context, v);
  41903. // If null is returned, there's no opaque data to render
  41904. if (renderCount === null) {
  41905. return;
  41906. }
  41907. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  41908. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  41909. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  41910. var renderFailed = !v.modelRenderCache.render(v, context);
  41911. // Update dirty flag/related
  41912. v.opaqueDirty = renderFailed;
  41913. failedCount += renderFailed ? 1 : 0;
  41914. }
  41915. });
  41916. // =======================================================================
  41917. // Third pass, transparent primitive rendering
  41918. // Enable Alpha Testing, Disable Depth Write
  41919. engine.setAlphaTesting(true);
  41920. engine.setDepthWrite(false);
  41921. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  41922. if (this._renderableData._transparentListChanged) {
  41923. this._updateTransparentData();
  41924. }
  41925. // From this point on we have up to date data to render, so let's go
  41926. failedCount += this._renderTransparentData();
  41927. // =======================================================================
  41928. // Unbind target/restore viewport setting, clear dirty flag, and quit
  41929. // The group's content is no longer dirty
  41930. this._cacheGroupDirty = failedCount !== 0;
  41931. if (this.isCachedGroup) {
  41932. this._unbindCacheTarget();
  41933. }
  41934. else {
  41935. if (curVP) {
  41936. engine.setViewport(curVP);
  41937. }
  41938. }
  41939. // Restore saved states
  41940. engine.setAlphaTesting(curAlphaTest);
  41941. engine.setDepthWrite(curDepthWrite);
  41942. }
  41943. };
  41944. Group2D.prototype._updateTransparentData = function () {
  41945. this.owner._addUpdateTransparentDataCount(1);
  41946. var rd = this._renderableData;
  41947. // Sort all the primitive from their depth, max (bottom) to min (top)
  41948. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  41949. var checkAndAddPrimInSegment = function (seg, tpiI) {
  41950. var tpi = rd._transparentPrimitives[tpiI];
  41951. // Fast rejection: if gii are different
  41952. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  41953. return false;
  41954. }
  41955. //let tpiZ = tpi._primitive.actualZOffset;
  41956. // We've made it so far, the tpi can be part of the segment, add it
  41957. tpi._transparentSegment = seg;
  41958. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  41959. return true;
  41960. };
  41961. // Free the existing TransparentSegments
  41962. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  41963. var ts = _a[_i];
  41964. ts.dispose(this.owner.engine);
  41965. }
  41966. rd._transparentSegments.splice(0);
  41967. var prevSeg = null;
  41968. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  41969. var tpi = rd._transparentPrimitives[tpiI];
  41970. // Check if the Data in which the primitive is stored is not sorted properly
  41971. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  41972. tpi._groupInstanceInfo.sortTransparentData();
  41973. }
  41974. // Reset the segment, we have to create/rebuild it
  41975. tpi._transparentSegment = null;
  41976. // If there's a previous valid segment, check if this prim can be part of it
  41977. if (prevSeg) {
  41978. checkAndAddPrimInSegment(prevSeg, tpiI);
  41979. }
  41980. // If we couldn't insert in the adjacent segments, he have to create one
  41981. if (!tpi._transparentSegment) {
  41982. var ts = new BABYLON.TransparentSegment();
  41983. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  41984. var prim = tpi._primitive;
  41985. ts.startZ = prim.actualZOffset;
  41986. prim._updateTransparentSegmentIndices(ts);
  41987. ts.endZ = ts.startZ;
  41988. tpi._transparentSegment = ts;
  41989. rd._transparentSegments.push(ts);
  41990. }
  41991. // Update prevSeg
  41992. prevSeg = tpi._transparentSegment;
  41993. }
  41994. //rd._firstChangedPrim = null;
  41995. rd._transparentListChanged = false;
  41996. };
  41997. Group2D.prototype._renderTransparentData = function () {
  41998. var failedCount = 0;
  41999. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  42000. var rd = this._renderableData;
  42001. var useInstanced = this.owner.supportInstancedArray;
  42002. var length = rd._transparentSegments.length;
  42003. for (var i = 0; i < length; i++) {
  42004. context.instancedBuffers = null;
  42005. var ts = rd._transparentSegments[i];
  42006. var gii = ts.groupInsanceInfo;
  42007. var mrc = gii.modelRenderCache;
  42008. var engine = this.owner.engine;
  42009. var count = ts.endDataIndex - ts.startDataIndex;
  42010. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  42011. // We don't want to create an Instanced Buffer for less that 5 prims
  42012. if (useInstanced && count >= 5) {
  42013. if (!ts.partBuffers) {
  42014. var buffers = new Array();
  42015. for (var j = 0; j < gii.transparentData.length; j++) {
  42016. var gitd = gii.transparentData[j];
  42017. var dfa = gitd._partData;
  42018. var data = dfa.pack();
  42019. var stride = dfa.stride;
  42020. var neededSize = count * stride * 4;
  42021. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42022. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42023. engine.updateArrayBuffer(segData);
  42024. buffers.push(buffer);
  42025. }
  42026. ts.partBuffers = buffers;
  42027. }
  42028. else if (gii.transparentDirty) {
  42029. for (var j = 0; j < gii.transparentData.length; j++) {
  42030. var gitd = gii.transparentData[j];
  42031. var dfa = gitd._partData;
  42032. var data = dfa.pack();
  42033. var stride = dfa.stride;
  42034. var buffer = ts.partBuffers[j];
  42035. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42036. engine.bindArrayBuffer(buffer);
  42037. engine.updateArrayBuffer(segData);
  42038. }
  42039. }
  42040. context.useInstancing = true;
  42041. context.instancesCount = count;
  42042. context.instancedBuffers = ts.partBuffers;
  42043. context.groupInfoPartData = gii.transparentData;
  42044. var renderFailed = !mrc.render(gii, context);
  42045. failedCount += renderFailed ? 1 : 0;
  42046. }
  42047. else {
  42048. context.useInstancing = false;
  42049. context.partDataStartIndex = ts.startDataIndex;
  42050. context.partDataEndIndex = ts.endDataIndex;
  42051. context.groupInfoPartData = gii.transparentData;
  42052. var renderFailed = !mrc.render(gii, context);
  42053. failedCount += renderFailed ? 1 : 0;
  42054. }
  42055. }
  42056. return failedCount;
  42057. };
  42058. Group2D.prototype._prepareContext = function (engine, context, gii) {
  42059. var gipd = null;
  42060. var setDirty;
  42061. var getDirty;
  42062. // Render Mode specifics
  42063. switch (context.renderMode) {
  42064. case BABYLON.Render2DContext.RenderModeOpaque:
  42065. {
  42066. if (!gii.hasOpaqueData) {
  42067. return null;
  42068. }
  42069. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  42070. getDirty = function () { return gii.opaqueDirty; };
  42071. context.groupInfoPartData = gii.opaqueData;
  42072. gipd = gii.opaqueData;
  42073. break;
  42074. }
  42075. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42076. {
  42077. if (!gii.hasAlphaTestData) {
  42078. return null;
  42079. }
  42080. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  42081. getDirty = function () { return gii.alphaTestDirty; };
  42082. context.groupInfoPartData = gii.alphaTestData;
  42083. gipd = gii.alphaTestData;
  42084. break;
  42085. }
  42086. default:
  42087. throw new Error("_prepareContext is only for opaque or alphaTest");
  42088. }
  42089. var renderCount = 0;
  42090. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  42091. // Skip it if instanced arrays are not supported
  42092. if (this.owner.supportInstancedArray) {
  42093. // Flag for instancing
  42094. context.useInstancing = true;
  42095. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  42096. for (var i = 0; i < gipd.length; i++) {
  42097. var pid = gipd[i];
  42098. // If the instances of the model was changed, pack the data
  42099. var array = pid._partData;
  42100. var instanceData_1 = array.pack();
  42101. renderCount += array.usedElementCount;
  42102. // Compute the size the instance buffer should have
  42103. var neededSize = array.usedElementCount * array.stride * 4;
  42104. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  42105. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  42106. if (pid._partBuffer) {
  42107. engine.deleteInstancesBuffer(pid._partBuffer);
  42108. }
  42109. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42110. pid._partBufferSize = neededSize;
  42111. setDirty(false);
  42112. // Update the WebGL buffer to match the new content of the instances data
  42113. engine.updateArrayBuffer(instanceData_1);
  42114. }
  42115. else if (getDirty()) {
  42116. // Update the WebGL buffer to match the new content of the instances data
  42117. engine.bindArrayBuffer(pid._partBuffer);
  42118. engine.updateArrayBuffer(instanceData_1);
  42119. }
  42120. }
  42121. setDirty(false);
  42122. }
  42123. else {
  42124. context.partDataStartIndex = 0;
  42125. // Find the first valid object to get the count
  42126. if (context.groupInfoPartData.length > 0) {
  42127. var i = 0;
  42128. while (!context.groupInfoPartData[i]) {
  42129. i++;
  42130. }
  42131. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  42132. }
  42133. }
  42134. return renderCount;
  42135. };
  42136. Group2D.prototype._setRenderingScale = function (scale) {
  42137. if (this._renderableData._renderingScale === scale) {
  42138. return;
  42139. }
  42140. this._renderableData._renderingScale = scale;
  42141. };
  42142. Group2D.prototype._bindCacheTarget = function () {
  42143. var curWidth;
  42144. var curHeight;
  42145. var rd = this._renderableData;
  42146. var rs = rd._renderingScale;
  42147. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  42148. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  42149. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  42150. if (rd._cacheNode) {
  42151. var size = rd._cacheNode.contentSize;
  42152. // Check if we have to deallocate because the size is too small
  42153. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  42154. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  42155. // For World space: no over-provisioning
  42156. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  42157. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  42158. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  42159. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  42160. rd._cacheTexture.freeRect(rd._cacheNode);
  42161. rd._cacheNode = null;
  42162. }
  42163. }
  42164. if (!rd._cacheNode) {
  42165. // Check if we have to allocate a rendering zone in the global cache texture
  42166. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  42167. rd._cacheNode = res.node;
  42168. rd._cacheTexture = res.texture;
  42169. rd._cacheRenderSprite = res.sprite;
  42170. sizeChanged = true;
  42171. }
  42172. if (sizeChanged) {
  42173. rd._cacheSize.copyFrom(Group2D._s);
  42174. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  42175. this.scale = this._renderableData._renderingScale;
  42176. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  42177. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  42178. }
  42179. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  42180. }
  42181. var n = rd._cacheNode;
  42182. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  42183. };
  42184. Group2D.prototype._unbindCacheTarget = function () {
  42185. if (this._renderableData._cacheTexture) {
  42186. this._renderableData._cacheTexture.unbindTexture();
  42187. }
  42188. };
  42189. Group2D.prototype.handleGroupChanged = function (prop) {
  42190. // This method is only for cachedGroup
  42191. var rd = this._renderableData;
  42192. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  42193. return;
  42194. }
  42195. // For now we only support these property changes
  42196. // TODO: add more! :)
  42197. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  42198. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  42199. }
  42200. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  42201. rd._cacheRenderSprite.rotation = this.rotation;
  42202. }
  42203. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  42204. rd._cacheRenderSprite.scale = this.scale;
  42205. }
  42206. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  42207. rd._cacheRenderSprite.origin = this.origin.clone();
  42208. }
  42209. else if (prop.id === Group2D.actualSizeProperty.id) {
  42210. rd._cacheRenderSprite.size = this.actualSize.clone();
  42211. }
  42212. };
  42213. Group2D.prototype.detectGroupStates = function () {
  42214. var isCanvas = this instanceof BABYLON.Canvas2D;
  42215. var canvasStrat = this.owner.cachingStrategy;
  42216. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  42217. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  42218. this._isRenderableGroup = isCanvas;
  42219. this._isCachedGroup = false;
  42220. }
  42221. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  42222. if (isCanvas) {
  42223. this._isRenderableGroup = true;
  42224. this._isCachedGroup = true;
  42225. }
  42226. else {
  42227. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  42228. this._isCachedGroup = false;
  42229. }
  42230. }
  42231. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42232. if (isCanvas) {
  42233. this._isRenderableGroup = true;
  42234. this._isCachedGroup = false;
  42235. }
  42236. else {
  42237. if (this.hierarchyDepth === 1) {
  42238. this._isRenderableGroup = true;
  42239. this._isCachedGroup = true;
  42240. }
  42241. else {
  42242. this._isRenderableGroup = false;
  42243. this._isCachedGroup = false;
  42244. }
  42245. }
  42246. }
  42247. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  42248. var gcb = this.cacheBehavior;
  42249. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  42250. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  42251. this._isCachedGroup = false;
  42252. }
  42253. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  42254. this._isRenderableGroup = true;
  42255. this._isCachedGroup = true;
  42256. }
  42257. }
  42258. if (this._isRenderableGroup) {
  42259. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  42260. if (!this._renderableData) {
  42261. this._renderableData = new RenderableGroupData();
  42262. }
  42263. }
  42264. // If the group is tagged as renderable we add it to the renderable tree
  42265. if (this._isCachedGroup) {
  42266. var cur = this.parent;
  42267. while (cur) {
  42268. if (cur instanceof Group2D && cur._isRenderableGroup) {
  42269. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  42270. cur._renderableData._childrenRenderableGroups.push(this);
  42271. }
  42272. break;
  42273. }
  42274. cur = cur.parent;
  42275. }
  42276. }
  42277. };
  42278. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42279. /**
  42280. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  42281. */
  42282. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  42283. /**
  42284. * When used, this group's content won't be cached, no matter which strategy used.
  42285. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  42286. */
  42287. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  42288. /**
  42289. * When used, the group's content will be cached in the nearest cached parent group/canvas
  42290. */
  42291. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  42292. Group2D._s = BABYLON.Size.Zero();
  42293. __decorate([
  42294. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  42295. ], Group2D.prototype, "size", null);
  42296. __decorate([
  42297. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  42298. ], Group2D.prototype, "actualSize", null);
  42299. Group2D = __decorate([
  42300. BABYLON.className("Group2D")
  42301. ], Group2D);
  42302. return Group2D;
  42303. })(BABYLON.Prim2DBase);
  42304. BABYLON.Group2D = Group2D;
  42305. var RenderableGroupData = (function () {
  42306. function RenderableGroupData() {
  42307. this._primDirtyList = new Array();
  42308. this._childrenRenderableGroups = new Array();
  42309. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  42310. this._transparentPrimitives = new Array();
  42311. this._transparentSegments = new Array();
  42312. this._transparentListChanged = false;
  42313. this._cacheNode = null;
  42314. this._cacheTexture = null;
  42315. this._cacheRenderSprite = null;
  42316. this._renderingScale = 1;
  42317. this._cacheNodeUVs = null;
  42318. this._cacheNodeUVsChangedObservable = null;
  42319. this._cacheSize = BABYLON.Size.Zero();
  42320. this._useMipMap = false;
  42321. this._anisotropicLevel = 1;
  42322. }
  42323. RenderableGroupData.prototype.dispose = function (engine) {
  42324. if (this._cacheRenderSprite) {
  42325. this._cacheRenderSprite.dispose();
  42326. this._cacheRenderSprite = null;
  42327. }
  42328. if (this._cacheTexture && this._cacheNode) {
  42329. this._cacheTexture.freeRect(this._cacheNode);
  42330. this._cacheTexture = null;
  42331. this._cacheNode = null;
  42332. }
  42333. if (this._primDirtyList) {
  42334. this._primDirtyList.splice(0);
  42335. this._primDirtyList = null;
  42336. }
  42337. if (this._renderGroupInstancesInfo) {
  42338. this._renderGroupInstancesInfo.forEach(function (k, v) {
  42339. v.dispose();
  42340. });
  42341. this._renderGroupInstancesInfo = null;
  42342. }
  42343. if (this._cacheNodeUVsChangedObservable) {
  42344. this._cacheNodeUVsChangedObservable.clear();
  42345. this._cacheNodeUVsChangedObservable = null;
  42346. }
  42347. if (this._transparentSegments) {
  42348. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  42349. var ts = _a[_i];
  42350. ts.dispose(engine);
  42351. }
  42352. this._transparentSegments.splice(0);
  42353. this._transparentSegments = null;
  42354. }
  42355. };
  42356. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  42357. var tpi = new TransparentPrimitiveInfo();
  42358. tpi._primitive = prim;
  42359. tpi._groupInstanceInfo = gii;
  42360. tpi._transparentSegment = null;
  42361. this._transparentPrimitives.push(tpi);
  42362. this._transparentListChanged = true;
  42363. return tpi;
  42364. };
  42365. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  42366. var index = this._transparentPrimitives.indexOf(tpi);
  42367. if (index !== -1) {
  42368. this._transparentPrimitives.splice(index, 1);
  42369. this._transparentListChanged = true;
  42370. }
  42371. };
  42372. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  42373. this._transparentListChanged = true;
  42374. //this.updateSmallestZChangedPrim(tpi);
  42375. };
  42376. return RenderableGroupData;
  42377. })();
  42378. BABYLON.RenderableGroupData = RenderableGroupData;
  42379. var TransparentPrimitiveInfo = (function () {
  42380. function TransparentPrimitiveInfo() {
  42381. }
  42382. return TransparentPrimitiveInfo;
  42383. })();
  42384. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  42385. })(BABYLON || (BABYLON = {}));
  42386. var BABYLON;
  42387. (function (BABYLON) {
  42388. var Rectangle2DRenderCache = (function (_super) {
  42389. __extends(Rectangle2DRenderCache, _super);
  42390. function Rectangle2DRenderCache(engine, modelKey) {
  42391. _super.call(this, engine, modelKey);
  42392. this.effectsReady = false;
  42393. this.fillVB = null;
  42394. this.fillIB = null;
  42395. this.fillIndicesCount = 0;
  42396. this.instancingFillAttributes = null;
  42397. this.effectFill = null;
  42398. this.effectFillInstanced = null;
  42399. this.borderVB = null;
  42400. this.borderIB = null;
  42401. this.borderIndicesCount = 0;
  42402. this.instancingBorderAttributes = null;
  42403. this.effectBorder = null;
  42404. this.effectBorderInstanced = null;
  42405. }
  42406. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  42407. // Do nothing if the shader is still loading/preparing
  42408. if (!this.effectsReady) {
  42409. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42410. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42411. return false;
  42412. }
  42413. this.effectsReady = true;
  42414. }
  42415. var canvas = instanceInfo.owner.owner;
  42416. var engine = canvas.engine;
  42417. var depthFunction = 0;
  42418. if (this.effectFill && this.effectBorder) {
  42419. depthFunction = engine.getDepthFunction();
  42420. engine.setDepthFunctionToLessOrEqual();
  42421. }
  42422. var curAlphaMode = engine.getAlphaMode();
  42423. if (this.effectFill) {
  42424. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42425. var pid = context.groupInfoPartData[partIndex];
  42426. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42427. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42428. }
  42429. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42430. engine.enableEffect(effect);
  42431. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42432. if (context.useInstancing) {
  42433. if (!this.instancingFillAttributes) {
  42434. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42435. }
  42436. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42437. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42438. canvas._addDrawCallCount(1, context.renderMode);
  42439. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  42440. engine.draw(true, 0, this.fillIndicesCount, count);
  42441. engine.unbindInstanceAttributes();
  42442. }
  42443. else {
  42444. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42445. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42446. this.setupUniforms(effect, partIndex, pid._partData, i);
  42447. engine.draw(true, 0, this.fillIndicesCount);
  42448. }
  42449. }
  42450. }
  42451. if (this.effectBorder) {
  42452. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42453. var pid = context.groupInfoPartData[partIndex];
  42454. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42455. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42456. }
  42457. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42458. engine.enableEffect(effect);
  42459. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42460. if (context.useInstancing) {
  42461. if (!this.instancingBorderAttributes) {
  42462. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42463. }
  42464. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42465. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42466. canvas._addDrawCallCount(1, context.renderMode);
  42467. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  42468. engine.draw(true, 0, this.borderIndicesCount, count);
  42469. engine.unbindInstanceAttributes();
  42470. }
  42471. else {
  42472. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42473. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42474. this.setupUniforms(effect, partIndex, pid._partData, i);
  42475. engine.draw(true, 0, this.borderIndicesCount);
  42476. }
  42477. }
  42478. }
  42479. engine.setAlphaMode(curAlphaMode);
  42480. if (this.effectFill && this.effectBorder) {
  42481. engine.setDepthFunction(depthFunction);
  42482. }
  42483. return true;
  42484. };
  42485. Rectangle2DRenderCache.prototype.dispose = function () {
  42486. if (!_super.prototype.dispose.call(this)) {
  42487. return false;
  42488. }
  42489. if (this.fillVB) {
  42490. this._engine._releaseBuffer(this.fillVB);
  42491. this.fillVB = null;
  42492. }
  42493. if (this.fillIB) {
  42494. this._engine._releaseBuffer(this.fillIB);
  42495. this.fillIB = null;
  42496. }
  42497. if (this.effectFill) {
  42498. this._engine._releaseEffect(this.effectFill);
  42499. this.effectFill = null;
  42500. }
  42501. if (this.effectFillInstanced) {
  42502. this._engine._releaseEffect(this.effectFillInstanced);
  42503. this.effectFillInstanced = null;
  42504. }
  42505. if (this.borderVB) {
  42506. this._engine._releaseBuffer(this.borderVB);
  42507. this.borderVB = null;
  42508. }
  42509. if (this.borderIB) {
  42510. this._engine._releaseBuffer(this.borderIB);
  42511. this.borderIB = null;
  42512. }
  42513. if (this.effectBorder) {
  42514. this._engine._releaseEffect(this.effectBorder);
  42515. this.effectBorder = null;
  42516. }
  42517. if (this.effectBorderInstanced) {
  42518. this._engine._releaseEffect(this.effectBorderInstanced);
  42519. this.effectBorderInstanced = null;
  42520. }
  42521. return true;
  42522. };
  42523. return Rectangle2DRenderCache;
  42524. })(BABYLON.ModelRenderCache);
  42525. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  42526. var Rectangle2DInstanceData = (function (_super) {
  42527. __extends(Rectangle2DInstanceData, _super);
  42528. function Rectangle2DInstanceData(partId) {
  42529. _super.call(this, partId, 1);
  42530. }
  42531. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  42532. get: function () {
  42533. return null;
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. __decorate([
  42539. BABYLON.instanceData()
  42540. ], Rectangle2DInstanceData.prototype, "properties", null);
  42541. return Rectangle2DInstanceData;
  42542. })(BABYLON.Shape2DInstanceData);
  42543. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  42544. var Rectangle2D = (function (_super) {
  42545. __extends(Rectangle2D, _super);
  42546. /**
  42547. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  42548. * @param settings a combination of settings, possible ones are
  42549. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42550. * - children: an array of direct children
  42551. * - id a text identifier, for information purpose
  42552. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  42553. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42554. * - scale: the initial scale of the primitive. default is 1
  42555. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  42556. * - origin: define the normalized origin point location, default [0.5;0.5]
  42557. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  42558. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  42559. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  42560. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  42561. * - borderThickness: the thickness of the drawn border, default is 1.
  42562. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42563. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  42564. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42565. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42566. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42567. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42568. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42569. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42570. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42571. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42572. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42573. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42574. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42575. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42576. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42577. */
  42578. function Rectangle2D(settings) {
  42579. // Avoid checking every time if the object exists
  42580. if (settings == null) {
  42581. settings = {};
  42582. }
  42583. _super.call(this, settings);
  42584. if (settings.size != null) {
  42585. this.size = settings.size;
  42586. }
  42587. else if (settings.width || settings.height) {
  42588. var size = new BABYLON.Size(settings.width, settings.height);
  42589. this.size = size;
  42590. }
  42591. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  42592. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  42593. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  42594. //this.size = size;
  42595. this.roundRadius = roundRadius;
  42596. this.borderThickness = borderThickness;
  42597. }
  42598. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  42599. get: function () {
  42600. if (this._actualSize) {
  42601. return this._actualSize;
  42602. }
  42603. return this.size;
  42604. },
  42605. set: function (value) {
  42606. this._actualSize = value;
  42607. },
  42608. enumerable: true,
  42609. configurable: true
  42610. });
  42611. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  42612. get: function () {
  42613. return this._notRounded;
  42614. },
  42615. set: function (value) {
  42616. this._notRounded = value;
  42617. },
  42618. enumerable: true,
  42619. configurable: true
  42620. });
  42621. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  42622. get: function () {
  42623. return this._roundRadius;
  42624. },
  42625. set: function (value) {
  42626. this._roundRadius = value;
  42627. this.notRounded = value === 0;
  42628. this._positioningDirty();
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  42634. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  42635. if (this.notRounded) {
  42636. return true;
  42637. }
  42638. // 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.
  42639. // 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)
  42640. // 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.
  42641. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  42642. var size = this.size;
  42643. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  42644. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  42645. var rr = this.roundRadius;
  42646. var rrs = rr * rr;
  42647. // Check if the point is in the bottom/left quarter area
  42648. Rectangle2D._i1.x = rr;
  42649. Rectangle2D._i1.y = rr;
  42650. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42651. // Compute the intersection point in the quarter local space
  42652. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42653. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42654. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42655. return Rectangle2D._i2.lengthSquared() <= rrs;
  42656. }
  42657. // Check if the point is in the top/left quarter area
  42658. Rectangle2D._i1.x = rr;
  42659. Rectangle2D._i1.y = size.height - rr;
  42660. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42661. // Compute the intersection point in the quarter local space
  42662. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42663. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42664. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42665. return Rectangle2D._i2.lengthSquared() <= rrs;
  42666. }
  42667. // Check if the point is in the top/right quarter area
  42668. Rectangle2D._i1.x = size.width - rr;
  42669. Rectangle2D._i1.y = size.height - rr;
  42670. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42671. // Compute the intersection point in the quarter local space
  42672. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42673. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42674. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42675. return Rectangle2D._i2.lengthSquared() <= rrs;
  42676. }
  42677. // Check if the point is in the bottom/right quarter area
  42678. Rectangle2D._i1.x = size.width - rr;
  42679. Rectangle2D._i1.y = rr;
  42680. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42681. // Compute the intersection point in the quarter local space
  42682. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42683. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42684. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42685. return Rectangle2D._i2.lengthSquared() <= rrs;
  42686. }
  42687. // At any other locations the point is guarantied to be inside
  42688. return true;
  42689. };
  42690. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  42691. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42692. };
  42693. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  42694. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  42695. return renderCache;
  42696. };
  42697. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42698. var renderCache = modelRenderCache;
  42699. var engine = this.owner.engine;
  42700. // Need to create WebGL resources for fill part?
  42701. if (this.fill) {
  42702. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  42703. var vb = new Float32Array(vbSize);
  42704. for (var i = 0; i < vbSize; i++) {
  42705. vb[i] = i;
  42706. }
  42707. renderCache.fillVB = engine.createVertexBuffer(vb);
  42708. var triCount = vbSize - 1;
  42709. var ib = new Float32Array(triCount * 3);
  42710. for (var i = 0; i < triCount; i++) {
  42711. ib[i * 3 + 0] = 0;
  42712. ib[i * 3 + 2] = i + 1;
  42713. ib[i * 3 + 1] = i + 2;
  42714. }
  42715. ib[triCount * 3 - 2] = 1;
  42716. renderCache.fillIB = engine.createIndexBuffer(ib);
  42717. renderCache.fillIndicesCount = triCount * 3;
  42718. // 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
  42719. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  42720. if (ei) {
  42721. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42722. }
  42723. // Get the non instanced version
  42724. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  42725. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42726. }
  42727. // Need to create WebGL resource for border part?
  42728. if (this.border) {
  42729. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  42730. var vb = new Float32Array(vbSize);
  42731. for (var i = 0; i < vbSize; i++) {
  42732. vb[i] = i;
  42733. }
  42734. renderCache.borderVB = engine.createVertexBuffer(vb);
  42735. var triCount = vbSize;
  42736. var rs = triCount / 2;
  42737. var ib = new Float32Array(triCount * 3);
  42738. for (var i = 0; i < rs; i++) {
  42739. var r0 = i;
  42740. var r1 = (i + 1) % rs;
  42741. ib[i * 6 + 0] = rs + r1;
  42742. ib[i * 6 + 1] = rs + r0;
  42743. ib[i * 6 + 2] = r0;
  42744. ib[i * 6 + 3] = r1;
  42745. ib[i * 6 + 4] = rs + r1;
  42746. ib[i * 6 + 5] = r0;
  42747. }
  42748. renderCache.borderIB = engine.createIndexBuffer(ib);
  42749. renderCache.borderIndicesCount = triCount * 3;
  42750. // 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
  42751. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  42752. if (ei) {
  42753. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42754. }
  42755. // Get the non instanced version
  42756. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  42757. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  42758. }
  42759. return renderCache;
  42760. };
  42761. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  42762. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42763. // Fall back to default implementation if there's no round Radius
  42764. if (this._notRounded) {
  42765. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  42766. }
  42767. else {
  42768. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  42769. initialContentPosition.x = initialContentPosition.y = rr;
  42770. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  42771. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  42772. }
  42773. };
  42774. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42775. // Fall back to default implementation if there's no round Radius
  42776. if (this._notRounded) {
  42777. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  42778. }
  42779. else {
  42780. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  42781. newPrimSize.copyFrom(primSize);
  42782. newPrimSize.width += rr * 2;
  42783. newPrimSize.height += rr * 2;
  42784. }
  42785. };
  42786. Rectangle2D.prototype.createInstanceDataParts = function () {
  42787. var res = new Array();
  42788. if (this.border) {
  42789. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  42790. }
  42791. if (this.fill) {
  42792. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  42793. }
  42794. return res;
  42795. };
  42796. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  42797. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  42798. return false;
  42799. }
  42800. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  42801. var d = part;
  42802. var size = this.actualSize;
  42803. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  42804. }
  42805. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  42806. var d = part;
  42807. var size = this.actualSize;
  42808. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  42809. }
  42810. return true;
  42811. };
  42812. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  42813. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  42814. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  42815. Rectangle2D.roundSubdivisions = 16;
  42816. __decorate([
  42817. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  42818. ], Rectangle2D.prototype, "actualSize", null);
  42819. __decorate([
  42820. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  42821. ], Rectangle2D.prototype, "notRounded", null);
  42822. __decorate([
  42823. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  42824. ], Rectangle2D.prototype, "roundRadius", null);
  42825. Rectangle2D = __decorate([
  42826. BABYLON.className("Rectangle2D")
  42827. ], Rectangle2D);
  42828. return Rectangle2D;
  42829. })(BABYLON.Shape2D);
  42830. BABYLON.Rectangle2D = Rectangle2D;
  42831. })(BABYLON || (BABYLON = {}));
  42832. var BABYLON;
  42833. (function (BABYLON) {
  42834. var Ellipse2DRenderCache = (function (_super) {
  42835. __extends(Ellipse2DRenderCache, _super);
  42836. function Ellipse2DRenderCache(engine, modelKey) {
  42837. _super.call(this, engine, modelKey);
  42838. this.effectsReady = false;
  42839. this.fillVB = null;
  42840. this.fillIB = null;
  42841. this.fillIndicesCount = 0;
  42842. this.instancingFillAttributes = null;
  42843. this.effectFillInstanced = null;
  42844. this.effectFill = null;
  42845. this.borderVB = null;
  42846. this.borderIB = null;
  42847. this.borderIndicesCount = 0;
  42848. this.instancingBorderAttributes = null;
  42849. this.effectBorderInstanced = null;
  42850. this.effectBorder = null;
  42851. }
  42852. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  42853. // Do nothing if the shader is still loading/preparing
  42854. if (!this.effectsReady) {
  42855. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42856. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42857. return false;
  42858. }
  42859. this.effectsReady = true;
  42860. }
  42861. var canvas = instanceInfo.owner.owner;
  42862. var engine = canvas.engine;
  42863. var depthFunction = 0;
  42864. if (this.effectFill && this.effectBorder) {
  42865. depthFunction = engine.getDepthFunction();
  42866. engine.setDepthFunctionToLessOrEqual();
  42867. }
  42868. var curAlphaMode = engine.getAlphaMode();
  42869. if (this.effectFill) {
  42870. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42871. var pid = context.groupInfoPartData[partIndex];
  42872. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42873. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42874. }
  42875. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42876. engine.enableEffect(effect);
  42877. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42878. if (context.useInstancing) {
  42879. if (!this.instancingFillAttributes) {
  42880. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42881. }
  42882. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42883. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42884. canvas._addDrawCallCount(1, context.renderMode);
  42885. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  42886. engine.draw(true, 0, this.fillIndicesCount, count);
  42887. engine.unbindInstanceAttributes();
  42888. }
  42889. else {
  42890. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42891. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42892. this.setupUniforms(effect, partIndex, pid._partData, i);
  42893. engine.draw(true, 0, this.fillIndicesCount);
  42894. }
  42895. }
  42896. }
  42897. if (this.effectBorder) {
  42898. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42899. var pid = context.groupInfoPartData[partIndex];
  42900. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42901. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42902. }
  42903. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42904. engine.enableEffect(effect);
  42905. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42906. if (context.useInstancing) {
  42907. if (!this.instancingBorderAttributes) {
  42908. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42909. }
  42910. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42911. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42912. canvas._addDrawCallCount(1, context.renderMode);
  42913. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  42914. engine.draw(true, 0, this.borderIndicesCount, count);
  42915. engine.unbindInstanceAttributes();
  42916. }
  42917. else {
  42918. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42919. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42920. this.setupUniforms(effect, partIndex, pid._partData, i);
  42921. engine.draw(true, 0, this.borderIndicesCount);
  42922. }
  42923. }
  42924. }
  42925. engine.setAlphaMode(curAlphaMode);
  42926. if (this.effectFill && this.effectBorder) {
  42927. engine.setDepthFunction(depthFunction);
  42928. }
  42929. return true;
  42930. };
  42931. Ellipse2DRenderCache.prototype.dispose = function () {
  42932. if (!_super.prototype.dispose.call(this)) {
  42933. return false;
  42934. }
  42935. if (this.fillVB) {
  42936. this._engine._releaseBuffer(this.fillVB);
  42937. this.fillVB = null;
  42938. }
  42939. if (this.fillIB) {
  42940. this._engine._releaseBuffer(this.fillIB);
  42941. this.fillIB = null;
  42942. }
  42943. if (this.effectFill) {
  42944. this._engine._releaseEffect(this.effectFill);
  42945. this.effectFill = null;
  42946. }
  42947. if (this.effectFillInstanced) {
  42948. this._engine._releaseEffect(this.effectFillInstanced);
  42949. this.effectFillInstanced = null;
  42950. }
  42951. if (this.borderVB) {
  42952. this._engine._releaseBuffer(this.borderVB);
  42953. this.borderVB = null;
  42954. }
  42955. if (this.borderIB) {
  42956. this._engine._releaseBuffer(this.borderIB);
  42957. this.borderIB = null;
  42958. }
  42959. if (this.effectBorder) {
  42960. this._engine._releaseEffect(this.effectBorder);
  42961. this.effectBorder = null;
  42962. }
  42963. if (this.effectBorderInstanced) {
  42964. this._engine._releaseEffect(this.effectBorderInstanced);
  42965. this.effectBorderInstanced = null;
  42966. }
  42967. return true;
  42968. };
  42969. return Ellipse2DRenderCache;
  42970. })(BABYLON.ModelRenderCache);
  42971. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  42972. var Ellipse2DInstanceData = (function (_super) {
  42973. __extends(Ellipse2DInstanceData, _super);
  42974. function Ellipse2DInstanceData(partId) {
  42975. _super.call(this, partId, 1);
  42976. }
  42977. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  42978. get: function () {
  42979. return null;
  42980. },
  42981. enumerable: true,
  42982. configurable: true
  42983. });
  42984. __decorate([
  42985. BABYLON.instanceData()
  42986. ], Ellipse2DInstanceData.prototype, "properties", null);
  42987. return Ellipse2DInstanceData;
  42988. })(BABYLON.Shape2DInstanceData);
  42989. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  42990. var Ellipse2D = (function (_super) {
  42991. __extends(Ellipse2D, _super);
  42992. /**
  42993. * Create an Ellipse 2D Shape primitive
  42994. * @param settings a combination of settings, possible ones are
  42995. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  42996. * - children: an array of direct children
  42997. * - id: a text identifier, for information purpose
  42998. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  42999. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43000. * - scale: the initial scale of the primitive. default is 1
  43001. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43002. * - origin: define the normalized origin point location, default [0.5;0.5]
  43003. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  43004. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  43005. * - 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. can also be a string value (see Canvas2D.GetBrushFromString)
  43006. * - 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. can be a string value (see Canvas2D.GetBrushFromString)
  43007. * - borderThickness: the thickness of the drawn border, default is 1.
  43008. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43009. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43010. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43011. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43012. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43013. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43014. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43015. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43016. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43017. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43018. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43019. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43020. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43021. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43022. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43023. */
  43024. function Ellipse2D(settings) {
  43025. // Avoid checking every time if the object exists
  43026. if (settings == null) {
  43027. settings = {};
  43028. }
  43029. _super.call(this, settings);
  43030. if (settings.size != null) {
  43031. this.size = settings.size;
  43032. }
  43033. else if (settings.width || settings.height) {
  43034. var size = new BABYLON.Size(settings.width, settings.height);
  43035. this.size = size;
  43036. }
  43037. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  43038. this.subdivisions = sub;
  43039. }
  43040. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  43041. get: function () {
  43042. if (this._actualSize) {
  43043. return this._actualSize;
  43044. }
  43045. return this.size;
  43046. },
  43047. set: function (value) {
  43048. this._actualSize = value;
  43049. },
  43050. enumerable: true,
  43051. configurable: true
  43052. });
  43053. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  43054. get: function () {
  43055. return this._subdivisions;
  43056. },
  43057. set: function (value) {
  43058. this._subdivisions = value;
  43059. },
  43060. enumerable: true,
  43061. configurable: true
  43062. });
  43063. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  43064. var w = this.size.width / 2;
  43065. var h = this.size.height / 2;
  43066. var x = intersectInfo._localPickPosition.x - w;
  43067. var y = intersectInfo._localPickPosition.y - h;
  43068. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  43069. };
  43070. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  43071. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43072. };
  43073. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  43074. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  43075. return renderCache;
  43076. };
  43077. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43078. var renderCache = modelRenderCache;
  43079. var engine = this.owner.engine;
  43080. // Need to create WebGL resources for fill part?
  43081. if (this.fill) {
  43082. var vbSize = this.subdivisions + 1;
  43083. var vb = new Float32Array(vbSize);
  43084. for (var i = 0; i < vbSize; i++) {
  43085. vb[i] = i;
  43086. }
  43087. renderCache.fillVB = engine.createVertexBuffer(vb);
  43088. var triCount = vbSize - 1;
  43089. var ib = new Float32Array(triCount * 3);
  43090. for (var i = 0; i < triCount; i++) {
  43091. ib[i * 3 + 0] = 0;
  43092. ib[i * 3 + 2] = i + 1;
  43093. ib[i * 3 + 1] = i + 2;
  43094. }
  43095. ib[triCount * 3 - 2] = 1;
  43096. renderCache.fillIB = engine.createIndexBuffer(ib);
  43097. renderCache.fillIndicesCount = triCount * 3;
  43098. // 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
  43099. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43100. if (ei) {
  43101. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43102. }
  43103. // Get the non instanced version
  43104. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43105. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43106. }
  43107. // Need to create WebGL resource for border part?
  43108. if (this.border) {
  43109. var vbSize = this.subdivisions * 2;
  43110. var vb = new Float32Array(vbSize);
  43111. for (var i = 0; i < vbSize; i++) {
  43112. vb[i] = i;
  43113. }
  43114. renderCache.borderVB = engine.createVertexBuffer(vb);
  43115. var triCount = vbSize;
  43116. var rs = triCount / 2;
  43117. var ib = new Float32Array(triCount * 3);
  43118. for (var i = 0; i < rs; i++) {
  43119. var r0 = i;
  43120. var r1 = (i + 1) % rs;
  43121. ib[i * 6 + 0] = rs + r1;
  43122. ib[i * 6 + 1] = rs + r0;
  43123. ib[i * 6 + 2] = r0;
  43124. ib[i * 6 + 3] = r1;
  43125. ib[i * 6 + 4] = rs + r1;
  43126. ib[i * 6 + 5] = r0;
  43127. }
  43128. renderCache.borderIB = engine.createIndexBuffer(ib);
  43129. renderCache.borderIndicesCount = (triCount * 3);
  43130. // 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
  43131. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43132. if (ei) {
  43133. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43134. }
  43135. // Get the non instanced version
  43136. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43137. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43138. }
  43139. return renderCache;
  43140. };
  43141. Ellipse2D.prototype.createInstanceDataParts = function () {
  43142. var res = new Array();
  43143. if (this.border) {
  43144. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43145. }
  43146. if (this.fill) {
  43147. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43148. }
  43149. return res;
  43150. };
  43151. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  43152. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43153. return false;
  43154. }
  43155. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43156. var d = part;
  43157. var size = this.actualSize;
  43158. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43159. }
  43160. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43161. var d = part;
  43162. var size = this.actualSize;
  43163. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43164. }
  43165. return true;
  43166. };
  43167. __decorate([
  43168. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  43169. ], Ellipse2D.prototype, "actualSize", null);
  43170. __decorate([
  43171. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  43172. ], Ellipse2D.prototype, "subdivisions", null);
  43173. Ellipse2D = __decorate([
  43174. BABYLON.className("Ellipse2D")
  43175. ], Ellipse2D);
  43176. return Ellipse2D;
  43177. })(BABYLON.Shape2D);
  43178. BABYLON.Ellipse2D = Ellipse2D;
  43179. })(BABYLON || (BABYLON = {}));
  43180. var BABYLON;
  43181. (function (BABYLON) {
  43182. var Sprite2DRenderCache = (function (_super) {
  43183. __extends(Sprite2DRenderCache, _super);
  43184. function Sprite2DRenderCache() {
  43185. _super.apply(this, arguments);
  43186. this.effectsReady = false;
  43187. this.vb = null;
  43188. this.ib = null;
  43189. this.instancingAttributes = null;
  43190. this.texture = null;
  43191. this.effect = null;
  43192. this.effectInstanced = null;
  43193. }
  43194. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  43195. // Do nothing if the shader is still loading/preparing
  43196. if (!this.effectsReady) {
  43197. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43198. return false;
  43199. }
  43200. this.effectsReady = true;
  43201. }
  43202. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  43203. var canvas = instanceInfo.owner.owner;
  43204. var engine = canvas.engine;
  43205. var cur = engine.getAlphaMode();
  43206. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43207. engine.enableEffect(effect);
  43208. effect.setTexture("diffuseSampler", this.texture);
  43209. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43210. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43211. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43212. }
  43213. var pid = context.groupInfoPartData[0];
  43214. if (context.useInstancing) {
  43215. if (!this.instancingAttributes) {
  43216. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  43217. }
  43218. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43219. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43220. canvas._addDrawCallCount(1, context.renderMode);
  43221. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43222. engine.draw(true, 0, 6, count);
  43223. engine.unbindInstanceAttributes();
  43224. }
  43225. else {
  43226. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43227. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43228. this.setupUniforms(effect, 0, pid._partData, i);
  43229. engine.draw(true, 0, 6);
  43230. }
  43231. }
  43232. engine.setAlphaMode(cur);
  43233. return true;
  43234. };
  43235. Sprite2DRenderCache.prototype.dispose = function () {
  43236. if (!_super.prototype.dispose.call(this)) {
  43237. return false;
  43238. }
  43239. if (this.vb) {
  43240. this._engine._releaseBuffer(this.vb);
  43241. this.vb = null;
  43242. }
  43243. if (this.ib) {
  43244. this._engine._releaseBuffer(this.ib);
  43245. this.ib = null;
  43246. }
  43247. if (this.texture) {
  43248. this.texture.dispose();
  43249. this.texture = null;
  43250. }
  43251. if (this.effect) {
  43252. this._engine._releaseEffect(this.effect);
  43253. this.effect = null;
  43254. }
  43255. if (this.effectInstanced) {
  43256. this._engine._releaseEffect(this.effectInstanced);
  43257. this.effectInstanced = null;
  43258. }
  43259. return true;
  43260. };
  43261. return Sprite2DRenderCache;
  43262. })(BABYLON.ModelRenderCache);
  43263. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  43264. var Sprite2DInstanceData = (function (_super) {
  43265. __extends(Sprite2DInstanceData, _super);
  43266. function Sprite2DInstanceData(partId) {
  43267. _super.call(this, partId, 1);
  43268. }
  43269. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  43270. get: function () {
  43271. return null;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  43277. get: function () {
  43278. return null;
  43279. },
  43280. enumerable: true,
  43281. configurable: true
  43282. });
  43283. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  43284. get: function () {
  43285. return null;
  43286. },
  43287. enumerable: true,
  43288. configurable: true
  43289. });
  43290. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  43291. // 3 floats being:
  43292. // - x: frame number to display
  43293. // - y: invertY setting
  43294. // - z: alignToPixel setting
  43295. get: function () {
  43296. return null;
  43297. },
  43298. enumerable: true,
  43299. configurable: true
  43300. });
  43301. __decorate([
  43302. BABYLON.instanceData()
  43303. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  43304. __decorate([
  43305. BABYLON.instanceData()
  43306. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  43307. __decorate([
  43308. BABYLON.instanceData()
  43309. ], Sprite2DInstanceData.prototype, "textureSize", null);
  43310. __decorate([
  43311. BABYLON.instanceData()
  43312. ], Sprite2DInstanceData.prototype, "properties", null);
  43313. return Sprite2DInstanceData;
  43314. })(BABYLON.InstanceDataBase);
  43315. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  43316. var Sprite2D = (function (_super) {
  43317. __extends(Sprite2D, _super);
  43318. /**
  43319. * Create an 2D Sprite primitive
  43320. * @param texture the texture that stores the sprite to render
  43321. * @param settings a combination of settings, possible ones are
  43322. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  43323. * - children: an array of direct children
  43324. * - id a text identifier, for information purpose
  43325. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43326. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43327. * - scale: the initial scale of the primitive. default is 1
  43328. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43329. * - origin: define the normalized origin point location, default [0.5;0.5]
  43330. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  43331. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  43332. * - invertY: if true the texture Y will be inverted, default is false.
  43333. * - 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.
  43334. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  43335. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43336. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43337. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43338. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43339. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43340. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43341. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43342. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43343. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43344. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43345. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43346. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43347. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43348. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43349. */
  43350. function Sprite2D(texture, settings) {
  43351. var _this = this;
  43352. if (!settings) {
  43353. settings = {};
  43354. }
  43355. _super.call(this, settings);
  43356. this.texture = texture;
  43357. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43358. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43359. this.size = settings.spriteSize;
  43360. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  43361. this.spriteFrame = 0;
  43362. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  43363. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  43364. this.isAlphaTest = true;
  43365. if (settings.spriteSize == null) {
  43366. if (texture.isReady()) {
  43367. this.size = texture.getSize();
  43368. }
  43369. else {
  43370. texture.onLoadObservable.add(function () {
  43371. _this.size = texture.getSize();
  43372. });
  43373. }
  43374. }
  43375. }
  43376. Object.defineProperty(Sprite2D.prototype, "texture", {
  43377. get: function () {
  43378. return this._texture;
  43379. },
  43380. set: function (value) {
  43381. this._texture = value;
  43382. },
  43383. enumerable: true,
  43384. configurable: true
  43385. });
  43386. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  43387. get: function () {
  43388. if (this._actualSize) {
  43389. return this._actualSize;
  43390. }
  43391. return this.size;
  43392. },
  43393. set: function (value) {
  43394. this._actualSize = value;
  43395. },
  43396. enumerable: true,
  43397. configurable: true
  43398. });
  43399. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  43400. get: function () {
  43401. return this._location;
  43402. },
  43403. set: function (value) {
  43404. this._location = value;
  43405. },
  43406. enumerable: true,
  43407. configurable: true
  43408. });
  43409. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  43410. get: function () {
  43411. return this._spriteFrame;
  43412. },
  43413. set: function (value) {
  43414. this._spriteFrame = value;
  43415. },
  43416. enumerable: true,
  43417. configurable: true
  43418. });
  43419. Object.defineProperty(Sprite2D.prototype, "invertY", {
  43420. get: function () {
  43421. return this._invertY;
  43422. },
  43423. set: function (value) {
  43424. this._invertY = value;
  43425. },
  43426. enumerable: true,
  43427. configurable: true
  43428. });
  43429. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  43430. /**
  43431. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  43432. */
  43433. get: function () {
  43434. return this._alignToPixel;
  43435. },
  43436. set: function (value) {
  43437. this._alignToPixel = value;
  43438. },
  43439. enumerable: true,
  43440. configurable: true
  43441. });
  43442. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  43443. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  43444. };
  43445. /**
  43446. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  43447. */
  43448. Sprite2D.prototype.getAnimatables = function () {
  43449. var res = new Array();
  43450. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  43451. res.push(this.texture);
  43452. }
  43453. return res;
  43454. };
  43455. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  43456. // 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
  43457. return true;
  43458. };
  43459. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  43460. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  43461. return sprite;
  43462. };
  43463. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  43464. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  43465. return renderCache;
  43466. };
  43467. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43468. var renderCache = modelRenderCache;
  43469. var engine = this.owner.engine;
  43470. var vb = new Float32Array(4);
  43471. for (var i = 0; i < 4; i++) {
  43472. vb[i] = i;
  43473. }
  43474. renderCache.vb = engine.createVertexBuffer(vb);
  43475. var ib = new Float32Array(6);
  43476. ib[0] = 0;
  43477. ib[1] = 2;
  43478. ib[2] = 1;
  43479. ib[3] = 0;
  43480. ib[4] = 3;
  43481. ib[5] = 2;
  43482. renderCache.ib = engine.createIndexBuffer(ib);
  43483. renderCache.texture = this.texture;
  43484. // 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
  43485. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  43486. if (ei) {
  43487. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43488. }
  43489. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  43490. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43491. return renderCache;
  43492. };
  43493. Sprite2D.prototype.createInstanceDataParts = function () {
  43494. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  43495. };
  43496. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  43497. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43498. return false;
  43499. }
  43500. if (!this.texture.isReady()) {
  43501. return false;
  43502. }
  43503. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  43504. var d = this._instanceDataParts[0];
  43505. var ts = this.texture.getBaseSize();
  43506. var sl = this.spriteLocation;
  43507. var ss = this.actualSize;
  43508. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  43509. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  43510. d.sizeUV = suv;
  43511. Sprite2D._prop.x = this.spriteFrame;
  43512. Sprite2D._prop.y = this.invertY ? 1 : 0;
  43513. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  43514. d.properties = Sprite2D._prop;
  43515. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43516. }
  43517. return true;
  43518. };
  43519. Sprite2D.SPRITE2D_MAINPARTID = 1;
  43520. Sprite2D._prop = BABYLON.Vector3.Zero();
  43521. __decorate([
  43522. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  43523. ], Sprite2D.prototype, "texture", null);
  43524. __decorate([
  43525. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  43526. ], Sprite2D.prototype, "actualSize", null);
  43527. __decorate([
  43528. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  43529. ], Sprite2D.prototype, "spriteLocation", null);
  43530. __decorate([
  43531. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  43532. ], Sprite2D.prototype, "spriteFrame", null);
  43533. __decorate([
  43534. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  43535. ], Sprite2D.prototype, "invertY", null);
  43536. Sprite2D = __decorate([
  43537. BABYLON.className("Sprite2D")
  43538. ], Sprite2D);
  43539. return Sprite2D;
  43540. })(BABYLON.RenderablePrim2D);
  43541. BABYLON.Sprite2D = Sprite2D;
  43542. })(BABYLON || (BABYLON = {}));
  43543. var BABYLON;
  43544. (function (BABYLON) {
  43545. var Text2DRenderCache = (function (_super) {
  43546. __extends(Text2DRenderCache, _super);
  43547. function Text2DRenderCache() {
  43548. _super.apply(this, arguments);
  43549. this.effectsReady = false;
  43550. this.vb = null;
  43551. this.ib = null;
  43552. this.instancingAttributes = null;
  43553. this.fontTexture = null;
  43554. this.effect = null;
  43555. this.effectInstanced = null;
  43556. }
  43557. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  43558. // Do nothing if the shader is still loading/preparing
  43559. if (!this.effectsReady) {
  43560. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43561. return false;
  43562. }
  43563. this.effectsReady = true;
  43564. }
  43565. var canvas = instanceInfo.owner.owner;
  43566. var engine = canvas.engine;
  43567. this.fontTexture.update();
  43568. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43569. engine.enableEffect(effect);
  43570. effect.setTexture("diffuseSampler", this.fontTexture);
  43571. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43572. var curAlphaMode = engine.getAlphaMode();
  43573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43574. var pid = context.groupInfoPartData[0];
  43575. if (context.useInstancing) {
  43576. if (!this.instancingAttributes) {
  43577. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  43578. }
  43579. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43580. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43581. canvas._addDrawCallCount(1, context.renderMode);
  43582. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43583. engine.draw(true, 0, 6, count);
  43584. engine.unbindInstanceAttributes();
  43585. }
  43586. else {
  43587. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43588. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43589. this.setupUniforms(effect, 0, pid._partData, i);
  43590. engine.draw(true, 0, 6);
  43591. }
  43592. }
  43593. engine.setAlphaMode(curAlphaMode);
  43594. return true;
  43595. };
  43596. Text2DRenderCache.prototype.dispose = function () {
  43597. if (!_super.prototype.dispose.call(this)) {
  43598. return false;
  43599. }
  43600. if (this.vb) {
  43601. this._engine._releaseBuffer(this.vb);
  43602. this.vb = null;
  43603. }
  43604. if (this.ib) {
  43605. this._engine._releaseBuffer(this.ib);
  43606. this.ib = null;
  43607. }
  43608. if (this.fontTexture) {
  43609. this.fontTexture.dispose();
  43610. this.fontTexture = null;
  43611. }
  43612. if (this.effect) {
  43613. this._engine._releaseEffect(this.effect);
  43614. this.effect = null;
  43615. }
  43616. if (this.effectInstanced) {
  43617. this._engine._releaseEffect(this.effectInstanced);
  43618. this.effectInstanced = null;
  43619. }
  43620. return true;
  43621. };
  43622. return Text2DRenderCache;
  43623. })(BABYLON.ModelRenderCache);
  43624. BABYLON.Text2DRenderCache = Text2DRenderCache;
  43625. var Text2DInstanceData = (function (_super) {
  43626. __extends(Text2DInstanceData, _super);
  43627. function Text2DInstanceData(partId, dataElementCount) {
  43628. _super.call(this, partId, dataElementCount);
  43629. }
  43630. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  43631. get: function () {
  43632. return null;
  43633. },
  43634. enumerable: true,
  43635. configurable: true
  43636. });
  43637. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  43638. get: function () {
  43639. return null;
  43640. },
  43641. enumerable: true,
  43642. configurable: true
  43643. });
  43644. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  43645. get: function () {
  43646. return null;
  43647. },
  43648. enumerable: true,
  43649. configurable: true
  43650. });
  43651. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  43652. get: function () {
  43653. return null;
  43654. },
  43655. enumerable: true,
  43656. configurable: true
  43657. });
  43658. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  43659. get: function () {
  43660. return null;
  43661. },
  43662. enumerable: true,
  43663. configurable: true
  43664. });
  43665. __decorate([
  43666. BABYLON.instanceData()
  43667. ], Text2DInstanceData.prototype, "topLeftUV", null);
  43668. __decorate([
  43669. BABYLON.instanceData()
  43670. ], Text2DInstanceData.prototype, "sizeUV", null);
  43671. __decorate([
  43672. BABYLON.instanceData()
  43673. ], Text2DInstanceData.prototype, "textureSize", null);
  43674. __decorate([
  43675. BABYLON.instanceData()
  43676. ], Text2DInstanceData.prototype, "color", null);
  43677. __decorate([
  43678. BABYLON.instanceData()
  43679. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  43680. return Text2DInstanceData;
  43681. })(BABYLON.InstanceDataBase);
  43682. BABYLON.Text2DInstanceData = Text2DInstanceData;
  43683. var Text2D = (function (_super) {
  43684. __extends(Text2D, _super);
  43685. /**
  43686. * Create a Text primitive
  43687. * @param text the text to display
  43688. * @param settings a combination of settings, possible ones are
  43689. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  43690. * - children: an array of direct children
  43691. * - id a text identifier, for information purpose
  43692. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43693. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43694. * - scale: the initial scale of the primitive. default is 1
  43695. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43696. * - origin: define the normalized origin point location, default [0.5;0.5]
  43697. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  43698. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  43699. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  43700. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  43701. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  43702. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  43703. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43704. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43705. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43706. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43707. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43708. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43709. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43710. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43711. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43712. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43713. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43714. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43715. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43716. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43717. */
  43718. function Text2D(text, settings) {
  43719. if (!settings) {
  43720. settings = {};
  43721. }
  43722. _super.call(this, settings);
  43723. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  43724. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  43725. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  43726. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  43727. this._textSize = null;
  43728. this.text = text;
  43729. this.size = (settings.size == null) ? null : settings.size;
  43730. this.isTransparent = true;
  43731. }
  43732. Object.defineProperty(Text2D.prototype, "fontName", {
  43733. get: function () {
  43734. return this._fontName;
  43735. },
  43736. set: function (value) {
  43737. if (this._fontName) {
  43738. throw new Error("Font Name change is not supported right now.");
  43739. }
  43740. this._fontName = value;
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  43746. get: function () {
  43747. return this._defaultFontColor;
  43748. },
  43749. set: function (value) {
  43750. this._defaultFontColor = value;
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(Text2D.prototype, "text", {
  43756. get: function () {
  43757. return this._text;
  43758. },
  43759. set: function (value) {
  43760. this._text = value;
  43761. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  43762. this._size = null;
  43763. this._updateCharCount();
  43764. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  43765. var s = this.textSize;
  43766. },
  43767. enumerable: true,
  43768. configurable: true
  43769. });
  43770. Object.defineProperty(Text2D.prototype, "size", {
  43771. get: function () {
  43772. if (this._size != null) {
  43773. return this._size;
  43774. }
  43775. return this.textSize;
  43776. },
  43777. set: function (value) {
  43778. this._size = value;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(Text2D.prototype, "actualSize", {
  43784. /**
  43785. * Get the actual size of the Text2D primitive
  43786. */
  43787. get: function () {
  43788. if (this._actualSize) {
  43789. return this._actualSize;
  43790. }
  43791. return this.size;
  43792. },
  43793. enumerable: true,
  43794. configurable: true
  43795. });
  43796. Object.defineProperty(Text2D.prototype, "textSize", {
  43797. /**
  43798. * Get the area that bounds the text associated to the primitive
  43799. */
  43800. get: function () {
  43801. if (!this._textSize) {
  43802. if (this.owner) {
  43803. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  43804. if (!newSize.equals(this._textSize)) {
  43805. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  43806. this._positioningDirty();
  43807. }
  43808. this._textSize = newSize;
  43809. }
  43810. else {
  43811. return Text2D.nullSize;
  43812. }
  43813. }
  43814. return this._textSize;
  43815. },
  43816. enumerable: true,
  43817. configurable: true
  43818. });
  43819. Object.defineProperty(Text2D.prototype, "fontTexture", {
  43820. get: function () {
  43821. if (this._fontTexture) {
  43822. return this._fontTexture;
  43823. }
  43824. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  43825. return this._fontTexture;
  43826. },
  43827. enumerable: true,
  43828. configurable: true
  43829. });
  43830. /**
  43831. * Dispose the primitive, remove it from its parent
  43832. */
  43833. Text2D.prototype.dispose = function () {
  43834. if (!_super.prototype.dispose.call(this)) {
  43835. return false;
  43836. }
  43837. if (this._fontTexture) {
  43838. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  43839. this._fontTexture = null;
  43840. }
  43841. return true;
  43842. };
  43843. Text2D.prototype.updateLevelBoundingInfo = function () {
  43844. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43845. };
  43846. Text2D.prototype.levelIntersect = function (intersectInfo) {
  43847. // 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...
  43848. return true;
  43849. };
  43850. Text2D.prototype.createModelRenderCache = function (modelKey) {
  43851. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  43852. return renderCache;
  43853. };
  43854. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43855. var renderCache = modelRenderCache;
  43856. var engine = this.owner.engine;
  43857. renderCache.fontTexture = this.fontTexture;
  43858. var vb = new Float32Array(4);
  43859. for (var i = 0; i < 4; i++) {
  43860. vb[i] = i;
  43861. }
  43862. renderCache.vb = engine.createVertexBuffer(vb);
  43863. var ib = new Float32Array(6);
  43864. ib[0] = 0;
  43865. ib[1] = 2;
  43866. ib[2] = 1;
  43867. ib[3] = 0;
  43868. ib[4] = 3;
  43869. ib[5] = 2;
  43870. renderCache.ib = engine.createIndexBuffer(ib);
  43871. // 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
  43872. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  43873. if (ei) {
  43874. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43875. }
  43876. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  43877. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43878. return renderCache;
  43879. };
  43880. Text2D.prototype.createInstanceDataParts = function () {
  43881. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  43882. };
  43883. // Looks like a hack!? Yes! Because that's what it is!
  43884. // 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
  43885. // 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)
  43886. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43887. if (!this._charCount) {
  43888. var curText = this._text;
  43889. this.text = "A";
  43890. return curText;
  43891. }
  43892. };
  43893. // if obj contains something, we restore the _text property
  43894. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43895. if (obj !== undefined) {
  43896. this.text = obj;
  43897. }
  43898. };
  43899. Text2D.prototype.refreshInstanceDataPart = function (part) {
  43900. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43901. return false;
  43902. }
  43903. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  43904. var d = part;
  43905. var texture = this.fontTexture;
  43906. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  43907. var ts = texture.getSize();
  43908. var offset = BABYLON.Vector2.Zero();
  43909. var lh = this.fontTexture.lineHeight;
  43910. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  43911. var charxpos = 0;
  43912. d.dataElementCount = this._charCount;
  43913. d.curElement = 0;
  43914. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  43915. var char = _a[_i];
  43916. // Line feed
  43917. if (char === "\n") {
  43918. offset.x = 0;
  43919. offset.y -= texture.lineHeight;
  43920. }
  43921. // Tabulation ?
  43922. if (char === "\t") {
  43923. var nextPos = charxpos + this._tabulationSize;
  43924. nextPos = nextPos - (nextPos % this._tabulationSize);
  43925. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  43926. charxpos = nextPos;
  43927. continue;
  43928. }
  43929. if (char < " ") {
  43930. continue;
  43931. }
  43932. this.updateInstanceDataPart(d, offset);
  43933. var ci = texture.getChar(char);
  43934. offset.x += ci.charWidth;
  43935. d.topLeftUV = ci.topLeftUV;
  43936. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  43937. d.sizeUV = suv;
  43938. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43939. d.color = this.defaultFontColor;
  43940. d.superSampleFactor = superSampleFactor;
  43941. ++d.curElement;
  43942. }
  43943. }
  43944. return true;
  43945. };
  43946. Text2D.prototype._updateCharCount = function () {
  43947. var count = 0;
  43948. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  43949. var char = _a[_i];
  43950. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  43951. continue;
  43952. }
  43953. ++count;
  43954. }
  43955. this._charCount = count;
  43956. };
  43957. Text2D.TEXT2D_MAINPARTID = 1;
  43958. __decorate([
  43959. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  43960. ], Text2D.prototype, "fontName", null);
  43961. __decorate([
  43962. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  43963. ], Text2D.prototype, "defaultFontColor", null);
  43964. __decorate([
  43965. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  43966. ], Text2D.prototype, "text", null);
  43967. __decorate([
  43968. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  43969. ], Text2D.prototype, "size", null);
  43970. Text2D = __decorate([
  43971. BABYLON.className("Text2D")
  43972. ], Text2D);
  43973. return Text2D;
  43974. })(BABYLON.RenderablePrim2D);
  43975. BABYLON.Text2D = Text2D;
  43976. })(BABYLON || (BABYLON = {}));
  43977. var BABYLON;
  43978. (function (BABYLON) {
  43979. var Lines2DRenderCache = (function (_super) {
  43980. __extends(Lines2DRenderCache, _super);
  43981. function Lines2DRenderCache(engine, modelKey) {
  43982. _super.call(this, engine, modelKey);
  43983. this.effectsReady = false;
  43984. this.fillVB = null;
  43985. this.fillIB = null;
  43986. this.fillIndicesCount = 0;
  43987. this.instancingFillAttributes = null;
  43988. this.effectFill = null;
  43989. this.effectFillInstanced = null;
  43990. this.borderVB = null;
  43991. this.borderIB = null;
  43992. this.borderIndicesCount = 0;
  43993. this.instancingBorderAttributes = null;
  43994. this.effectBorder = null;
  43995. this.effectBorderInstanced = null;
  43996. }
  43997. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  43998. // Do nothing if the shader is still loading/preparing
  43999. if (!this.effectsReady) {
  44000. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44001. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44002. return false;
  44003. }
  44004. this.effectsReady = true;
  44005. }
  44006. var canvas = instanceInfo.owner.owner;
  44007. var engine = canvas.engine;
  44008. var depthFunction = 0;
  44009. if (this.effectFill && this.effectBorder) {
  44010. depthFunction = engine.getDepthFunction();
  44011. engine.setDepthFunctionToLessOrEqual();
  44012. }
  44013. var curAlphaMode = engine.getAlphaMode();
  44014. if (this.effectFill) {
  44015. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44016. var pid = context.groupInfoPartData[partIndex];
  44017. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44018. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44019. }
  44020. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44021. engine.enableEffect(effect);
  44022. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  44023. if (context.useInstancing) {
  44024. if (!this.instancingFillAttributes) {
  44025. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44026. }
  44027. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44028. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44029. canvas._addDrawCallCount(1, context.renderMode);
  44030. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44031. engine.draw(true, 0, this.fillIndicesCount, count);
  44032. engine.unbindInstanceAttributes();
  44033. }
  44034. else {
  44035. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44036. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44037. this.setupUniforms(effect, partIndex, pid._partData, i);
  44038. engine.draw(true, 0, this.fillIndicesCount);
  44039. }
  44040. }
  44041. }
  44042. if (this.effectBorder) {
  44043. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44044. var pid = context.groupInfoPartData[partIndex];
  44045. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44046. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44047. }
  44048. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44049. engine.enableEffect(effect);
  44050. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  44051. if (context.useInstancing) {
  44052. if (!this.instancingBorderAttributes) {
  44053. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44054. }
  44055. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44056. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44057. canvas._addDrawCallCount(1, context.renderMode);
  44058. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44059. engine.draw(true, 0, this.borderIndicesCount, count);
  44060. engine.unbindInstanceAttributes();
  44061. }
  44062. else {
  44063. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44064. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44065. this.setupUniforms(effect, partIndex, pid._partData, i);
  44066. engine.draw(true, 0, this.borderIndicesCount);
  44067. }
  44068. }
  44069. }
  44070. engine.setAlphaMode(curAlphaMode);
  44071. if (this.effectFill && this.effectBorder) {
  44072. engine.setDepthFunction(depthFunction);
  44073. }
  44074. return true;
  44075. };
  44076. Lines2DRenderCache.prototype.dispose = function () {
  44077. if (!_super.prototype.dispose.call(this)) {
  44078. return false;
  44079. }
  44080. if (this.fillVB) {
  44081. this._engine._releaseBuffer(this.fillVB);
  44082. this.fillVB = null;
  44083. }
  44084. if (this.fillIB) {
  44085. this._engine._releaseBuffer(this.fillIB);
  44086. this.fillIB = null;
  44087. }
  44088. if (this.effectFill) {
  44089. this._engine._releaseEffect(this.effectFill);
  44090. this.effectFill = null;
  44091. }
  44092. if (this.effectFillInstanced) {
  44093. this._engine._releaseEffect(this.effectFillInstanced);
  44094. this.effectFillInstanced = null;
  44095. }
  44096. if (this.borderVB) {
  44097. this._engine._releaseBuffer(this.borderVB);
  44098. this.borderVB = null;
  44099. }
  44100. if (this.borderIB) {
  44101. this._engine._releaseBuffer(this.borderIB);
  44102. this.borderIB = null;
  44103. }
  44104. if (this.effectBorder) {
  44105. this._engine._releaseEffect(this.effectBorder);
  44106. this.effectBorder = null;
  44107. }
  44108. if (this.effectBorderInstanced) {
  44109. this._engine._releaseEffect(this.effectBorderInstanced);
  44110. this.effectBorderInstanced = null;
  44111. }
  44112. return true;
  44113. };
  44114. return Lines2DRenderCache;
  44115. })(BABYLON.ModelRenderCache);
  44116. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  44117. var Lines2DInstanceData = (function (_super) {
  44118. __extends(Lines2DInstanceData, _super);
  44119. function Lines2DInstanceData(partId) {
  44120. _super.call(this, partId, 1);
  44121. }
  44122. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  44123. get: function () {
  44124. return null;
  44125. },
  44126. enumerable: true,
  44127. configurable: true
  44128. });
  44129. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  44130. get: function () {
  44131. return null;
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. __decorate([
  44137. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44138. ], Lines2DInstanceData.prototype, "boundingMin", null);
  44139. __decorate([
  44140. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44141. ], Lines2DInstanceData.prototype, "boundingMax", null);
  44142. return Lines2DInstanceData;
  44143. })(BABYLON.Shape2DInstanceData);
  44144. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  44145. var Lines2D = (function (_super) {
  44146. __extends(Lines2D, _super);
  44147. /**
  44148. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  44149. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  44150. * @param settings a combination of settings, possible ones are
  44151. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  44152. * - children: an array of direct children
  44153. * - id a text identifier, for information purpose
  44154. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44155. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44156. * - scale: the initial scale of the primitive. default is 1
  44157. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44158. * - origin: define the normalized origin point location, default [0.5;0.5]
  44159. * - 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.
  44160. * - 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.
  44161. * - startCap: 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.
  44162. * - endCap: 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.
  44163. * - 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. can be a string value (see Canvas2D.GetBrushFromString)
  44164. * - 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. can be a string value (see Canvas2D.GetBrushFromString)
  44165. * - borderThickness: the thickness of the drawn border, default is 1.
  44166. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44167. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44168. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44169. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44170. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44171. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44172. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44173. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44174. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44175. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44176. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44177. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44178. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44179. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44180. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44181. */
  44182. function Lines2D(points, settings) {
  44183. if (!settings) {
  44184. settings = {};
  44185. }
  44186. _super.call(this, settings);
  44187. this._fillVB = null;
  44188. this._fillIB = null;
  44189. this._borderVB = null;
  44190. this._borderIB = null;
  44191. this._size = BABYLON.Size.Zero();
  44192. this._boundingMin = null;
  44193. this._boundingMax = null;
  44194. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  44195. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  44196. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  44197. var closed = (settings.closed == null) ? false : settings.closed;
  44198. this.points = points;
  44199. this.fillThickness = fillThickness;
  44200. this.startCap = startCap;
  44201. this.endCap = endCap;
  44202. this.closed = closed;
  44203. }
  44204. Object.defineProperty(Lines2D, "NoCap", {
  44205. /**
  44206. * No Cap to apply on the extremity
  44207. */
  44208. get: function () { return Lines2D._noCap; },
  44209. enumerable: true,
  44210. configurable: true
  44211. });
  44212. Object.defineProperty(Lines2D, "RoundCap", {
  44213. /**
  44214. * A round cap, will use the line thickness as diameter
  44215. */
  44216. get: function () { return Lines2D._roundCap; },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(Lines2D, "TriangleCap", {
  44221. /**
  44222. * Creates a triangle at the extremity.
  44223. */
  44224. get: function () { return Lines2D._triangleCap; },
  44225. enumerable: true,
  44226. configurable: true
  44227. });
  44228. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  44229. /**
  44230. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  44231. */
  44232. get: function () { return Lines2D._squareAnchorCap; },
  44233. enumerable: true,
  44234. configurable: true
  44235. });
  44236. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  44237. /**
  44238. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  44239. */
  44240. get: function () { return Lines2D._roundAnchorCap; },
  44241. enumerable: true,
  44242. configurable: true
  44243. });
  44244. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  44245. /**
  44246. * Creates a diamond anchor at the extremity.
  44247. */
  44248. get: function () { return Lines2D._diamondAnchorCap; },
  44249. enumerable: true,
  44250. configurable: true
  44251. });
  44252. Object.defineProperty(Lines2D, "ArrowCap", {
  44253. /**
  44254. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  44255. */
  44256. get: function () { return Lines2D._arrowCap; },
  44257. enumerable: true,
  44258. configurable: true
  44259. });
  44260. Object.defineProperty(Lines2D.prototype, "points", {
  44261. get: function () {
  44262. return this._points;
  44263. },
  44264. set: function (value) {
  44265. this._points = value;
  44266. this._boundingBoxDirty();
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  44272. get: function () {
  44273. return this._fillThickness;
  44274. },
  44275. set: function (value) {
  44276. this._fillThickness = value;
  44277. },
  44278. enumerable: true,
  44279. configurable: true
  44280. });
  44281. Object.defineProperty(Lines2D.prototype, "closed", {
  44282. get: function () {
  44283. return this._closed;
  44284. },
  44285. set: function (value) {
  44286. this._closed = value;
  44287. },
  44288. enumerable: true,
  44289. configurable: true
  44290. });
  44291. Object.defineProperty(Lines2D.prototype, "startCap", {
  44292. get: function () {
  44293. return this._startCap;
  44294. },
  44295. set: function (value) {
  44296. this._startCap = value;
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. Object.defineProperty(Lines2D.prototype, "endCap", {
  44302. get: function () {
  44303. return this._endCap;
  44304. },
  44305. set: function (value) {
  44306. this._endCap = value;
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  44312. var _this = this;
  44313. if (this._contour == null) {
  44314. this._computeLines2D();
  44315. }
  44316. var pl = this.points.length;
  44317. var l = this.closed ? pl + 1 : pl;
  44318. var p = intersectInfo._localPickPosition;
  44319. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  44320. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  44321. for (var i = 1; i < l; i++) {
  44322. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  44323. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  44324. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  44325. return true;
  44326. }
  44327. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  44328. return true;
  44329. }
  44330. Lines2D._prevA.x = Lines2D._curA.x;
  44331. Lines2D._prevA.y = Lines2D._curA.y;
  44332. Lines2D._prevB.x = Lines2D._curB.x;
  44333. Lines2D._prevB.y = Lines2D._curB.y;
  44334. }
  44335. var capIntersect = function (tri, points) {
  44336. var l = tri.length;
  44337. for (var i = 0; i < l; i += 3) {
  44338. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  44339. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  44340. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  44341. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  44342. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  44343. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  44344. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  44345. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  44346. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  44347. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  44348. return true;
  44349. }
  44350. }
  44351. return false;
  44352. };
  44353. if (this._startCapTriIndices) {
  44354. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  44355. return true;
  44356. }
  44357. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  44358. return true;
  44359. }
  44360. }
  44361. return false;
  44362. };
  44363. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  44364. get: function () {
  44365. if (!this._boundingMin) {
  44366. this._computeLines2D();
  44367. }
  44368. return this._boundingMin;
  44369. },
  44370. enumerable: true,
  44371. configurable: true
  44372. });
  44373. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  44374. get: function () {
  44375. if (!this._boundingMax) {
  44376. this._computeLines2D();
  44377. }
  44378. return this._boundingMax;
  44379. },
  44380. enumerable: true,
  44381. configurable: true
  44382. });
  44383. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  44384. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  44385. // Remove the BORDER category, we don't use it in the VertexShader
  44386. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  44387. if (i !== -1) {
  44388. res.splice(i, 1);
  44389. }
  44390. return res;
  44391. };
  44392. Lines2D.prototype.updateLevelBoundingInfo = function () {
  44393. if (!this._boundingMin) {
  44394. this._computeLines2D();
  44395. }
  44396. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  44397. };
  44398. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  44399. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  44400. return renderCache;
  44401. };
  44402. ///////////////////////////////////////////////////////////////////////////////////
  44403. // Methods for Lines building
  44404. Lines2D.prototype._perp = function (v, res) {
  44405. res.x = v.y;
  44406. res.y = -v.x;
  44407. };
  44408. ;
  44409. Lines2D.prototype._direction = function (a, b, res) {
  44410. a.subtractToRef(b, res);
  44411. res.normalize();
  44412. };
  44413. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  44414. a.addToRef(b, tangent);
  44415. tangent.normalize();
  44416. miter.x = -tangent.y;
  44417. miter.y = tangent.x;
  44418. Lines2D._miterTps.x = -a.y;
  44419. Lines2D._miterTps.y = a.x;
  44420. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  44421. };
  44422. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  44423. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  44424. if (d === 0)
  44425. return false;
  44426. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  44427. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  44428. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  44429. return false;
  44430. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  44431. return false;
  44432. return true;
  44433. };
  44434. Lines2D.prototype._updateMinMax = function (array, offset) {
  44435. if (offset >= array.length) {
  44436. return;
  44437. }
  44438. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  44439. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  44440. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  44441. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  44442. };
  44443. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  44444. var borderMode = borderThickness != null && !isNaN(borderThickness);
  44445. var off = index * (borderMode ? 8 : 4);
  44446. // 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)
  44447. if (off >= array.length) {
  44448. return;
  44449. }
  44450. // Store start/end normal, we need it for the cap construction
  44451. if (index === 0) {
  44452. this._perp(n, Lines2D._startDir);
  44453. }
  44454. else if (index === max - 1) {
  44455. this._perp(n, Lines2D._endDir);
  44456. Lines2D._endDir.x *= -1;
  44457. Lines2D._endDir.y *= -1;
  44458. }
  44459. var swap = false;
  44460. array[off + 0] = p.x + n.x * halfThickness;
  44461. array[off + 1] = p.y + n.y * halfThickness;
  44462. array[off + 2] = p.x + n.x * -halfThickness;
  44463. array[off + 3] = p.y + n.y * -halfThickness;
  44464. this._updateMinMax(array, off);
  44465. this._updateMinMax(array, off + 2);
  44466. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  44467. // 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
  44468. if (detectFlip !== undefined) {
  44469. // Flip if intersect
  44470. var flipOff = detectFlip * (borderMode ? 8 : 4);
  44471. if (this._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])) {
  44472. swap = true;
  44473. var tps = array[off + 0];
  44474. array[off + 0] = array[off + 2];
  44475. array[off + 2] = tps;
  44476. tps = array[off + 1];
  44477. array[off + 1] = array[off + 3];
  44478. array[off + 3] = tps;
  44479. }
  44480. }
  44481. if (borderMode) {
  44482. var t = halfThickness + borderThickness;
  44483. array[off + 4] = p.x + n.x * (swap ? -t : t);
  44484. array[off + 5] = p.y + n.y * (swap ? -t : t);
  44485. array[off + 6] = p.x + n.x * (swap ? t : -t);
  44486. array[off + 7] = p.y + n.y * (swap ? t : -t);
  44487. this._updateMinMax(array, off + 4);
  44488. this._updateMinMax(array, off + 6);
  44489. }
  44490. if (contour) {
  44491. off += borderMode ? 4 : 0;
  44492. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  44493. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  44494. }
  44495. };
  44496. Lines2D.prototype._getCapSize = function (type, border) {
  44497. if (border === void 0) { border = false; }
  44498. var sd = Lines2D._roundCapSubDiv;
  44499. // If no array given, we call this to get the size
  44500. var vbsize = 0, ibsize = 0;
  44501. switch (type) {
  44502. case Lines2D.NoCap:
  44503. {
  44504. // If the line is not close and we're computing border, we add the size to generate the edge border
  44505. if (!this.closed && border) {
  44506. vbsize = 4;
  44507. ibsize = 6;
  44508. }
  44509. else {
  44510. vbsize = ibsize = 0;
  44511. }
  44512. break;
  44513. }
  44514. case Lines2D.RoundCap:
  44515. {
  44516. if (border) {
  44517. vbsize = sd;
  44518. ibsize = (sd - 2) * 3;
  44519. }
  44520. else {
  44521. vbsize = (sd / 2) + 1;
  44522. ibsize = (sd / 2) * 3;
  44523. }
  44524. break;
  44525. }
  44526. case Lines2D.ArrowCap:
  44527. {
  44528. if (border) {
  44529. vbsize = 12;
  44530. ibsize = 24;
  44531. }
  44532. else {
  44533. vbsize = 3;
  44534. ibsize = 3;
  44535. }
  44536. break;
  44537. }
  44538. case Lines2D.TriangleCap:
  44539. {
  44540. if (border) {
  44541. vbsize = 6;
  44542. ibsize = 12;
  44543. }
  44544. else {
  44545. vbsize = 3;
  44546. ibsize = 3;
  44547. }
  44548. break;
  44549. }
  44550. case Lines2D.DiamondAnchorCap:
  44551. {
  44552. if (border) {
  44553. vbsize = 10;
  44554. ibsize = 24;
  44555. }
  44556. else {
  44557. vbsize = 5;
  44558. ibsize = 9;
  44559. }
  44560. break;
  44561. }
  44562. case Lines2D.SquareAnchorCap:
  44563. {
  44564. if (border) {
  44565. vbsize = 12;
  44566. ibsize = 30;
  44567. }
  44568. else {
  44569. vbsize = 4;
  44570. ibsize = 6;
  44571. }
  44572. break;
  44573. }
  44574. case Lines2D.RoundAnchorCap:
  44575. {
  44576. if (border) {
  44577. vbsize = sd * 2;
  44578. ibsize = (sd - 1) * 6;
  44579. }
  44580. else {
  44581. vbsize = sd + 1;
  44582. ibsize = (sd + 1) * 3;
  44583. }
  44584. break;
  44585. }
  44586. }
  44587. return { vbsize: vbsize * 2, ibsize: ibsize };
  44588. };
  44589. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  44590. var c = Math.cos(rotation);
  44591. var s = Math.sin(rotation);
  44592. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  44593. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  44594. var offset = baseOffset + (index * 2);
  44595. vb[offset + 0] = Lines2D._tpsV.x;
  44596. vb[offset + 1] = Lines2D._tpsV.y;
  44597. if (contour) {
  44598. contour.push(Lines2D._tpsV.x);
  44599. contour.push(Lines2D._tpsV.y);
  44600. }
  44601. this._updateMinMax(vb, offset);
  44602. return (baseOffset + index * 2) / 2;
  44603. };
  44604. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  44605. ib[baseOffset + index] = vertexIndex;
  44606. };
  44607. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  44608. // 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
  44609. var sd = Lines2D._roundCapSubDiv;
  44610. var dir = new BABYLON.Vector2(1, 0);
  44611. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  44612. var ht = thickness / 2;
  44613. var t = thickness;
  44614. var borderMode = borderThickness != null;
  44615. var bt = borderThickness;
  44616. switch (type) {
  44617. case Lines2D.NoCap:
  44618. if (borderMode && !this.closed) {
  44619. var vi = 0;
  44620. var ii = 0;
  44621. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  44622. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  44623. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  44624. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  44625. this._storeIndex(ib, ibi, ii++, v1);
  44626. this._storeIndex(ib, ibi, ii++, v2);
  44627. this._storeIndex(ib, ibi, ii++, v3);
  44628. this._storeIndex(ib, ibi, ii++, v1);
  44629. this._storeIndex(ib, ibi, ii++, v3);
  44630. this._storeIndex(ib, ibi, ii++, v4);
  44631. }
  44632. break;
  44633. case Lines2D.ArrowCap:
  44634. ht *= 2;
  44635. case Lines2D.TriangleCap:
  44636. {
  44637. if (borderMode) {
  44638. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  44639. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  44640. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  44641. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  44642. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  44643. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  44644. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  44645. var ii = 0;
  44646. this._storeIndex(ib, ibi, ii++, v1);
  44647. this._storeIndex(ib, ibi, ii++, v4);
  44648. this._storeIndex(ib, ibi, ii++, v5);
  44649. this._storeIndex(ib, ibi, ii++, v1);
  44650. this._storeIndex(ib, ibi, ii++, v5);
  44651. this._storeIndex(ib, ibi, ii++, v2);
  44652. this._storeIndex(ib, ibi, ii++, v6);
  44653. this._storeIndex(ib, ibi, ii++, v3);
  44654. this._storeIndex(ib, ibi, ii++, v2);
  44655. this._storeIndex(ib, ibi, ii++, v6);
  44656. this._storeIndex(ib, ibi, ii++, v2);
  44657. this._storeIndex(ib, ibi, ii++, v5);
  44658. if (type === Lines2D.ArrowCap) {
  44659. var rht = thickness / 2;
  44660. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  44661. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  44662. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  44663. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  44664. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  44665. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  44666. this._storeIndex(ib, ibi, ii++, v7);
  44667. this._storeIndex(ib, ibi, ii++, v8);
  44668. this._storeIndex(ib, ibi, ii++, v9);
  44669. this._storeIndex(ib, ibi, ii++, v7);
  44670. this._storeIndex(ib, ibi, ii++, v9);
  44671. this._storeIndex(ib, ibi, ii++, v4);
  44672. this._storeIndex(ib, ibi, ii++, v10);
  44673. this._storeIndex(ib, ibi, ii++, v12);
  44674. this._storeIndex(ib, ibi, ii++, v11);
  44675. this._storeIndex(ib, ibi, ii++, v10);
  44676. this._storeIndex(ib, ibi, ii++, v6);
  44677. this._storeIndex(ib, ibi, ii++, v12);
  44678. }
  44679. }
  44680. else {
  44681. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  44682. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  44683. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  44684. this._storeIndex(ib, ibi, 0, v1);
  44685. this._storeIndex(ib, ibi, 1, v2);
  44686. this._storeIndex(ib, ibi, 2, v3);
  44687. }
  44688. break;
  44689. }
  44690. case Lines2D.RoundCap:
  44691. {
  44692. if (borderMode) {
  44693. var curA = -Math.PI / 2;
  44694. var incA = Math.PI / (sd / 2 - 1);
  44695. var ii = 0;
  44696. for (var i = 0; i < (sd / 2); i++) {
  44697. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44698. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  44699. if (i > 0) {
  44700. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44701. this._storeIndex(ib, ibi, ii++, v2 - 2);
  44702. this._storeIndex(ib, ibi, ii++, v2);
  44703. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44704. this._storeIndex(ib, ibi, ii++, v2);
  44705. this._storeIndex(ib, ibi, ii++, v1);
  44706. }
  44707. curA += incA;
  44708. }
  44709. }
  44710. else {
  44711. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  44712. var curA = -Math.PI / 2;
  44713. var incA = Math.PI / (sd / 2 - 1);
  44714. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  44715. curA += incA;
  44716. for (var i = 1; i < (sd / 2); i++) {
  44717. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  44718. this._storeIndex(ib, ibi, i * 3 + 0, c);
  44719. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  44720. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  44721. curA += incA;
  44722. }
  44723. }
  44724. break;
  44725. }
  44726. case Lines2D.SquareAnchorCap:
  44727. {
  44728. var vi = 0;
  44729. var c = borderMode ? null : contour;
  44730. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  44731. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  44732. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  44733. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  44734. if (borderMode) {
  44735. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  44736. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  44737. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  44738. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  44739. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  44740. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  44741. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  44742. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  44743. var ii = 0;
  44744. this._storeIndex(ib, ibi, ii++, v6);
  44745. this._storeIndex(ib, ibi, ii++, v1);
  44746. this._storeIndex(ib, ibi, ii++, v5);
  44747. this._storeIndex(ib, ibi, ii++, v6);
  44748. this._storeIndex(ib, ibi, ii++, v7);
  44749. this._storeIndex(ib, ibi, ii++, v1);
  44750. this._storeIndex(ib, ibi, ii++, v1);
  44751. this._storeIndex(ib, ibi, ii++, v7);
  44752. this._storeIndex(ib, ibi, ii++, v8);
  44753. this._storeIndex(ib, ibi, ii++, v1);
  44754. this._storeIndex(ib, ibi, ii++, v8);
  44755. this._storeIndex(ib, ibi, ii++, v2);
  44756. this._storeIndex(ib, ibi, ii++, v2);
  44757. this._storeIndex(ib, ibi, ii++, v8);
  44758. this._storeIndex(ib, ibi, ii++, v9);
  44759. this._storeIndex(ib, ibi, ii++, v2);
  44760. this._storeIndex(ib, ibi, ii++, v9);
  44761. this._storeIndex(ib, ibi, ii++, v3);
  44762. this._storeIndex(ib, ibi, ii++, v3);
  44763. this._storeIndex(ib, ibi, ii++, v9);
  44764. this._storeIndex(ib, ibi, ii++, v10);
  44765. this._storeIndex(ib, ibi, ii++, v3);
  44766. this._storeIndex(ib, ibi, ii++, v10);
  44767. this._storeIndex(ib, ibi, ii++, v4);
  44768. this._storeIndex(ib, ibi, ii++, v10);
  44769. this._storeIndex(ib, ibi, ii++, v11);
  44770. this._storeIndex(ib, ibi, ii++, v4);
  44771. this._storeIndex(ib, ibi, ii++, v11);
  44772. this._storeIndex(ib, ibi, ii++, v12);
  44773. this._storeIndex(ib, ibi, ii++, v4);
  44774. }
  44775. else {
  44776. this._storeIndex(ib, ibi, 0, v1);
  44777. this._storeIndex(ib, ibi, 1, v2);
  44778. this._storeIndex(ib, ibi, 2, v3);
  44779. this._storeIndex(ib, ibi, 3, v1);
  44780. this._storeIndex(ib, ibi, 4, v3);
  44781. this._storeIndex(ib, ibi, 5, v4);
  44782. }
  44783. break;
  44784. }
  44785. case Lines2D.RoundAnchorCap:
  44786. {
  44787. var cpos = Math.sqrt(t * t - ht * ht);
  44788. var center = new BABYLON.Vector2(cpos, 0);
  44789. var curA = BABYLON.Tools.ToRadians(-150);
  44790. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  44791. if (borderMode) {
  44792. var ii = 0;
  44793. for (var i = 0; i < sd; i++) {
  44794. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  44795. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  44796. if (i > 0) {
  44797. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44798. this._storeIndex(ib, ibi, ii++, v2 - 2);
  44799. this._storeIndex(ib, ibi, ii++, v2);
  44800. this._storeIndex(ib, ibi, ii++, v1 - 2);
  44801. this._storeIndex(ib, ibi, ii++, v2);
  44802. this._storeIndex(ib, ibi, ii++, v1);
  44803. }
  44804. curA += incA;
  44805. }
  44806. }
  44807. else {
  44808. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  44809. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  44810. curA += incA;
  44811. for (var i = 1; i < sd; i++) {
  44812. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  44813. this._storeIndex(ib, ibi, i * 3 + 0, c);
  44814. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  44815. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  44816. curA += incA;
  44817. }
  44818. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  44819. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  44820. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  44821. }
  44822. break;
  44823. }
  44824. case Lines2D.DiamondAnchorCap:
  44825. {
  44826. var vi = 0;
  44827. var c = borderMode ? null : contour;
  44828. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  44829. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  44830. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  44831. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  44832. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  44833. if (borderMode) {
  44834. var f = Math.sqrt(bt * bt * 2);
  44835. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  44836. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  44837. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  44838. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  44839. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  44840. var ii = 0;
  44841. this._storeIndex(ib, ibi, ii++, v6);
  44842. this._storeIndex(ib, ibi, ii++, v7);
  44843. this._storeIndex(ib, ibi, ii++, v1);
  44844. this._storeIndex(ib, ibi, ii++, v1);
  44845. this._storeIndex(ib, ibi, ii++, v7);
  44846. this._storeIndex(ib, ibi, ii++, v2);
  44847. this._storeIndex(ib, ibi, ii++, v2);
  44848. this._storeIndex(ib, ibi, ii++, v7);
  44849. this._storeIndex(ib, ibi, ii++, v8);
  44850. this._storeIndex(ib, ibi, ii++, v2);
  44851. this._storeIndex(ib, ibi, ii++, v8);
  44852. this._storeIndex(ib, ibi, ii++, v3);
  44853. this._storeIndex(ib, ibi, ii++, v3);
  44854. this._storeIndex(ib, ibi, ii++, v8);
  44855. this._storeIndex(ib, ibi, ii++, v9);
  44856. this._storeIndex(ib, ibi, ii++, v3);
  44857. this._storeIndex(ib, ibi, ii++, v9);
  44858. this._storeIndex(ib, ibi, ii++, v4);
  44859. this._storeIndex(ib, ibi, ii++, v4);
  44860. this._storeIndex(ib, ibi, ii++, v9);
  44861. this._storeIndex(ib, ibi, ii++, v10);
  44862. this._storeIndex(ib, ibi, ii++, v4);
  44863. this._storeIndex(ib, ibi, ii++, v10);
  44864. this._storeIndex(ib, ibi, ii++, v5);
  44865. }
  44866. else {
  44867. this._storeIndex(ib, ibi, 0, v1);
  44868. this._storeIndex(ib, ibi, 1, v2);
  44869. this._storeIndex(ib, ibi, 2, v3);
  44870. this._storeIndex(ib, ibi, 3, v1);
  44871. this._storeIndex(ib, ibi, 4, v3);
  44872. this._storeIndex(ib, ibi, 5, v5);
  44873. this._storeIndex(ib, ibi, 6, v5);
  44874. this._storeIndex(ib, ibi, 7, v3);
  44875. this._storeIndex(ib, ibi, 8, v4);
  44876. }
  44877. break;
  44878. }
  44879. }
  44880. return null;
  44881. };
  44882. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  44883. var lineA = BABYLON.Vector2.Zero();
  44884. var lineB = BABYLON.Vector2.Zero();
  44885. var tangent = BABYLON.Vector2.Zero();
  44886. var miter = BABYLON.Vector2.Zero();
  44887. var curNormal = null;
  44888. if (this.closed) {
  44889. this.points.push(this.points[0]);
  44890. }
  44891. var total = this.points.length;
  44892. for (var i = 1; i < total; i++) {
  44893. var last = this.points[i - 1];
  44894. var cur = this.points[i];
  44895. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  44896. this._direction(cur, last, lineA);
  44897. if (!curNormal) {
  44898. curNormal = BABYLON.Vector2.Zero();
  44899. this._perp(lineA, curNormal);
  44900. }
  44901. if (i === 1) {
  44902. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  44903. }
  44904. if (!next) {
  44905. this._perp(lineA, curNormal);
  44906. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  44907. }
  44908. else {
  44909. this._direction(next, cur, lineB);
  44910. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  44911. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  44912. }
  44913. }
  44914. if (this.points.length > 2 && this.closed) {
  44915. var last2 = this.points[total - 2];
  44916. var cur2 = this.points[0];
  44917. var next2 = this.points[1];
  44918. this._direction(cur2, last2, lineA);
  44919. this._direction(next2, cur2, lineB);
  44920. this._perp(lineA, curNormal);
  44921. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  44922. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  44923. // Patch contour
  44924. if (contour) {
  44925. var off = (bt == null) ? 0 : 4;
  44926. contour[0].x = vb[off + 0];
  44927. contour[0].y = vb[off + 1];
  44928. contour[1].x = vb[off + 2];
  44929. contour[1].y = vb[off + 3];
  44930. }
  44931. }
  44932. // Remove the point we added at the beginning
  44933. if (this.closed) {
  44934. this.points.splice(total - 1);
  44935. }
  44936. };
  44937. // Methods for Lines building
  44938. ///////////////////////////////////////////////////////////////////////////////////
  44939. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44940. var renderCache = modelRenderCache;
  44941. var engine = this.owner.engine;
  44942. if (this._fillVB === null) {
  44943. this._computeLines2D();
  44944. }
  44945. // Need to create WebGL resources for fill part?
  44946. if (this.fill) {
  44947. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  44948. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  44949. renderCache.fillIndicesCount = this._fillIB.length;
  44950. // 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
  44951. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  44952. if (ei) {
  44953. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44954. }
  44955. // Get the non instanced version
  44956. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  44957. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44958. }
  44959. // Need to create WebGL resources for border part?
  44960. if (this.border) {
  44961. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  44962. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  44963. renderCache.borderIndicesCount = this._borderIB.length;
  44964. // 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
  44965. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  44966. if (ei) {
  44967. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44968. }
  44969. // Get the non instanced version
  44970. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  44971. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44972. }
  44973. this._fillVB = null;
  44974. this._fillIB = null;
  44975. this._borderVB = null;
  44976. this._borderIB = null;
  44977. return renderCache;
  44978. };
  44979. Lines2D.prototype._computeLines2D = function () {
  44980. // Init min/max because their being computed here
  44981. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  44982. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  44983. var contour = new Array();
  44984. var startCapContour = new Array();
  44985. var endCapContour = new Array();
  44986. // Need to create WebGL resources for fill part?
  44987. if (this.fill) {
  44988. var startCapInfo = this._getCapSize(this.startCap);
  44989. var endCapInfo = this._getCapSize(this.endCap);
  44990. var count = this.points.length;
  44991. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  44992. this._fillVB = new Float32Array(vbSize);
  44993. var vb = this._fillVB;
  44994. var ht = this.fillThickness / 2;
  44995. var total = this.points.length;
  44996. this._buildLine(vb, this.border ? null : contour, ht);
  44997. var max = total * 2;
  44998. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  44999. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45000. var ib = this._fillIB;
  45001. for (var i = 0; i < triCount; i += 2) {
  45002. ib[i * 3 + 0] = i + 0;
  45003. ib[i * 3 + 1] = i + 1;
  45004. ib[i * 3 + 2] = (i + 2) % max;
  45005. ib[i * 3 + 3] = i + 1;
  45006. ib[i * 3 + 4] = (i + 3) % max;
  45007. ib[i * 3 + 5] = (i + 2) % max;
  45008. }
  45009. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  45010. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D._endDir, this.border ? null : startCapContour);
  45011. }
  45012. // Need to create WebGL resources for border part?
  45013. if (this.border) {
  45014. var startCapInfo = this._getCapSize(this.startCap, true);
  45015. var endCapInfo = this._getCapSize(this.endCap, true);
  45016. var count = this.points.length;
  45017. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45018. this._borderVB = new Float32Array(vbSize);
  45019. var vb = this._borderVB;
  45020. var ht = this.fillThickness / 2;
  45021. var bt = this.borderThickness;
  45022. var total = this.points.length;
  45023. this._buildLine(vb, contour, ht, bt);
  45024. var max = total * 2 * 2;
  45025. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  45026. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45027. var ib = this._borderIB;
  45028. for (var i = 0; i < triCount; i += 4) {
  45029. ib[i * 3 + 0] = i + 0;
  45030. ib[i * 3 + 1] = i + 2;
  45031. ib[i * 3 + 2] = (i + 6) % max;
  45032. ib[i * 3 + 3] = i + 0;
  45033. ib[i * 3 + 4] = (i + 6) % max;
  45034. ib[i * 3 + 5] = (i + 4) % max;
  45035. ib[i * 3 + 6] = i + 3;
  45036. ib[i * 3 + 7] = i + 1;
  45037. ib[i * 3 + 8] = (i + 5) % max;
  45038. ib[i * 3 + 9] = i + 3;
  45039. ib[i * 3 + 10] = (i + 5) % max;
  45040. ib[i * 3 + 11] = (i + 7) % max;
  45041. }
  45042. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  45043. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D._endDir, endCapContour);
  45044. }
  45045. this._contour = contour;
  45046. if (startCapContour.length > 0) {
  45047. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  45048. this._startCapTriIndices = startCapTri;
  45049. this._startCapContour = startCapContour;
  45050. }
  45051. if (endCapContour.length > 0) {
  45052. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  45053. this._endCapContour = endCapContour;
  45054. this._endCapTriIndices = endCapTri;
  45055. }
  45056. var bs = this._boundingMax.subtract(this._boundingMin);
  45057. this._size.width = bs.x;
  45058. this._size.height = bs.y;
  45059. };
  45060. Object.defineProperty(Lines2D.prototype, "size", {
  45061. get: function () {
  45062. if (this._size == null) {
  45063. this._computeLines2D();
  45064. }
  45065. return this._size;
  45066. },
  45067. enumerable: true,
  45068. configurable: true
  45069. });
  45070. Lines2D.prototype.createInstanceDataParts = function () {
  45071. var res = new Array();
  45072. if (this.border) {
  45073. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45074. }
  45075. if (this.fill) {
  45076. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45077. }
  45078. return res;
  45079. };
  45080. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  45081. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45082. return false;
  45083. }
  45084. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45085. var d = part;
  45086. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  45087. d.boundingMin = this.boundingMin;
  45088. d.boundingMax = this.boundingMax;
  45089. }
  45090. }
  45091. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45092. var d = part;
  45093. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  45094. d.boundingMin = this.boundingMin;
  45095. d.boundingMax = this.boundingMax;
  45096. }
  45097. }
  45098. return true;
  45099. };
  45100. Lines2D._prevA = BABYLON.Vector2.Zero();
  45101. Lines2D._prevB = BABYLON.Vector2.Zero();
  45102. Lines2D._curA = BABYLON.Vector2.Zero();
  45103. Lines2D._curB = BABYLON.Vector2.Zero();
  45104. Lines2D._miterTps = BABYLON.Vector2.Zero();
  45105. Lines2D._startDir = BABYLON.Vector2.Zero();
  45106. Lines2D._endDir = BABYLON.Vector2.Zero();
  45107. Lines2D._tpsV = BABYLON.Vector2.Zero();
  45108. Lines2D._noCap = 0;
  45109. Lines2D._roundCap = 1;
  45110. Lines2D._triangleCap = 2;
  45111. Lines2D._squareAnchorCap = 3;
  45112. Lines2D._roundAnchorCap = 4;
  45113. Lines2D._diamondAnchorCap = 5;
  45114. Lines2D._arrowCap = 6;
  45115. Lines2D._roundCapSubDiv = 36;
  45116. __decorate([
  45117. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  45118. ], Lines2D.prototype, "points", null);
  45119. __decorate([
  45120. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  45121. ], Lines2D.prototype, "fillThickness", null);
  45122. __decorate([
  45123. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  45124. ], Lines2D.prototype, "closed", null);
  45125. __decorate([
  45126. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  45127. ], Lines2D.prototype, "startCap", null);
  45128. __decorate([
  45129. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  45130. ], Lines2D.prototype, "endCap", null);
  45131. Lines2D = __decorate([
  45132. BABYLON.className("Lines2D")
  45133. ], Lines2D);
  45134. return Lines2D;
  45135. })(BABYLON.Shape2D);
  45136. BABYLON.Lines2D = Lines2D;
  45137. })(BABYLON || (BABYLON = {}));
  45138. var BABYLON;
  45139. (function (BABYLON) {
  45140. // This class contains data that lifetime is bounding to the Babylon Engine object
  45141. var Canvas2DEngineBoundData = (function () {
  45142. function Canvas2DEngineBoundData() {
  45143. this._modelCache = new BABYLON.StringDictionary();
  45144. }
  45145. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  45146. return this._modelCache.getOrAddWithFactory(key, factory);
  45147. };
  45148. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  45149. if (!modelRenderCache.isDisposed) {
  45150. return false;
  45151. }
  45152. this._modelCache.remove(modelRenderCache.modelKey);
  45153. return true;
  45154. };
  45155. return Canvas2DEngineBoundData;
  45156. })();
  45157. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  45158. var Canvas2D = (function (_super) {
  45159. __extends(Canvas2D, _super);
  45160. function Canvas2D(scene, settings) {
  45161. var _this = this;
  45162. _super.call(this, settings);
  45163. /**
  45164. * 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.
  45165. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  45166. */
  45167. this.worldSpaceToNodeLocal = function (worldPos) {
  45168. var node = _this._worldSpaceNode;
  45169. if (!node) {
  45170. return;
  45171. }
  45172. var mtx = node.getWorldMatrix().clone();
  45173. mtx.invert();
  45174. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  45175. var res = new BABYLON.Vector2(v.x, v.y);
  45176. var size = _this.actualSize;
  45177. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  45178. res.y += size.height * 0.5;
  45179. return res;
  45180. };
  45181. /**
  45182. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  45183. */
  45184. this.worldSpaceCacheChanged = function () {
  45185. var plane = _this.worldSpaceCanvasNode;
  45186. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  45187. vd.uvs = new Float32Array(8);
  45188. var material = plane.material;
  45189. var tex = _this._renderableData._cacheTexture;
  45190. if (material.diffuseTexture !== tex) {
  45191. material.diffuseTexture = tex;
  45192. tex.hasAlpha = true;
  45193. }
  45194. var nodeuv = _this._renderableData._cacheNodeUVs;
  45195. for (var i = 0; i < 4; i++) {
  45196. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  45197. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  45198. }
  45199. vd.applyToMesh(plane);
  45200. };
  45201. this._notifDebugMode = false;
  45202. this._mapCounter = 0;
  45203. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  45204. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  45205. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  45206. this._groupRenderCounter = new BABYLON.PerfCounter();
  45207. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  45208. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  45209. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  45210. this._updateLayoutCounter = new BABYLON.PerfCounter();
  45211. this._updatePositioningCounter = new BABYLON.PerfCounter();
  45212. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  45213. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  45214. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  45215. this._profileInfoText = null;
  45216. BABYLON.Prim2DBase._isCanvasInit = false;
  45217. if (!settings) {
  45218. settings = {};
  45219. }
  45220. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  45221. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  45222. this._background.zOrder = 1.0;
  45223. this._background.isPickable = false;
  45224. this._background.origin = BABYLON.Vector2.Zero();
  45225. this._background.levelVisible = false;
  45226. if (settings.backgroundRoundRadius != null) {
  45227. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  45228. }
  45229. if (settings.backgroundBorder != null) {
  45230. if (typeof (settings.backgroundBorder) === "string") {
  45231. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  45232. }
  45233. else {
  45234. this.backgroundBorder = settings.backgroundBorder;
  45235. }
  45236. }
  45237. if (settings.backgroundBorderThickNess != null) {
  45238. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  45239. }
  45240. if (settings.backgroundFill != null) {
  45241. if (typeof (settings.backgroundFill) === "string") {
  45242. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  45243. }
  45244. else {
  45245. this.backgroundFill = settings.backgroundFill;
  45246. }
  45247. }
  45248. this._background._patchHierarchy(this);
  45249. }
  45250. var engine = scene.getEngine();
  45251. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  45252. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  45253. this._capturedPointers = new BABYLON.StringDictionary();
  45254. this._pickStartingPosition = BABYLON.Vector2.Zero();
  45255. this._hierarchyLevelMaxSiblingCount = 50;
  45256. this._hierarchyDepth = 0;
  45257. this._zOrder = 0;
  45258. this._zMax = 1;
  45259. this._scene = scene;
  45260. this._engine = engine;
  45261. this._renderingSize = new BABYLON.Size(0, 0);
  45262. this._trackedGroups = new Array();
  45263. this._maxAdaptiveWorldSpaceCanvasSize = null;
  45264. this._groupCacheMaps = new BABYLON.StringDictionary();
  45265. this._patchHierarchy(this);
  45266. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  45267. this._fitRenderingDevice = !settings.size;
  45268. if (!settings.size) {
  45269. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  45270. }
  45271. // Register scene dispose to also dispose the canvas when it'll happens
  45272. scene.onDisposeObservable.add(function (d, s) {
  45273. _this.dispose();
  45274. });
  45275. if (this._isScreenSpace) {
  45276. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  45277. _this._engine.clear(null, false, true);
  45278. _this._render();
  45279. });
  45280. }
  45281. else {
  45282. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  45283. _this._render();
  45284. });
  45285. }
  45286. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  45287. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  45288. this._setupInteraction(enableInteraction);
  45289. }
  45290. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  45291. get: function () {
  45292. return this._drawCallsOpaqueCounter;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  45298. get: function () {
  45299. return this._drawCallsAlphaTestCounter;
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  45305. get: function () {
  45306. return this._drawCallsTransparentCounter;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  45312. get: function () {
  45313. return this._groupRenderCounter;
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  45319. get: function () {
  45320. return this._updateTransparentDataCounter;
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  45326. get: function () {
  45327. return this._cachedGroupRenderCounter;
  45328. },
  45329. enumerable: true,
  45330. configurable: true
  45331. });
  45332. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  45333. get: function () {
  45334. return this._updateCachedStateCounter;
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  45340. get: function () {
  45341. return this._updateLayoutCounter;
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  45347. get: function () {
  45348. return this._updatePositioningCounter;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  45354. get: function () {
  45355. return this._updateLocalTransformCounter;
  45356. },
  45357. enumerable: true,
  45358. configurable: true
  45359. });
  45360. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  45361. get: function () {
  45362. return this._updateGlobalTransformCounter;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  45368. get: function () {
  45369. return this._boundingInfoRecomputeCounter;
  45370. },
  45371. enumerable: true,
  45372. configurable: true
  45373. });
  45374. Canvas2D.prototype._canvasPreInit = function (settings) {
  45375. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  45376. this._cachingStrategy = cachingStrategy;
  45377. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  45378. };
  45379. Canvas2D.prototype._setupInteraction = function (enable) {
  45380. var _this = this;
  45381. // No change detection
  45382. if (enable === this._interactionEnabled) {
  45383. return;
  45384. }
  45385. // Set the new state
  45386. this._interactionEnabled = enable;
  45387. // ScreenSpace mode
  45388. if (this._isScreenSpace) {
  45389. // Disable interaction
  45390. if (!enable) {
  45391. if (this._scenePrePointerObserver) {
  45392. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  45393. this._scenePrePointerObserver = null;
  45394. }
  45395. return;
  45396. }
  45397. // Enable Interaction
  45398. // Register the observable
  45399. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  45400. var hs = 1 / _this.engine.getHardwareScalingLevel();
  45401. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  45402. _this._handlePointerEventForInteraction(e, localPos, s);
  45403. });
  45404. }
  45405. else {
  45406. var scene = this.scene;
  45407. if (enable) {
  45408. scene.constantlyUpdateMeshUnderPointer = true;
  45409. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  45410. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  45411. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  45412. _this._handlePointerEventForInteraction(e, localPos, s);
  45413. }
  45414. });
  45415. }
  45416. else {
  45417. if (this._scenePointerObserver) {
  45418. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  45419. this._scenePointerObserver = null;
  45420. }
  45421. }
  45422. }
  45423. };
  45424. /**
  45425. * Internal method, you should use the Prim2DBase version instead
  45426. */
  45427. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  45428. if (this.isPointerCaptured(pointerId)) {
  45429. return false;
  45430. }
  45431. // Try to capture the pointer on the HTML side
  45432. try {
  45433. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  45434. }
  45435. catch (e) {
  45436. }
  45437. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45438. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  45439. this._capturedPointers.add(pointerId.toString(), primitive);
  45440. return true;
  45441. };
  45442. /**
  45443. * Internal method, you should use the Prim2DBase version instead
  45444. */
  45445. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  45446. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  45447. return false;
  45448. }
  45449. // Try to release the pointer on the HTML side
  45450. try {
  45451. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  45452. }
  45453. catch (e) {
  45454. }
  45455. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45456. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  45457. this._capturedPointers.remove(pointerId.toString());
  45458. return true;
  45459. };
  45460. /**
  45461. * Determine if the given pointer is captured or not
  45462. * @param pointerId the Id of the pointer
  45463. * @return true if it's captured, false otherwise
  45464. */
  45465. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  45466. return this._capturedPointers.contains(pointerId.toString());
  45467. };
  45468. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  45469. // Avoid unnecessary lookup
  45470. if (this._capturedPointers.count === 0) {
  45471. return null;
  45472. }
  45473. return this._capturedPointers.get(pointerId.toString());
  45474. };
  45475. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  45476. // Dispose check
  45477. if (this.isDisposed) {
  45478. return;
  45479. }
  45480. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  45481. this._updatePointerInfo(eventData, localPosition);
  45482. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45483. // 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.
  45484. // 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.
  45485. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  45486. // 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
  45487. this._updateOverStatus();
  45488. // Check if we have nothing to raise
  45489. if (!this._actualOverPrimitive && !capturedPrim) {
  45490. return;
  45491. }
  45492. // Update the relatedTarget info with the over primitive or the captured one (if any)
  45493. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  45494. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  45495. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  45496. // Analyze the pointer event type and fire proper events on the primitive
  45497. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45498. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  45499. }
  45500. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45501. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  45502. }
  45503. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  45504. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  45505. }
  45506. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  45507. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  45508. }
  45509. };
  45510. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  45511. var pii = this._primPointerInfo;
  45512. if (!pii.canvasPointerPos) {
  45513. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  45514. }
  45515. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  45516. var engine = this._scene.getEngine();
  45517. if (this._isScreenSpace) {
  45518. var cameraViewport = camera.viewport;
  45519. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45520. // Moving coordinates to local viewport world
  45521. var x = localPosition.x - viewport.x;
  45522. var y = localPosition.y - viewport.y;
  45523. pii.canvasPointerPos.x = x - this.actualPosition.x;
  45524. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  45525. }
  45526. else {
  45527. pii.canvasPointerPos.x = localPosition.x;
  45528. pii.canvasPointerPos.y = localPosition.y;
  45529. }
  45530. pii.mouseWheelDelta = 0;
  45531. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45532. var event = eventData.event;
  45533. if (event.wheelDelta) {
  45534. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  45535. }
  45536. else if (event.detail) {
  45537. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  45538. }
  45539. }
  45540. else {
  45541. var pe = eventData.event;
  45542. pii.ctrlKey = pe.ctrlKey;
  45543. pii.altKey = pe.altKey;
  45544. pii.shiftKey = pe.shiftKey;
  45545. pii.metaKey = pe.metaKey;
  45546. pii.button = pe.button;
  45547. pii.buttons = pe.buttons;
  45548. pii.pointerId = pe.pointerId;
  45549. pii.width = pe.width;
  45550. pii.height = pe.height;
  45551. pii.presssure = pe.pressure;
  45552. pii.tilt.x = pe.tiltX;
  45553. pii.tilt.y = pe.tiltY;
  45554. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  45555. }
  45556. };
  45557. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  45558. if (this.scene.getRenderId() === this._intersectionRenderId) {
  45559. return;
  45560. }
  45561. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  45562. if (!this._globalTransform) {
  45563. this.updateCachedStates(true);
  45564. }
  45565. var ii = Canvas2D._interInfo;
  45566. ii.pickPosition.x = mouseLocalPos.x;
  45567. ii.pickPosition.y = mouseLocalPos.y;
  45568. ii.findFirstOnly = false;
  45569. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  45570. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  45571. this._previousIntersectionList = this._actualIntersectionList;
  45572. this._actualIntersectionList = null;
  45573. this._previousOverPrimitive = this._actualOverPrimitive;
  45574. this._actualOverPrimitive = null;
  45575. return;
  45576. }
  45577. this.intersect(ii);
  45578. this._previousIntersectionList = this._actualIntersectionList;
  45579. this._actualIntersectionList = ii.intersectedPrimitives;
  45580. this._previousOverPrimitive = this._actualOverPrimitive;
  45581. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  45582. this._intersectionRenderId = this.scene.getRenderId();
  45583. };
  45584. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  45585. Canvas2D.prototype._updateOverStatus = function () {
  45586. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  45587. return;
  45588. }
  45589. // Detect a change of over
  45590. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  45591. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  45592. if (prevPrim !== actualPrim) {
  45593. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  45594. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45595. // Notify the previous "over" prim that the pointer is no longer over it
  45596. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  45597. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  45598. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  45599. }
  45600. // Notify the new "over" prim that the pointer is over it
  45601. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  45602. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  45603. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  45604. }
  45605. }
  45606. this._hoverStatusRenderId = this.scene.getRenderId();
  45607. };
  45608. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  45609. if (this._primPointerInfo.isCaptured) {
  45610. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  45611. }
  45612. else {
  45613. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  45614. var pii = _a[_i];
  45615. if (pii.prim === prim) {
  45616. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  45617. return;
  45618. }
  45619. }
  45620. }
  45621. };
  45622. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  45623. if (!this._notifDebugMode) {
  45624. return;
  45625. }
  45626. var debug = "";
  45627. for (var i = 0; i < prim.hierarchyDepth; i++) {
  45628. debug += " ";
  45629. }
  45630. var pii = this._primPointerInfo;
  45631. 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();
  45632. console.log(debug);
  45633. };
  45634. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  45635. var ppi = this._primPointerInfo;
  45636. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  45637. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  45638. this._notifParents(prim, mask);
  45639. }
  45640. var bubbleCancelled = false;
  45641. var cur = prim;
  45642. while (cur) {
  45643. // Only trigger the observers if the primitive is intersected (except for out)
  45644. if (!bubbleCancelled) {
  45645. this._updatePrimPointerPos(cur);
  45646. // Exec the observers
  45647. this._debugExecObserver(cur, mask);
  45648. cur._pointerEventObservable.notifyObservers(ppi, mask);
  45649. this._triggerActionManager(cur, ppi, mask, eventData);
  45650. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  45651. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  45652. if (ppi.cancelBubble) {
  45653. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  45654. return;
  45655. }
  45656. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  45657. bubbleCancelled = true;
  45658. }
  45659. }
  45660. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  45661. if (bubbleCancelled) {
  45662. this._updatePrimPointerPos(cur);
  45663. }
  45664. // Trigger a PointerEnter corresponding to the PointerOver
  45665. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45666. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  45667. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  45668. }
  45669. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45670. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  45671. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  45672. }
  45673. // Loop to the parent
  45674. cur = cur.parent;
  45675. }
  45676. };
  45677. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  45678. var _this = this;
  45679. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  45680. if (!this._globalTransform) {
  45681. this.updateCachedStates(true);
  45682. }
  45683. // Process Trigger related to PointerDown
  45684. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  45685. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  45686. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  45687. this._pickStartingTime = new Date().getTime();
  45688. this._pickedDownPrim = null;
  45689. if (prim.actionManager) {
  45690. this._pickedDownPrim = prim;
  45691. if (prim.actionManager.hasPickTriggers) {
  45692. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45693. switch (eventData.button) {
  45694. case 0:
  45695. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  45696. break;
  45697. case 1:
  45698. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  45699. break;
  45700. case 2:
  45701. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  45702. break;
  45703. }
  45704. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  45705. }
  45706. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  45707. window.setTimeout(function () {
  45708. var ppi = _this._primPointerInfo;
  45709. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  45710. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  45711. var ii = new BABYLON.IntersectInfo2D();
  45712. ii.pickPosition = ppi.canvasPointerPos.clone();
  45713. ii.findFirstOnly = false;
  45714. _this.intersect(ii);
  45715. if (ii.isPrimIntersected(prim) !== null) {
  45716. if (prim.actionManager) {
  45717. 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)) {
  45718. _this._pickStartingTime = 0;
  45719. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  45720. }
  45721. }
  45722. }
  45723. }, BABYLON.ActionManager.LongPressDelay);
  45724. }
  45725. }
  45726. }
  45727. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  45728. this._pickStartingTime = 0;
  45729. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45730. if (prim.actionManager) {
  45731. // OnPickUpTrigger
  45732. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  45733. // OnPickTrigger
  45734. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  45735. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  45736. }
  45737. }
  45738. // OnPickOutTrigger
  45739. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  45740. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  45741. }
  45742. }
  45743. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  45744. if (prim.actionManager) {
  45745. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45746. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  45747. }
  45748. }
  45749. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  45750. if (prim.actionManager) {
  45751. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  45752. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  45753. }
  45754. }
  45755. };
  45756. Canvas2D.prototype._notifParents = function (prim, mask) {
  45757. var pii = this._primPointerInfo;
  45758. var curPrim = this;
  45759. while (curPrim) {
  45760. this._updatePrimPointerPos(curPrim);
  45761. // Fire the proper notification
  45762. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45763. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  45764. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  45765. }
  45766. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45767. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  45768. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  45769. }
  45770. curPrim = curPrim.parent;
  45771. }
  45772. };
  45773. /**
  45774. * Don't forget to call the dispose method when you're done with the Canvas instance.
  45775. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  45776. */
  45777. Canvas2D.prototype.dispose = function () {
  45778. if (!_super.prototype.dispose.call(this)) {
  45779. return false;
  45780. }
  45781. if (this._profilingCanvas) {
  45782. this._profilingCanvas.dispose();
  45783. this._profilingCanvas = null;
  45784. }
  45785. if (this.interactionEnabled) {
  45786. this._setupInteraction(false);
  45787. }
  45788. if (this._beforeRenderObserver) {
  45789. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  45790. this._beforeRenderObserver = null;
  45791. }
  45792. if (this._afterRenderObserver) {
  45793. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  45794. this._afterRenderObserver = null;
  45795. }
  45796. if (this._groupCacheMaps) {
  45797. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  45798. this._groupCacheMaps = null;
  45799. }
  45800. };
  45801. Object.defineProperty(Canvas2D.prototype, "scene", {
  45802. /**
  45803. * Accessor to the Scene that owns the Canvas
  45804. * @returns The instance of the Scene object
  45805. */
  45806. get: function () {
  45807. return this._scene;
  45808. },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. Object.defineProperty(Canvas2D.prototype, "engine", {
  45813. /**
  45814. * Accessor to the Engine that drives the Scene used by this Canvas
  45815. * @returns The instance of the Engine object
  45816. */
  45817. get: function () {
  45818. return this._engine;
  45819. },
  45820. enumerable: true,
  45821. configurable: true
  45822. });
  45823. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  45824. /**
  45825. * Accessor of the Caching Strategy used by this Canvas.
  45826. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  45827. * @returns the value corresponding to the used strategy.
  45828. */
  45829. get: function () {
  45830. return this._cachingStrategy;
  45831. },
  45832. enumerable: true,
  45833. configurable: true
  45834. });
  45835. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  45836. /**
  45837. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  45838. * @returns {}
  45839. */
  45840. get: function () {
  45841. return this._isScreenSpace;
  45842. },
  45843. enumerable: true,
  45844. configurable: true
  45845. });
  45846. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  45847. /**
  45848. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  45849. */
  45850. get: function () {
  45851. return this._worldSpaceNode;
  45852. },
  45853. set: function (val) {
  45854. this._worldSpaceNode = val;
  45855. },
  45856. enumerable: true,
  45857. configurable: true
  45858. });
  45859. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  45860. /**
  45861. * Check if the WebGL Instanced Array extension is supported or not
  45862. */
  45863. get: function () {
  45864. return this._supprtInstancedArray;
  45865. },
  45866. enumerable: true,
  45867. configurable: true
  45868. });
  45869. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  45870. /**
  45871. * Property that defines the fill object used to draw the background of the Canvas.
  45872. * Note that Canvas with a Caching Strategy of
  45873. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  45874. */
  45875. get: function () {
  45876. if (!this._background || !this._background.isVisible) {
  45877. return null;
  45878. }
  45879. return this._background.fill;
  45880. },
  45881. set: function (value) {
  45882. this.checkBackgroundAvailability();
  45883. if (value === this._background.fill) {
  45884. return;
  45885. }
  45886. this._background.fill = value;
  45887. this._background.levelVisible = true;
  45888. },
  45889. enumerable: true,
  45890. configurable: true
  45891. });
  45892. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  45893. /**
  45894. * Property that defines the border object used to draw the background of the Canvas.
  45895. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  45896. */
  45897. get: function () {
  45898. if (!this._background || !this._background.isVisible) {
  45899. return null;
  45900. }
  45901. return this._background.border;
  45902. },
  45903. set: function (value) {
  45904. this.checkBackgroundAvailability();
  45905. if (value === this._background.border) {
  45906. return;
  45907. }
  45908. this._background.border = value;
  45909. this._background.levelVisible = true;
  45910. },
  45911. enumerable: true,
  45912. configurable: true
  45913. });
  45914. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  45915. /**
  45916. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  45917. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  45918. */
  45919. get: function () {
  45920. if (!this._background || !this._background.isVisible) {
  45921. return null;
  45922. }
  45923. return this._background.borderThickness;
  45924. },
  45925. set: function (value) {
  45926. this.checkBackgroundAvailability();
  45927. if (value === this._background.borderThickness) {
  45928. return;
  45929. }
  45930. this._background.borderThickness = value;
  45931. },
  45932. enumerable: true,
  45933. configurable: true
  45934. });
  45935. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  45936. /**
  45937. * You can set the roundRadius of the background
  45938. * @returns The current roundRadius
  45939. */
  45940. get: function () {
  45941. if (!this._background || !this._background.isVisible) {
  45942. return null;
  45943. }
  45944. return this._background.roundRadius;
  45945. },
  45946. set: function (value) {
  45947. this.checkBackgroundAvailability();
  45948. if (value === this._background.roundRadius) {
  45949. return;
  45950. }
  45951. this._background.roundRadius = value;
  45952. this._background.levelVisible = true;
  45953. },
  45954. enumerable: true,
  45955. configurable: true
  45956. });
  45957. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  45958. /**
  45959. * Enable/Disable interaction for this Canvas
  45960. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  45961. */
  45962. get: function () {
  45963. return this._interactionEnabled;
  45964. },
  45965. set: function (enable) {
  45966. this._setupInteraction(enable);
  45967. },
  45968. enumerable: true,
  45969. configurable: true
  45970. });
  45971. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  45972. /**
  45973. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  45974. * @returns {}
  45975. */
  45976. get: function () {
  45977. return this.__engineData;
  45978. },
  45979. enumerable: true,
  45980. configurable: true
  45981. });
  45982. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  45983. if (this._profilingCanvas) {
  45984. return this._profilingCanvas;
  45985. }
  45986. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  45987. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  45988. new BABYLON.Rectangle2D({
  45989. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  45990. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  45991. ]
  45992. })
  45993. ]
  45994. });
  45995. this._profileInfoText = canvas.findById("ProfileInfoText");
  45996. this._profilingCanvas = canvas;
  45997. return canvas;
  45998. };
  45999. Canvas2D.prototype.checkBackgroundAvailability = function () {
  46000. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46001. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  46002. }
  46003. };
  46004. Canvas2D.prototype._initPerfMetrics = function () {
  46005. this._drawCallsOpaqueCounter.fetchNewFrame();
  46006. this._drawCallsAlphaTestCounter.fetchNewFrame();
  46007. this._drawCallsTransparentCounter.fetchNewFrame();
  46008. this._groupRenderCounter.fetchNewFrame();
  46009. this._updateTransparentDataCounter.fetchNewFrame();
  46010. this._cachedGroupRenderCounter.fetchNewFrame();
  46011. this._updateCachedStateCounter.fetchNewFrame();
  46012. this._updateLayoutCounter.fetchNewFrame();
  46013. this._updatePositioningCounter.fetchNewFrame();
  46014. this._updateLocalTransformCounter.fetchNewFrame();
  46015. this._updateGlobalTransformCounter.fetchNewFrame();
  46016. this._boundingInfoRecomputeCounter.fetchNewFrame();
  46017. };
  46018. Canvas2D.prototype._fetchPerfMetrics = function () {
  46019. this._drawCallsOpaqueCounter.addCount(0, true);
  46020. this._drawCallsAlphaTestCounter.addCount(0, true);
  46021. this._drawCallsTransparentCounter.addCount(0, true);
  46022. this._groupRenderCounter.addCount(0, true);
  46023. this._updateTransparentDataCounter.addCount(0, true);
  46024. this._cachedGroupRenderCounter.addCount(0, true);
  46025. this._updateCachedStateCounter.addCount(0, true);
  46026. this._updateLayoutCounter.addCount(0, true);
  46027. this._updatePositioningCounter.addCount(0, true);
  46028. this._updateLocalTransformCounter.addCount(0, true);
  46029. this._updateGlobalTransformCounter.addCount(0, true);
  46030. this._boundingInfoRecomputeCounter.addCount(0, true);
  46031. };
  46032. Canvas2D.prototype._updateProfileCanvas = function () {
  46033. if (this._profileInfoText == null) {
  46034. return;
  46035. }
  46036. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  46037. var p = "Draw Calls:\n" +
  46038. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  46039. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  46040. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  46041. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  46042. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  46043. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  46044. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  46045. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  46046. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  46047. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  46048. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  46049. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  46050. this._profileInfoText.text = p;
  46051. };
  46052. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  46053. switch (renderMode) {
  46054. case BABYLON.Render2DContext.RenderModeOpaque:
  46055. this._drawCallsOpaqueCounter.addCount(count, false);
  46056. return;
  46057. case BABYLON.Render2DContext.RenderModeAlphaTest:
  46058. this._drawCallsAlphaTestCounter.addCount(count, false);
  46059. return;
  46060. case BABYLON.Render2DContext.RenderModeTransparent:
  46061. this._drawCallsTransparentCounter.addCount(count, false);
  46062. return;
  46063. }
  46064. };
  46065. Canvas2D.prototype._addGroupRenderCount = function (count) {
  46066. this._groupRenderCounter.addCount(count, false);
  46067. };
  46068. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  46069. this._updateTransparentDataCounter.addCount(count, false);
  46070. };
  46071. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  46072. this._cachedGroupRenderCounter.addCount(count, false);
  46073. };
  46074. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  46075. this._updateCachedStateCounter.addCount(count, false);
  46076. };
  46077. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  46078. this._updateLayoutCounter.addCount(count, false);
  46079. };
  46080. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  46081. this._updatePositioningCounter.addCount(count, false);
  46082. };
  46083. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  46084. this._updateLocalTransformCounter.addCount(count, false);
  46085. };
  46086. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  46087. this._updateGlobalTransformCounter.addCount(count, false);
  46088. };
  46089. Canvas2D.prototype.onPrimBecomesDirty = function () {
  46090. this._addPrimToDirtyList(this);
  46091. };
  46092. Canvas2D.prototype._updateTrackedNodes = function () {
  46093. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46094. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46095. var rh = this.engine.getRenderHeight();
  46096. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  46097. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  46098. var group = _a[_i];
  46099. if (group.isDisposed || !group.isVisible) {
  46100. continue;
  46101. }
  46102. var node = group.trackedNode;
  46103. var worldMtx = node.getWorldMatrix();
  46104. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  46105. group.x = Math.round(proj.x);
  46106. group.y = Math.round(rh - proj.y);
  46107. }
  46108. };
  46109. /**
  46110. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  46111. */
  46112. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  46113. this._updateCanvasState(forceRecompute);
  46114. };
  46115. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  46116. if (this._globalTransformStep < 2) {
  46117. return;
  46118. }
  46119. var n = this.worldSpaceCanvasNode;
  46120. var bi = n.getBoundingInfo().boundingBox;
  46121. var v = bi.vectorsWorld;
  46122. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46123. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46124. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  46125. var projPoints = new Array(4);
  46126. for (var i = 0; i < 4; i++) {
  46127. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  46128. }
  46129. var left = projPoints[3].subtract(projPoints[0]).length();
  46130. var top = projPoints[3].subtract(projPoints[1]).length();
  46131. var right = projPoints[1].subtract(projPoints[2]).length();
  46132. var bottom = projPoints[2].subtract(projPoints[0]).length();
  46133. var w = Math.round(Math.max(top, bottom));
  46134. var h = Math.round(Math.max(right, left));
  46135. var isW = w > h;
  46136. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  46137. var edge = Math.max(w, h);
  46138. if (edge < 256) {
  46139. edge = 256;
  46140. }
  46141. else {
  46142. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  46143. }
  46144. // Clip values if needed
  46145. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  46146. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  46147. if (newScale !== this.scale) {
  46148. var scale = newScale;
  46149. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  46150. this._setRenderingScale(scale);
  46151. }
  46152. };
  46153. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  46154. // Check if the update has already been made for this render Frame
  46155. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  46156. return;
  46157. }
  46158. // Detect a change of rendering size
  46159. var renderingSizeChanged = false;
  46160. var newWidth = this.engine.getRenderWidth();
  46161. if (newWidth !== this._renderingSize.width) {
  46162. renderingSizeChanged = true;
  46163. }
  46164. this._renderingSize.width = newWidth;
  46165. var newHeight = this.engine.getRenderHeight();
  46166. if (newHeight !== this._renderingSize.height) {
  46167. renderingSizeChanged = true;
  46168. }
  46169. this._renderingSize.height = newHeight;
  46170. // If the canvas fit the rendering size and it changed, update
  46171. if (renderingSizeChanged && this._fitRenderingDevice) {
  46172. this.size = this._renderingSize;
  46173. if (this._background) {
  46174. this._background.size = this.size;
  46175. }
  46176. // Dirty the Layout at the Canvas level to recompute as the size changed
  46177. this._setLayoutDirty();
  46178. }
  46179. var context = new BABYLON.PrepareRender2DContext();
  46180. ++this._globalTransformProcessStep;
  46181. this.updateCachedStates(false);
  46182. this._prepareGroupRender(context);
  46183. this._updateRenderId = this.scene.getRenderId();
  46184. };
  46185. /**
  46186. * Method that renders the Canvas, you should not invoke
  46187. */
  46188. Canvas2D.prototype._render = function () {
  46189. this._initPerfMetrics();
  46190. this._updateTrackedNodes();
  46191. this._updateCanvasState(false);
  46192. if (!this._isScreenSpace) {
  46193. this._updateAdaptiveSizeWorldCanvas();
  46194. }
  46195. this._updateCanvasState(false);
  46196. if (this._primPointerInfo.canvasPointerPos) {
  46197. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  46198. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  46199. }
  46200. this.engine.setState(false);
  46201. this._groupRender();
  46202. if (!this._isScreenSpace) {
  46203. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  46204. this.worldSpaceCacheChanged();
  46205. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  46206. }
  46207. }
  46208. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  46209. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  46210. this._cachedCanvasGroup._renderCachedCanvas();
  46211. }
  46212. this._fetchPerfMetrics();
  46213. this._updateProfileCanvas();
  46214. };
  46215. /**
  46216. * Internal method that allocate a cache for the given group.
  46217. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  46218. * @param group The group to allocate the cache of.
  46219. * @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.
  46220. */
  46221. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  46222. if (useMipMap === void 0) { useMipMap = false; }
  46223. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  46224. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  46225. // Determine size
  46226. var size = group.actualSize;
  46227. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  46228. if (minSize) {
  46229. size.width = Math.max(minSize.width, size.width);
  46230. size.height = Math.max(minSize.height, size.height);
  46231. }
  46232. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  46233. // Try to find a spot in one of the cached texture
  46234. var res = null;
  46235. var map;
  46236. for (var _i = 0; _i < mapArray.length; _i++) {
  46237. var _map = mapArray[_i];
  46238. map = _map;
  46239. var node = map.allocateRect(size);
  46240. if (node) {
  46241. res = { node: node, texture: map };
  46242. break;
  46243. }
  46244. }
  46245. // Couldn't find a map that could fit the rect, create a new map for it
  46246. if (!res) {
  46247. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  46248. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  46249. if (size.width > mapSize.width || size.height > mapSize.height) {
  46250. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  46251. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  46252. }
  46253. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  46254. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  46255. map.anisotropicFilteringLevel = 4;
  46256. mapArray.splice(0, 0, map);
  46257. var node = map.allocateRect(size);
  46258. res = { node: node, texture: map };
  46259. }
  46260. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  46261. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  46262. if (group !== this || this._isScreenSpace) {
  46263. var node = res.node;
  46264. // 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
  46265. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  46266. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  46267. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  46268. sprite.zOrder = 1;
  46269. sprite.origin = BABYLON.Vector2.Zero();
  46270. }
  46271. else {
  46272. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  46273. sprite.origin = group.origin.clone();
  46274. res.sprite = sprite;
  46275. }
  46276. }
  46277. return res;
  46278. };
  46279. /**
  46280. * Internal method used to register a Scene Node to track position for the given group
  46281. * Do not invoke this method, for internal purpose only.
  46282. * @param group the group to track its associated Scene Node
  46283. */
  46284. Canvas2D.prototype._registerTrackedNode = function (group) {
  46285. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46286. return;
  46287. }
  46288. this._trackedGroups.push(group);
  46289. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46290. };
  46291. /**
  46292. * Internal method used to unregister a tracked Scene Node
  46293. * Do not invoke this method, it's for internal purpose only.
  46294. * @param group the group to unregister its tracked Scene Node from.
  46295. */
  46296. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  46297. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46298. return;
  46299. }
  46300. var i = this._trackedGroups.indexOf(group);
  46301. if (i !== -1) {
  46302. this._trackedGroups.splice(i, 1);
  46303. }
  46304. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46305. };
  46306. /**
  46307. * Get a Solid Color Brush instance matching the given color.
  46308. * @param color The color to retrieve
  46309. * @return A shared instance of the SolidColorBrush2D class that use the given color
  46310. */
  46311. Canvas2D.GetSolidColorBrush = function (color) {
  46312. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  46313. };
  46314. /**
  46315. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  46316. * @param color The color to retrieve
  46317. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  46318. */
  46319. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  46320. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  46321. };
  46322. /**
  46323. * Get a Gradient Color Brush
  46324. * @param color1 starting color
  46325. * @param color2 engine color
  46326. * @param translation translation vector to apply. default is [0;0]
  46327. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  46328. * @param scale scaling factor to apply. default is 1.
  46329. */
  46330. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  46331. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  46332. if (rotation === void 0) { rotation = 0; }
  46333. if (scale === void 0) { scale = 1; }
  46334. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  46335. };
  46336. /**
  46337. * Create a solid or gradient brush from a string value.
  46338. * @param brushString should be either
  46339. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  46340. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  46341. */
  46342. Canvas2D.GetBrushFromString = function (brushString) {
  46343. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  46344. brushString = brushString.trim();
  46345. var split = brushString.split(",");
  46346. // Solid, formatted as: "[solid:]#FF808080"
  46347. if (split.length === 1) {
  46348. var value = null;
  46349. if (brushString.indexOf("solid:") === 0) {
  46350. value = brushString.substr(6).trim();
  46351. }
  46352. else if (brushString.indexOf("#") === 0) {
  46353. value = brushString;
  46354. }
  46355. else {
  46356. return null;
  46357. }
  46358. return Canvas2D.GetSolidColorBrushFromHex(value);
  46359. }
  46360. else {
  46361. if (split[0].indexOf("gradient:") === 0) {
  46362. split[0] = split[0].substr(9).trim();
  46363. }
  46364. try {
  46365. var start = BABYLON.Color4.FromHexString(split[0].trim());
  46366. var end = BABYLON.Color4.FromHexString(split[1].trim());
  46367. var t = BABYLON.Vector2.Zero();
  46368. if (split.length > 2) {
  46369. var v = split[2].trim();
  46370. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  46371. return null;
  46372. }
  46373. var sep = v.indexOf(":");
  46374. var x = parseFloat(v.substr(1, sep));
  46375. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  46376. t = new BABYLON.Vector2(x, y);
  46377. }
  46378. var r = 0;
  46379. if (split.length > 3) {
  46380. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  46381. }
  46382. var s = 1;
  46383. if (split.length > 4) {
  46384. s = parseFloat(split[4].trim());
  46385. }
  46386. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  46387. }
  46388. catch (e) {
  46389. return null;
  46390. }
  46391. }
  46392. };
  46393. /**
  46394. * 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.
  46395. * This strategy doesn't allow primitives added directly as children of the Canvas.
  46396. * 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.
  46397. */
  46398. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  46399. /**
  46400. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  46401. * 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.
  46402. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  46403. * 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.
  46404. */
  46405. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  46406. /**
  46407. * 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).
  46408. */
  46409. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  46410. /**
  46411. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  46412. * 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).
  46413. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  46414. */
  46415. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  46416. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  46417. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  46418. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  46419. Canvas2D._m = BABYLON.Matrix.Identity();
  46420. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  46421. /**
  46422. * Define the default size used for both the width and height of a MapTexture to allocate.
  46423. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  46424. */
  46425. Canvas2D._groupTextureCacheSize = 1024;
  46426. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  46427. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  46428. Canvas2D = __decorate([
  46429. BABYLON.className("Canvas2D")
  46430. ], Canvas2D);
  46431. return Canvas2D;
  46432. })(BABYLON.Group2D);
  46433. BABYLON.Canvas2D = Canvas2D;
  46434. var WorldSpaceCanvas2D = (function (_super) {
  46435. __extends(WorldSpaceCanvas2D, _super);
  46436. /**
  46437. * 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.
  46438. * 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.
  46439. * @param scene the Scene that owns the Canvas
  46440. * @param size the dimension of the Canvas in World Space
  46441. * @param settings a combination of settings, possible ones are
  46442. * - children: an array of direct children primitives
  46443. * - id: a text identifier, for information purpose only, default is null.
  46444. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  46445. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  46446. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  46447. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  46448. * - 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).
  46449. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46450. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46451. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46452. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46453. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46454. * - 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.
  46455. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  46456. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46457. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46458. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46459. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46460. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46461. */
  46462. function WorldSpaceCanvas2D(scene, size, settings) {
  46463. BABYLON.Prim2DBase._isCanvasInit = true;
  46464. var s = settings;
  46465. s.isScreenSpace = false;
  46466. s.size = size.clone();
  46467. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  46468. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  46469. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  46470. }
  46471. _super.call(this, scene, settings);
  46472. BABYLON.Prim2DBase._isCanvasInit = false;
  46473. this._renderableData._useMipMap = true;
  46474. this._renderableData._anisotropicLevel = 8;
  46475. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  46476. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  46477. //}
  46478. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  46479. var id = settings ? settings.id || null : null;
  46480. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  46481. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  46482. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  46483. if (settings.maxAdaptiveCanvasSize == null) {
  46484. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  46485. }
  46486. else {
  46487. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  46488. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  46489. }
  46490. if (createWorldSpaceNode) {
  46491. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  46492. var vertexData = BABYLON.VertexData.CreatePlane({
  46493. width: size.width,
  46494. height: size.height,
  46495. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  46496. });
  46497. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  46498. this.applyCachedTexture(vertexData, mtl);
  46499. vertexData.applyToMesh(plane, true);
  46500. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  46501. mtl.disableLighting = true;
  46502. mtl.useAlphaFromDiffuseTexture = true;
  46503. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  46504. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  46505. plane.material = mtl;
  46506. this._worldSpaceNode = plane;
  46507. }
  46508. else {
  46509. this._worldSpaceNode = settings.customWorldSpaceNode;
  46510. this.applyCachedTexture(null, null);
  46511. }
  46512. }
  46513. WorldSpaceCanvas2D = __decorate([
  46514. BABYLON.className("WorldSpaceCanvas2D")
  46515. ], WorldSpaceCanvas2D);
  46516. return WorldSpaceCanvas2D;
  46517. })(Canvas2D);
  46518. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  46519. var ScreenSpaceCanvas2D = (function (_super) {
  46520. __extends(ScreenSpaceCanvas2D, _super);
  46521. /**
  46522. * 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.
  46523. * 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.
  46524. * All caching strategies will be available.
  46525. * 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]
  46526. * @param scene the Scene that owns the Canvas
  46527. * @param settings a combination of settings, possible ones are
  46528. * - children: an array of direct children primitives
  46529. * - id: a text identifier, for information purpose only
  46530. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  46531. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  46532. * - position: 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]
  46533. * - width: the width of the Canvas. you can alternatively use the size setting.
  46534. * - height: the height of the Canvas. you can alternatively use the size setting.
  46535. * - 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
  46536. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  46537. * - 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.
  46538. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46539. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46540. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46541. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  46542. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46543. * - 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.
  46544. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46545. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46546. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46547. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46548. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  46549. */
  46550. function ScreenSpaceCanvas2D(scene, settings) {
  46551. BABYLON.Prim2DBase._isCanvasInit = true;
  46552. _super.call(this, scene, settings);
  46553. }
  46554. ScreenSpaceCanvas2D = __decorate([
  46555. BABYLON.className("ScreenSpaceCanvas2D")
  46556. ], ScreenSpaceCanvas2D);
  46557. return ScreenSpaceCanvas2D;
  46558. })(Canvas2D);
  46559. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  46560. })(BABYLON || (BABYLON = {}));
  46561. var BABYLON;
  46562. (function (BABYLON) {
  46563. /**
  46564. * This is the class that is used to display a World Space Canvas into a 3D scene
  46565. */
  46566. var WorldSpaceCanvas2DNode = (function (_super) {
  46567. __extends(WorldSpaceCanvas2DNode, _super);
  46568. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  46569. _super.call(this, name, scene);
  46570. this._canvas = canvas;
  46571. }
  46572. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  46573. _super.prototype.dispose.call(this);
  46574. if (this._canvas) {
  46575. this._canvas.dispose();
  46576. this._canvas = null;
  46577. }
  46578. };
  46579. return WorldSpaceCanvas2DNode;
  46580. })(BABYLON.Mesh);
  46581. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  46582. })(BABYLON || (BABYLON = {}));
  46583. var BABYLON;
  46584. (function (BABYLON) {
  46585. var LayoutEngineBase = (function () {
  46586. function LayoutEngineBase() {
  46587. this.layoutDirtyOnPropertyChangedMask = 0;
  46588. }
  46589. LayoutEngineBase.prototype.updateLayout = function (prim) {
  46590. };
  46591. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  46592. get: function () {
  46593. return false;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. LayoutEngineBase.prototype.isLocked = function () {
  46599. return this._isLocked;
  46600. };
  46601. LayoutEngineBase.prototype.lock = function () {
  46602. if (this._isLocked) {
  46603. return false;
  46604. }
  46605. this._isLocked = true;
  46606. return true;
  46607. };
  46608. LayoutEngineBase = __decorate([
  46609. BABYLON.className("LayoutEngineBase")
  46610. ], LayoutEngineBase);
  46611. return LayoutEngineBase;
  46612. })();
  46613. BABYLON.LayoutEngineBase = LayoutEngineBase;
  46614. var CanvasLayoutEngine = (function (_super) {
  46615. __extends(CanvasLayoutEngine, _super);
  46616. function CanvasLayoutEngine() {
  46617. _super.apply(this, arguments);
  46618. }
  46619. // A very simple (no) layout computing...
  46620. // The Canvas and its direct children gets the Canvas' size as Layout Area
  46621. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  46622. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  46623. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  46624. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  46625. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  46626. var child = _a[_i];
  46627. this._doUpdate(child);
  46628. }
  46629. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  46630. }
  46631. };
  46632. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  46633. // Canvas ?
  46634. if (prim instanceof BABYLON.Canvas2D) {
  46635. prim.layoutArea = prim.actualSize;
  46636. }
  46637. else if (prim.parent instanceof BABYLON.Canvas2D) {
  46638. prim.layoutArea = prim.owner.actualSize;
  46639. }
  46640. else {
  46641. prim.layoutArea = prim.parent.contentArea;
  46642. }
  46643. };
  46644. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  46645. get: function () {
  46646. return true;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  46652. CanvasLayoutEngine = __decorate([
  46653. BABYLON.className("CanvasLayoutEngine")
  46654. ], CanvasLayoutEngine);
  46655. return CanvasLayoutEngine;
  46656. })(LayoutEngineBase);
  46657. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  46658. var StackPanelLayoutEngine = (function (_super) {
  46659. __extends(StackPanelLayoutEngine, _super);
  46660. function StackPanelLayoutEngine() {
  46661. _super.call(this);
  46662. this._isHorizontal = true;
  46663. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  46664. }
  46665. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  46666. get: function () {
  46667. if (!StackPanelLayoutEngine._horizontal) {
  46668. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  46669. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  46670. StackPanelLayoutEngine._horizontal.lock();
  46671. }
  46672. return StackPanelLayoutEngine._horizontal;
  46673. },
  46674. enumerable: true,
  46675. configurable: true
  46676. });
  46677. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  46678. get: function () {
  46679. if (!StackPanelLayoutEngine._vertical) {
  46680. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  46681. StackPanelLayoutEngine._vertical.isHorizontal = false;
  46682. StackPanelLayoutEngine._vertical.lock();
  46683. }
  46684. return StackPanelLayoutEngine._vertical;
  46685. },
  46686. enumerable: true,
  46687. configurable: true
  46688. });
  46689. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  46690. get: function () {
  46691. return this._isHorizontal;
  46692. },
  46693. set: function (val) {
  46694. if (this.isLocked()) {
  46695. return;
  46696. }
  46697. this._isHorizontal = val;
  46698. },
  46699. enumerable: true,
  46700. configurable: true
  46701. });
  46702. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  46703. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  46704. var x = 0;
  46705. var y = 0;
  46706. var h = this.isHorizontal;
  46707. var max = 0;
  46708. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  46709. var child = _a[_i];
  46710. var layoutArea = child.layoutArea;
  46711. child.margin.computeArea(child.actualSize, layoutArea);
  46712. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  46713. }
  46714. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  46715. var child = _c[_b];
  46716. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  46717. var layoutArea = child.layoutArea;
  46718. if (h) {
  46719. x += layoutArea.width;
  46720. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  46721. }
  46722. else {
  46723. y += layoutArea.height;
  46724. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  46725. }
  46726. }
  46727. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  46728. }
  46729. };
  46730. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  46731. get: function () {
  46732. return false;
  46733. },
  46734. enumerable: true,
  46735. configurable: true
  46736. });
  46737. StackPanelLayoutEngine._horizontal = null;
  46738. StackPanelLayoutEngine._vertical = null;
  46739. StackPanelLayoutEngine = __decorate([
  46740. BABYLON.className("StackPanelLayoutEngine")
  46741. ], StackPanelLayoutEngine);
  46742. return StackPanelLayoutEngine;
  46743. })(LayoutEngineBase);
  46744. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  46745. })(BABYLON || (BABYLON = {}));
  46746. var BABYLON;
  46747. (function (BABYLON) {
  46748. var ShaderMaterial = (function (_super) {
  46749. __extends(ShaderMaterial, _super);
  46750. function ShaderMaterial(name, scene, shaderPath, options) {
  46751. _super.call(this, name, scene);
  46752. this._textures = {};
  46753. this._textureArrays = {};
  46754. this._floats = {};
  46755. this._floatsArrays = {};
  46756. this._colors3 = {};
  46757. this._colors4 = {};
  46758. this._vectors2 = {};
  46759. this._vectors3 = {};
  46760. this._vectors4 = {};
  46761. this._matrices = {};
  46762. this._matrices3x3 = {};
  46763. this._matrices2x2 = {};
  46764. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46765. this._shaderPath = shaderPath;
  46766. options.needAlphaBlending = options.needAlphaBlending || false;
  46767. options.needAlphaTesting = options.needAlphaTesting || false;
  46768. options.attributes = options.attributes || ["position", "normal", "uv"];
  46769. options.uniforms = options.uniforms || ["worldViewProjection"];
  46770. options.samplers = options.samplers || [];
  46771. options.defines = options.defines || [];
  46772. this._options = options;
  46773. }
  46774. ShaderMaterial.prototype.needAlphaBlending = function () {
  46775. return this._options.needAlphaBlending;
  46776. };
  46777. ShaderMaterial.prototype.needAlphaTesting = function () {
  46778. return this._options.needAlphaTesting;
  46779. };
  46780. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46781. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46782. this._options.uniforms.push(uniformName);
  46783. }
  46784. };
  46785. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46786. if (this._options.samplers.indexOf(name) === -1) {
  46787. this._options.samplers.push(name);
  46788. }
  46789. this._textures[name] = texture;
  46790. return this;
  46791. };
  46792. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46793. if (this._options.samplers.indexOf(name) === -1) {
  46794. this._options.samplers.push(name);
  46795. }
  46796. this._checkUniform(name);
  46797. this._textureArrays[name] = textures;
  46798. return this;
  46799. };
  46800. ShaderMaterial.prototype.setFloat = function (name, value) {
  46801. this._checkUniform(name);
  46802. this._floats[name] = value;
  46803. return this;
  46804. };
  46805. ShaderMaterial.prototype.setFloats = function (name, value) {
  46806. this._checkUniform(name);
  46807. this._floatsArrays[name] = value;
  46808. return this;
  46809. };
  46810. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46811. this._checkUniform(name);
  46812. this._colors3[name] = value;
  46813. return this;
  46814. };
  46815. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46816. this._checkUniform(name);
  46817. this._colors4[name] = value;
  46818. return this;
  46819. };
  46820. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46821. this._checkUniform(name);
  46822. this._vectors2[name] = value;
  46823. return this;
  46824. };
  46825. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46826. this._checkUniform(name);
  46827. this._vectors3[name] = value;
  46828. return this;
  46829. };
  46830. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46831. this._checkUniform(name);
  46832. this._vectors4[name] = value;
  46833. return this;
  46834. };
  46835. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46836. this._checkUniform(name);
  46837. this._matrices[name] = value;
  46838. return this;
  46839. };
  46840. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46841. this._checkUniform(name);
  46842. this._matrices3x3[name] = value;
  46843. return this;
  46844. };
  46845. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46846. this._checkUniform(name);
  46847. this._matrices2x2[name] = value;
  46848. return this;
  46849. };
  46850. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46851. var scene = this.getScene();
  46852. var engine = scene.getEngine();
  46853. if (!this.checkReadyOnEveryCall) {
  46854. if (this._renderId === scene.getRenderId()) {
  46855. return true;
  46856. }
  46857. }
  46858. // Instances
  46859. var defines = [];
  46860. var fallbacks = new BABYLON.EffectFallbacks();
  46861. if (useInstances) {
  46862. defines.push("#define INSTANCES");
  46863. }
  46864. for (var index = 0; index < this._options.defines.length; index++) {
  46865. defines.push(this._options.defines[index]);
  46866. }
  46867. // Bones
  46868. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46869. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46870. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46871. fallbacks.addCPUSkinningFallback(0, mesh);
  46872. }
  46873. // Alpha test
  46874. if (engine.getAlphaTesting()) {
  46875. defines.push("#define ALPHATEST");
  46876. }
  46877. var previousEffect = this._effect;
  46878. var join = defines.join("\n");
  46879. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  46880. if (!this._effect.isReady()) {
  46881. return false;
  46882. }
  46883. if (previousEffect !== this._effect) {
  46884. scene.resetCachedMaterial();
  46885. }
  46886. this._renderId = scene.getRenderId();
  46887. return true;
  46888. };
  46889. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46890. var scene = this.getScene();
  46891. if (this._options.uniforms.indexOf("world") !== -1) {
  46892. this._effect.setMatrix("world", world);
  46893. }
  46894. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46895. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46896. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46897. }
  46898. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46899. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46900. }
  46901. };
  46902. ShaderMaterial.prototype.bind = function (world, mesh) {
  46903. // Std values
  46904. this.bindOnlyWorldMatrix(world);
  46905. if (this.getScene().getCachedMaterial() !== this) {
  46906. if (this._options.uniforms.indexOf("view") !== -1) {
  46907. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46908. }
  46909. if (this._options.uniforms.indexOf("projection") !== -1) {
  46910. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46911. }
  46912. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46913. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46914. }
  46915. // Bones
  46916. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46917. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46918. }
  46919. var name;
  46920. // Texture
  46921. for (name in this._textures) {
  46922. this._effect.setTexture(name, this._textures[name]);
  46923. }
  46924. // Texture arrays
  46925. for (name in this._textureArrays) {
  46926. this._effect.setTextureArray(name, this._textureArrays[name]);
  46927. }
  46928. // Float
  46929. for (name in this._floats) {
  46930. this._effect.setFloat(name, this._floats[name]);
  46931. }
  46932. // Float s
  46933. for (name in this._floatsArrays) {
  46934. this._effect.setArray(name, this._floatsArrays[name]);
  46935. }
  46936. // Color3
  46937. for (name in this._colors3) {
  46938. this._effect.setColor3(name, this._colors3[name]);
  46939. }
  46940. // Color4
  46941. for (name in this._colors4) {
  46942. var color = this._colors4[name];
  46943. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46944. }
  46945. // Vector2
  46946. for (name in this._vectors2) {
  46947. this._effect.setVector2(name, this._vectors2[name]);
  46948. }
  46949. // Vector3
  46950. for (name in this._vectors3) {
  46951. this._effect.setVector3(name, this._vectors3[name]);
  46952. }
  46953. // Vector4
  46954. for (name in this._vectors4) {
  46955. this._effect.setVector4(name, this._vectors4[name]);
  46956. }
  46957. // Matrix
  46958. for (name in this._matrices) {
  46959. this._effect.setMatrix(name, this._matrices[name]);
  46960. }
  46961. // Matrix 3x3
  46962. for (name in this._matrices3x3) {
  46963. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46964. }
  46965. // Matrix 2x2
  46966. for (name in this._matrices2x2) {
  46967. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46968. }
  46969. }
  46970. _super.prototype.bind.call(this, world, mesh);
  46971. };
  46972. ShaderMaterial.prototype.clone = function (name) {
  46973. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46974. return newShaderMaterial;
  46975. };
  46976. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46977. if (forceDisposeTextures) {
  46978. var name;
  46979. for (name in this._textures) {
  46980. this._textures[name].dispose();
  46981. }
  46982. for (name in this._textureArrays) {
  46983. var array = this._textureArrays[name];
  46984. for (var index = 0; index < array.length; index++) {
  46985. array[index].dispose();
  46986. }
  46987. }
  46988. }
  46989. this._textures = {};
  46990. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46991. };
  46992. ShaderMaterial.prototype.serialize = function () {
  46993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46994. serializationObject.customType = "BABYLON.ShaderMaterial";
  46995. serializationObject.options = this._options;
  46996. serializationObject.shaderPath = this._shaderPath;
  46997. var name;
  46998. // Texture
  46999. serializationObject.textures = {};
  47000. for (name in this._textures) {
  47001. serializationObject.textures[name] = this._textures[name].serialize();
  47002. }
  47003. // Texture arrays
  47004. serializationObject.textureArrays = {};
  47005. for (name in this._textureArrays) {
  47006. serializationObject.textureArrays[name] = [];
  47007. var array = this._textureArrays[name];
  47008. for (var index = 0; index < array.length; index++) {
  47009. serializationObject.textureArrays[name].push(array[index].serialize());
  47010. }
  47011. }
  47012. // Float
  47013. serializationObject.floats = {};
  47014. for (name in this._floats) {
  47015. serializationObject.floats[name] = this._floats[name];
  47016. }
  47017. // Float s
  47018. serializationObject.floatArrays = {};
  47019. for (name in this._floatsArrays) {
  47020. serializationObject.floatArrays[name] = this._floatsArrays[name];
  47021. }
  47022. // Color3
  47023. serializationObject.colors3 = {};
  47024. for (name in this._colors3) {
  47025. serializationObject.colors3[name] = this._colors3[name].asArray();
  47026. }
  47027. // Color4
  47028. serializationObject.colors4 = {};
  47029. for (name in this._colors4) {
  47030. serializationObject.colors4[name] = this._colors4[name].asArray();
  47031. }
  47032. // Vector2
  47033. serializationObject.vectors2 = {};
  47034. for (name in this._vectors2) {
  47035. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47036. }
  47037. // Vector3
  47038. serializationObject.vectors3 = {};
  47039. for (name in this._vectors3) {
  47040. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47041. }
  47042. // Vector4
  47043. serializationObject.vectors4 = {};
  47044. for (name in this._vectors4) {
  47045. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47046. }
  47047. // Matrix
  47048. serializationObject.matrices = {};
  47049. for (name in this._matrices) {
  47050. serializationObject.matrices[name] = this._matrices[name].asArray();
  47051. }
  47052. // Matrix 3x3
  47053. serializationObject.matrices3x3 = {};
  47054. for (name in this._matrices3x3) {
  47055. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47056. }
  47057. // Matrix 2x2
  47058. serializationObject.matrices2x2 = {};
  47059. for (name in this._matrices2x2) {
  47060. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47061. }
  47062. return serializationObject;
  47063. };
  47064. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47065. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47066. var name;
  47067. // Texture
  47068. for (name in source.textures) {
  47069. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47070. }
  47071. // Texture arrays
  47072. for (name in source.textureArrays) {
  47073. var array = source.textureArrays[name];
  47074. var textureArray = new Array();
  47075. for (var index = 0; index < array.length; index++) {
  47076. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47077. }
  47078. material.setTextureArray(name, textureArray);
  47079. }
  47080. // Float
  47081. for (name in source.floats) {
  47082. material.setFloat(name, source.floats[name]);
  47083. }
  47084. // Float s
  47085. for (name in source.floatsArrays) {
  47086. material.setFloats(name, source.floatsArrays[name]);
  47087. }
  47088. // Color3
  47089. for (name in source.colors3) {
  47090. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47091. }
  47092. // Color4
  47093. for (name in source.colors4) {
  47094. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47095. }
  47096. // Vector2
  47097. for (name in source.vectors2) {
  47098. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47099. }
  47100. // Vector3
  47101. for (name in source.vectors3) {
  47102. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47103. }
  47104. // Vector4
  47105. for (name in source.vectors4) {
  47106. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47107. }
  47108. // Matrix
  47109. for (name in source.matrices) {
  47110. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47111. }
  47112. // Matrix 3x3
  47113. for (name in source.matrices3x3) {
  47114. material.setMatrix3x3(name, source.matrices3x3[name]);
  47115. }
  47116. // Matrix 2x2
  47117. for (name in source.matrices2x2) {
  47118. material.setMatrix2x2(name, source.matrices2x2[name]);
  47119. }
  47120. return material;
  47121. };
  47122. return ShaderMaterial;
  47123. })(BABYLON.Material);
  47124. BABYLON.ShaderMaterial = ShaderMaterial;
  47125. })(BABYLON || (BABYLON = {}));
  47126. var BABYLON;
  47127. (function (BABYLON) {
  47128. var Internals;
  47129. (function (Internals) {
  47130. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  47131. // All values and structures referenced from:
  47132. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  47133. var DDS_MAGIC = 0x20534444;
  47134. 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;
  47135. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  47136. 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;
  47137. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  47138. function FourCCToInt32(value) {
  47139. return value.charCodeAt(0) +
  47140. (value.charCodeAt(1) << 8) +
  47141. (value.charCodeAt(2) << 16) +
  47142. (value.charCodeAt(3) << 24);
  47143. }
  47144. function Int32ToFourCC(value) {
  47145. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  47146. }
  47147. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  47148. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  47149. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  47150. var headerLengthInt = 31; // The header length in 32 bit ints
  47151. // Offsets into the header array
  47152. var off_magic = 0;
  47153. var off_size = 1;
  47154. var off_flags = 2;
  47155. var off_height = 3;
  47156. var off_width = 4;
  47157. var off_mipmapCount = 7;
  47158. var off_pfFlags = 20;
  47159. var off_pfFourCC = 21;
  47160. var off_RGBbpp = 22;
  47161. var off_RMask = 23;
  47162. var off_GMask = 24;
  47163. var off_BMask = 25;
  47164. var off_AMask = 26;
  47165. var off_caps1 = 27;
  47166. var off_caps2 = 28;
  47167. ;
  47168. var DDSTools = (function () {
  47169. function DDSTools() {
  47170. }
  47171. DDSTools.GetDDSInfo = function (arrayBuffer) {
  47172. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  47173. var mipmapCount = 1;
  47174. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  47175. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47176. }
  47177. return {
  47178. width: header[off_width],
  47179. height: header[off_height],
  47180. mipmapCount: mipmapCount,
  47181. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  47182. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  47183. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  47184. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  47185. };
  47186. };
  47187. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47188. var byteArray = new Uint8Array(dataLength);
  47189. var srcData = new Uint8Array(arrayBuffer);
  47190. var index = 0;
  47191. for (var y = height - 1; y >= 0; y--) {
  47192. for (var x = 0; x < width; x++) {
  47193. var srcPos = dataOffset + (x + y * width) * 4;
  47194. byteArray[index + 2] = srcData[srcPos];
  47195. byteArray[index + 1] = srcData[srcPos + 1];
  47196. byteArray[index] = srcData[srcPos + 2];
  47197. byteArray[index + 3] = srcData[srcPos + 3];
  47198. index += 4;
  47199. }
  47200. }
  47201. return byteArray;
  47202. };
  47203. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47204. var byteArray = new Uint8Array(dataLength);
  47205. var srcData = new Uint8Array(arrayBuffer);
  47206. var index = 0;
  47207. for (var y = height - 1; y >= 0; y--) {
  47208. for (var x = 0; x < width; x++) {
  47209. var srcPos = dataOffset + (x + y * width) * 3;
  47210. byteArray[index + 2] = srcData[srcPos];
  47211. byteArray[index + 1] = srcData[srcPos + 1];
  47212. byteArray[index] = srcData[srcPos + 2];
  47213. index += 3;
  47214. }
  47215. }
  47216. return byteArray;
  47217. };
  47218. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47219. var byteArray = new Uint8Array(dataLength);
  47220. var srcData = new Uint8Array(arrayBuffer);
  47221. var index = 0;
  47222. for (var y = height - 1; y >= 0; y--) {
  47223. for (var x = 0; x < width; x++) {
  47224. var srcPos = dataOffset + (x + y * width);
  47225. byteArray[index] = srcData[srcPos];
  47226. index++;
  47227. }
  47228. }
  47229. return byteArray;
  47230. };
  47231. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  47232. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  47233. if (header[off_magic] != DDS_MAGIC) {
  47234. BABYLON.Tools.Error("Invalid magic number in DDS header");
  47235. return;
  47236. }
  47237. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  47238. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  47239. return;
  47240. }
  47241. if (info.isFourCC) {
  47242. fourCC = header[off_pfFourCC];
  47243. switch (fourCC) {
  47244. case FOURCC_DXT1:
  47245. blockBytes = 8;
  47246. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47247. break;
  47248. case FOURCC_DXT3:
  47249. blockBytes = 16;
  47250. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47251. break;
  47252. case FOURCC_DXT5:
  47253. blockBytes = 16;
  47254. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47255. break;
  47256. default:
  47257. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  47258. return;
  47259. }
  47260. }
  47261. mipmapCount = 1;
  47262. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  47263. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47264. }
  47265. var bpp = header[off_RGBbpp];
  47266. for (var face = 0; face < faces; face++) {
  47267. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  47268. width = header[off_width];
  47269. height = header[off_height];
  47270. dataOffset = header[off_size] + 4;
  47271. for (i = 0; i < mipmapCount; ++i) {
  47272. if (info.isRGB) {
  47273. if (bpp === 24) {
  47274. dataLength = width * height * 3;
  47275. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47276. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  47277. }
  47278. else {
  47279. dataLength = width * height * 4;
  47280. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47281. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  47282. }
  47283. }
  47284. else if (info.isLuminance) {
  47285. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  47286. var unpaddedRowSize = width;
  47287. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  47288. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  47289. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47290. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  47291. }
  47292. else {
  47293. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  47294. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  47295. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  47296. }
  47297. dataOffset += dataLength;
  47298. width *= 0.5;
  47299. height *= 0.5;
  47300. width = Math.max(1.0, width);
  47301. height = Math.max(1.0, height);
  47302. }
  47303. }
  47304. };
  47305. return DDSTools;
  47306. })();
  47307. Internals.DDSTools = DDSTools;
  47308. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47309. })(BABYLON || (BABYLON = {}));
  47310. var BABYLON;
  47311. (function (BABYLON) {
  47312. var CannonJSPlugin = (function () {
  47313. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  47314. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  47315. if (iterations === void 0) { iterations = 10; }
  47316. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  47317. this.name = "CannonJSPlugin";
  47318. this._physicsMaterials = [];
  47319. this._fixedTimeStep = 1 / 60;
  47320. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47321. this._currentCollisionGroup = 2;
  47322. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  47323. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  47324. this._tmpPosition = BABYLON.Vector3.Zero();
  47325. this._tmpQuaternion = new BABYLON.Quaternion();
  47326. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  47327. this._tmpDeltaRotation = new BABYLON.Quaternion();
  47328. this._tmpUnityRotation = new BABYLON.Quaternion();
  47329. if (!this.isSupported()) {
  47330. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  47331. return;
  47332. }
  47333. this.world = new CANNON.World();
  47334. this.world.broadphase = new CANNON.NaiveBroadphase();
  47335. this.world.solver.iterations = iterations;
  47336. }
  47337. CannonJSPlugin.prototype.setGravity = function (gravity) {
  47338. this.world.gravity.copy(gravity);
  47339. };
  47340. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  47341. this._fixedTimeStep = timeStep;
  47342. };
  47343. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  47344. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  47345. };
  47346. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47347. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47348. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47349. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47350. };
  47351. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47352. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47353. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47354. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47355. };
  47356. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47357. //parent-child relationship. Does this impostor has a parent impostor?
  47358. if (impostor.parent) {
  47359. if (impostor.physicsBody) {
  47360. this.removePhysicsBody(impostor);
  47361. //TODO is that needed?
  47362. impostor.forceUpdate();
  47363. }
  47364. return;
  47365. }
  47366. //should a new body be created for this impostor?
  47367. if (impostor.isBodyInitRequired()) {
  47368. var shape = this._createShape(impostor);
  47369. //unregister events, if body is being changed
  47370. var oldBody = impostor.physicsBody;
  47371. if (oldBody) {
  47372. this.removePhysicsBody(impostor);
  47373. }
  47374. //create the body and material
  47375. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  47376. var bodyCreationObject = {
  47377. mass: impostor.getParam("mass"),
  47378. material: material
  47379. };
  47380. // A simple extend, in case native options were used.
  47381. var nativeOptions = impostor.getParam("nativeOptions");
  47382. for (var key in nativeOptions) {
  47383. if (nativeOptions.hasOwnProperty(key)) {
  47384. bodyCreationObject[key] = nativeOptions[key];
  47385. }
  47386. }
  47387. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  47388. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  47389. this.world.addEventListener("preStep", impostor.beforeStep);
  47390. this.world.addEventListener("postStep", impostor.afterStep);
  47391. impostor.physicsBody.addShape(shape);
  47392. this.world.add(impostor.physicsBody);
  47393. //try to keep the body moving in the right direction by taking old properties.
  47394. //Should be tested!
  47395. if (oldBody) {
  47396. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  47397. impostor.physicsBody[param].copy(oldBody[param]);
  47398. });
  47399. }
  47400. this._processChildMeshes(impostor);
  47401. }
  47402. //now update the body's transformation
  47403. this._updatePhysicsBodyTransformation(impostor);
  47404. };
  47405. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47406. var _this = this;
  47407. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47408. if (meshChildren.length) {
  47409. var processMesh = function (localPosition, mesh) {
  47410. var childImpostor = mesh.getPhysicsImpostor();
  47411. if (childImpostor) {
  47412. var parent = childImpostor.parent;
  47413. if (parent !== mainImpostor) {
  47414. var localPosition = mesh.position;
  47415. if (childImpostor.physicsBody) {
  47416. _this.removePhysicsBody(childImpostor);
  47417. childImpostor.physicsBody = null;
  47418. }
  47419. childImpostor.parent = mainImpostor;
  47420. childImpostor.resetUpdateFlags();
  47421. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47422. //Add the mass of the children.
  47423. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47424. }
  47425. }
  47426. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47427. };
  47428. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47429. }
  47430. };
  47431. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47432. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47433. this.world.removeEventListener("preStep", impostor.beforeStep);
  47434. this.world.removeEventListener("postStep", impostor.afterStep);
  47435. this.world.remove(impostor.physicsBody);
  47436. };
  47437. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47438. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47439. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47440. if (!mainBody || !connectedBody) {
  47441. return;
  47442. }
  47443. var constraint;
  47444. var jointData = impostorJoint.joint.jointData;
  47445. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47446. var constraintData = {
  47447. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47448. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47449. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47450. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47451. maxForce: jointData.nativeParams.maxForce,
  47452. collideConnected: !!jointData.collision
  47453. };
  47454. //Not needed, Cannon has a collideConnected flag
  47455. /*if (!jointData.collision) {
  47456. //add 1st body to a collision group of its own, if it is not in 1
  47457. if (mainBody.collisionFilterGroup === 1) {
  47458. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  47459. this._currentCollisionGroup <<= 1;
  47460. }
  47461. if (connectedBody.collisionFilterGroup === 1) {
  47462. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  47463. this._currentCollisionGroup <<= 1;
  47464. }
  47465. //add their mask to the collisionFilterMask of each other:
  47466. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  47467. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  47468. }*/
  47469. switch (impostorJoint.joint.type) {
  47470. case BABYLON.PhysicsJoint.HingeJoint:
  47471. case BABYLON.PhysicsJoint.Hinge2Joint:
  47472. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47473. break;
  47474. case BABYLON.PhysicsJoint.DistanceJoint:
  47475. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47476. break;
  47477. case BABYLON.PhysicsJoint.SpringJoint:
  47478. var springData = jointData;
  47479. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47480. restLength: springData.length,
  47481. stiffness: springData.stiffness,
  47482. damping: springData.damping,
  47483. localAnchorA: constraintData.pivotA,
  47484. localAnchorB: constraintData.pivotB
  47485. });
  47486. break;
  47487. case BABYLON.PhysicsJoint.LockJoint:
  47488. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47489. break;
  47490. case BABYLON.PhysicsJoint.PointToPointJoint:
  47491. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47492. default:
  47493. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47494. break;
  47495. }
  47496. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47497. constraint.collideConnected = !!jointData.collision;
  47498. impostorJoint.joint.physicsJoint = constraint;
  47499. //don't add spring as constraint, as it is not one.
  47500. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47501. this.world.addConstraint(constraint);
  47502. }
  47503. else {
  47504. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47505. constraint.applyForce();
  47506. });
  47507. }
  47508. };
  47509. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47510. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47511. };
  47512. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47513. var index;
  47514. var mat;
  47515. for (index = 0; index < this._physicsMaterials.length; index++) {
  47516. mat = this._physicsMaterials[index];
  47517. if (mat.friction === friction && mat.restitution === restitution) {
  47518. return mat;
  47519. }
  47520. }
  47521. var currentMat = new CANNON.Material(name);
  47522. currentMat.friction = friction;
  47523. currentMat.restitution = restitution;
  47524. this._physicsMaterials.push(currentMat);
  47525. return currentMat;
  47526. };
  47527. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47528. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47529. };
  47530. CannonJSPlugin.prototype._createShape = function (impostor) {
  47531. var object = impostor.object;
  47532. var returnValue;
  47533. var extendSize = impostor.getObjectExtendSize();
  47534. switch (impostor.type) {
  47535. case BABYLON.PhysicsEngine.SphereImpostor:
  47536. var radiusX = extendSize.x;
  47537. var radiusY = extendSize.y;
  47538. var radiusZ = extendSize.z;
  47539. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47540. break;
  47541. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47542. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47543. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47544. break;
  47545. case BABYLON.PhysicsImpostor.BoxImpostor:
  47546. var box = extendSize.scale(0.5);
  47547. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47548. break;
  47549. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47550. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47551. returnValue = new CANNON.Plane();
  47552. break;
  47553. case BABYLON.PhysicsImpostor.MeshImpostor:
  47554. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47555. var rawFaces = object.getIndices ? object.getIndices() : [];
  47556. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47557. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47558. break;
  47559. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47560. returnValue = this._createHeightmap(object);
  47561. break;
  47562. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47563. returnValue = new CANNON.Particle();
  47564. break;
  47565. }
  47566. return returnValue;
  47567. };
  47568. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47569. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47570. var matrix = [];
  47571. //For now pointDepth will not be used and will be automatically calculated.
  47572. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47573. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47574. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47575. var elementSize = dim * 2 / arraySize;
  47576. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47577. for (var i = 0; i < pos.length; i = i + 3) {
  47578. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47579. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47580. var y = pos[i + 1] + minY;
  47581. if (!matrix[x]) {
  47582. matrix[x] = [];
  47583. }
  47584. if (!matrix[x][z]) {
  47585. matrix[x][z] = y;
  47586. }
  47587. matrix[x][z] = Math.max(y, matrix[x][z]);
  47588. }
  47589. for (var x = 0; x <= arraySize; ++x) {
  47590. if (!matrix[x]) {
  47591. var loc = 1;
  47592. while (!matrix[(x + loc) % arraySize]) {
  47593. loc++;
  47594. }
  47595. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47596. }
  47597. for (var z = 0; z <= arraySize; ++z) {
  47598. if (!matrix[x][z]) {
  47599. var loc = 1;
  47600. var newValue;
  47601. while (newValue === undefined) {
  47602. newValue = matrix[x][(z + loc++) % arraySize];
  47603. }
  47604. matrix[x][z] = newValue;
  47605. }
  47606. }
  47607. }
  47608. var shape = new CANNON.Heightfield(matrix, {
  47609. elementSize: elementSize
  47610. });
  47611. //For future reference, needed for body transformation
  47612. shape.minY = minY;
  47613. return shape;
  47614. };
  47615. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47616. var object = impostor.object;
  47617. //make sure it is updated...
  47618. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47619. // The delta between the mesh position and the mesh bounding box center
  47620. var center = impostor.getObjectCenter();
  47621. var extendSize = impostor.getObjectExtendSize();
  47622. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47623. this._tmpPosition.copyFrom(center);
  47624. var quaternion = object.rotationQuaternion;
  47625. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47626. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47627. //-90 DEG in X, precalculated
  47628. quaternion = quaternion.multiply(this._minus90X);
  47629. //Invert! (Precalculated, 90 deg in X)
  47630. //No need to clone. this will never change.
  47631. impostor.setDeltaRotation(this._plus90X);
  47632. }
  47633. //If it is a heightfield, if should be centered.
  47634. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  47635. var mesh = object;
  47636. //calculate the correct body position:
  47637. var rotationQuaternion = mesh.rotationQuaternion;
  47638. mesh.rotationQuaternion = this._tmpUnityRotation;
  47639. mesh.computeWorldMatrix(true);
  47640. //get original center with no rotation
  47641. var c = center.clone();
  47642. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47643. //rotation is back
  47644. mesh.rotationQuaternion = rotationQuaternion;
  47645. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47646. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47647. mesh.setPivotMatrix(p);
  47648. mesh.computeWorldMatrix(true);
  47649. //calculate the translation
  47650. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47651. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47652. //add it inverted to the delta
  47653. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47654. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47655. mesh.setPivotMatrix(oldPivot);
  47656. mesh.computeWorldMatrix(true);
  47657. }
  47658. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  47659. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47660. this._tmpPosition.copyFrom(object.position);
  47661. }
  47662. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47663. //Now update the impostor object
  47664. impostor.physicsBody.position.copy(this._tmpPosition);
  47665. impostor.physicsBody.quaternion.copy(quaternion);
  47666. };
  47667. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47668. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47669. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47670. };
  47671. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47672. impostor.physicsBody.position.copy(newPosition);
  47673. impostor.physicsBody.quaternion.copy(newRotation);
  47674. };
  47675. CannonJSPlugin.prototype.isSupported = function () {
  47676. return window.CANNON !== undefined;
  47677. };
  47678. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47679. impostor.physicsBody.velocity.copy(velocity);
  47680. };
  47681. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47682. impostor.physicsBody.angularVelocity.copy(velocity);
  47683. };
  47684. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47685. var v = impostor.physicsBody.velocity;
  47686. if (!v)
  47687. return null;
  47688. return new BABYLON.Vector3(v.x, v.y, v.z);
  47689. };
  47690. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47691. var v = impostor.physicsBody.angularVelocity;
  47692. if (!v)
  47693. return null;
  47694. return new BABYLON.Vector3(v.x, v.y, v.z);
  47695. };
  47696. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47697. impostor.physicsBody.mass = mass;
  47698. impostor.physicsBody.updateMassProperties();
  47699. };
  47700. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47701. impostor.physicsBody.sleep();
  47702. };
  47703. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47704. impostor.physicsBody.wakeUp();
  47705. };
  47706. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47707. joint.physicsJoint.distance = maxDistance;
  47708. };
  47709. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47710. if (!motorIndex) {
  47711. joint.physicsJoint.enableMotor();
  47712. }
  47713. };
  47714. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47715. if (!motorIndex) {
  47716. joint.physicsJoint.disableMotor();
  47717. }
  47718. };
  47719. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47720. if (!motorIndex) {
  47721. joint.physicsJoint.enableMotor();
  47722. joint.physicsJoint.setMotorSpeed(speed);
  47723. if (maxForce) {
  47724. this.setLimit(joint, maxForce);
  47725. }
  47726. }
  47727. };
  47728. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47729. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47730. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47731. };
  47732. CannonJSPlugin.prototype.dispose = function () {
  47733. //nothing to do, actually.
  47734. };
  47735. return CannonJSPlugin;
  47736. })();
  47737. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47738. })(BABYLON || (BABYLON = {}));
  47739. var BABYLON;
  47740. (function (BABYLON) {
  47741. var OimoJSPlugin = (function () {
  47742. function OimoJSPlugin(iterations) {
  47743. this.name = "OimoJSPlugin";
  47744. this._tmpImpostorsArray = [];
  47745. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47746. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47747. this.world.clear();
  47748. //making sure no stats are calculated
  47749. this.world.isNoStat = true;
  47750. }
  47751. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47752. this.world.gravity.copy(gravity);
  47753. };
  47754. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47755. this.world.timeStep = timeStep;
  47756. };
  47757. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47758. var _this = this;
  47759. impostors.forEach(function (impostor) {
  47760. impostor.beforeStep();
  47761. });
  47762. this.world.step();
  47763. impostors.forEach(function (impostor) {
  47764. impostor.afterStep();
  47765. //update the ordered impostors array
  47766. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47767. });
  47768. //check for collisions
  47769. var contact = this.world.contacts;
  47770. while (contact !== null) {
  47771. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47772. contact = contact.next;
  47773. continue;
  47774. }
  47775. //is this body colliding with any other? get the impostor
  47776. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47777. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47778. if (!mainImpostor || !collidingImpostor) {
  47779. contact = contact.next;
  47780. continue;
  47781. }
  47782. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47783. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47784. contact = contact.next;
  47785. }
  47786. };
  47787. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47788. var mass = impostor.physicsBody.massInfo.mass;
  47789. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  47790. };
  47791. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47792. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  47793. this.applyImpulse(impostor, force, contactPoint);
  47794. };
  47795. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47796. var _this = this;
  47797. //parent-child relationship. Does this impostor has a parent impostor?
  47798. if (impostor.parent) {
  47799. if (impostor.physicsBody) {
  47800. this.removePhysicsBody(impostor);
  47801. //TODO is that needed?
  47802. impostor.forceUpdate();
  47803. }
  47804. return;
  47805. }
  47806. if (impostor.isBodyInitRequired()) {
  47807. var bodyConfig = {
  47808. name: impostor.uniqueId,
  47809. //Oimo must have mass, also for static objects.
  47810. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  47811. size: [],
  47812. type: [],
  47813. pos: [],
  47814. rot: [],
  47815. move: impostor.getParam("mass") !== 0,
  47816. //Supporting older versions of Oimo
  47817. world: this.world
  47818. };
  47819. var impostors = [impostor];
  47820. function addToArray(parent) {
  47821. if (!parent.getChildMeshes)
  47822. return;
  47823. parent.getChildMeshes().forEach(function (m) {
  47824. if (m.physicsImpostor) {
  47825. impostors.push(m.physicsImpostor);
  47826. m.physicsImpostor._init();
  47827. }
  47828. });
  47829. }
  47830. addToArray(impostor.object);
  47831. function checkWithEpsilon(value) {
  47832. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  47833. }
  47834. impostors.forEach(function (i) {
  47835. //get the correct bounding box
  47836. var oldQuaternion = i.object.rotationQuaternion;
  47837. var rot = new OIMO.Euler().setFromQuaternion({
  47838. x: impostor.object.rotationQuaternion.x,
  47839. y: impostor.object.rotationQuaternion.y,
  47840. z: impostor.object.rotationQuaternion.z,
  47841. s: impostor.object.rotationQuaternion.w
  47842. });
  47843. var extendSize = i.getObjectExtendSize();
  47844. if (i === impostor) {
  47845. var center = impostor.getObjectCenter();
  47846. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  47847. //Can also use Array.prototype.push.apply
  47848. bodyConfig.pos.push(center.x);
  47849. bodyConfig.pos.push(center.y);
  47850. bodyConfig.pos.push(center.z);
  47851. //tmp solution
  47852. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  47853. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  47854. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  47855. }
  47856. else {
  47857. bodyConfig.pos.push(i.object.position.x);
  47858. bodyConfig.pos.push(i.object.position.y);
  47859. bodyConfig.pos.push(i.object.position.z);
  47860. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  47861. bodyConfig.rot.push(0);
  47862. bodyConfig.rot.push(0);
  47863. bodyConfig.rot.push(0);
  47864. }
  47865. // register mesh
  47866. switch (i.type) {
  47867. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47868. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  47869. case BABYLON.PhysicsImpostor.SphereImpostor:
  47870. var radiusX = extendSize.x;
  47871. var radiusY = extendSize.y;
  47872. var radiusZ = extendSize.z;
  47873. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  47874. bodyConfig.type.push('sphere');
  47875. //due to the way oimo works with compounds, add 3 times
  47876. bodyConfig.size.push(size);
  47877. bodyConfig.size.push(size);
  47878. bodyConfig.size.push(size);
  47879. break;
  47880. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47881. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  47882. var sizeY = checkWithEpsilon(extendSize.y);
  47883. bodyConfig.type.push('cylinder');
  47884. bodyConfig.size.push(sizeX);
  47885. bodyConfig.size.push(sizeY);
  47886. //due to the way oimo works with compounds, add one more value.
  47887. bodyConfig.size.push(sizeY);
  47888. break;
  47889. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47890. case BABYLON.PhysicsImpostor.BoxImpostor:
  47891. default:
  47892. var sizeX = checkWithEpsilon(extendSize.x);
  47893. var sizeY = checkWithEpsilon(extendSize.y);
  47894. var sizeZ = checkWithEpsilon(extendSize.z);
  47895. bodyConfig.type.push('box');
  47896. bodyConfig.size.push(sizeX);
  47897. bodyConfig.size.push(sizeY);
  47898. bodyConfig.size.push(sizeZ);
  47899. break;
  47900. }
  47901. //actually not needed, but hey...
  47902. i.object.rotationQuaternion = oldQuaternion;
  47903. });
  47904. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  47905. }
  47906. else {
  47907. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  47908. }
  47909. impostor.setDeltaPosition(this._tmpPositionVector);
  47910. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  47911. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  47912. };
  47913. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47914. //impostor.physicsBody.dispose();
  47915. //Same as : (older oimo versions)
  47916. this.world.removeRigidBody(impostor.physicsBody);
  47917. };
  47918. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47919. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47920. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47921. if (!mainBody || !connectedBody) {
  47922. return;
  47923. }
  47924. var jointData = impostorJoint.joint.jointData;
  47925. var options = jointData.nativeParams || {};
  47926. var type;
  47927. var nativeJointData = {
  47928. body1: mainBody,
  47929. body2: connectedBody,
  47930. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  47931. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  47932. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  47933. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  47934. min: options.min,
  47935. max: options.max,
  47936. collision: options.collision || jointData.collision,
  47937. spring: options.spring,
  47938. //supporting older version of Oimo
  47939. world: this.world
  47940. };
  47941. switch (impostorJoint.joint.type) {
  47942. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47943. type = "jointBall";
  47944. break;
  47945. case BABYLON.PhysicsJoint.SpringJoint:
  47946. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  47947. var springData = jointData;
  47948. nativeJointData.min = springData.length || nativeJointData.min;
  47949. //Max should also be set, just make sure it is at least min
  47950. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  47951. case BABYLON.PhysicsJoint.DistanceJoint:
  47952. type = "jointDistance";
  47953. nativeJointData.max = jointData.maxDistance;
  47954. break;
  47955. case BABYLON.PhysicsJoint.PrismaticJoint:
  47956. type = "jointPrisme";
  47957. break;
  47958. case BABYLON.PhysicsJoint.SliderJoint:
  47959. type = "jointSlide";
  47960. break;
  47961. case BABYLON.PhysicsJoint.WheelJoint:
  47962. type = "jointWheel";
  47963. break;
  47964. case BABYLON.PhysicsJoint.HingeJoint:
  47965. default:
  47966. type = "jointHinge";
  47967. break;
  47968. }
  47969. nativeJointData.type = type;
  47970. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  47971. };
  47972. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47973. //Bug in Oimo prevents us from disposing a joint in the playground
  47974. //joint.joint.physicsJoint.dispose();
  47975. //So we will bruteforce it!
  47976. try {
  47977. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  47978. }
  47979. catch (e) {
  47980. BABYLON.Tools.Warn(e);
  47981. }
  47982. };
  47983. OimoJSPlugin.prototype.isSupported = function () {
  47984. return OIMO !== undefined;
  47985. };
  47986. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47987. if (!impostor.physicsBody.sleeping) {
  47988. //TODO check that
  47989. if (impostor.physicsBody.shapes.next) {
  47990. var parentShape = this._getLastShape(impostor.physicsBody);
  47991. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  47992. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  47993. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  47994. }
  47995. else {
  47996. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  47997. }
  47998. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  47999. impostor.object.rotationQuaternion.normalize();
  48000. }
  48001. };
  48002. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48003. var body = impostor.physicsBody;
  48004. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  48005. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  48006. body.syncShapes();
  48007. body.awake();
  48008. };
  48009. OimoJSPlugin.prototype._getLastShape = function (body) {
  48010. var lastShape = body.shapes;
  48011. while (lastShape.next) {
  48012. lastShape = lastShape.next;
  48013. }
  48014. return lastShape;
  48015. };
  48016. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48017. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  48018. };
  48019. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48020. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  48021. };
  48022. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48023. var v = impostor.physicsBody.linearVelocity;
  48024. if (!v)
  48025. return null;
  48026. return new BABYLON.Vector3(v.x, v.y, v.z);
  48027. };
  48028. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48029. var v = impostor.physicsBody.angularVelocity;
  48030. if (!v)
  48031. return null;
  48032. return new BABYLON.Vector3(v.x, v.y, v.z);
  48033. };
  48034. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48035. var staticBody = mass === 0;
  48036. //this will actually set the body's density and not its mass.
  48037. //But this is how oimo treats the mass variable.
  48038. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  48039. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  48040. };
  48041. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  48042. impostor.physicsBody.sleep();
  48043. };
  48044. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  48045. impostor.physicsBody.awake();
  48046. };
  48047. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48048. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  48049. if (minDistance !== void 0) {
  48050. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  48051. }
  48052. };
  48053. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48054. //TODO separate rotational and transational motors.
  48055. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48056. if (motor) {
  48057. motor.setMotor(speed, maxForce);
  48058. }
  48059. };
  48060. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  48061. //TODO separate rotational and transational motors.
  48062. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48063. if (motor) {
  48064. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  48065. }
  48066. };
  48067. OimoJSPlugin.prototype.dispose = function () {
  48068. this.world.clear();
  48069. };
  48070. return OimoJSPlugin;
  48071. })();
  48072. BABYLON.OimoJSPlugin = OimoJSPlugin;
  48073. })(BABYLON || (BABYLON = {}));
  48074. var BABYLON;
  48075. (function (BABYLON) {
  48076. var DisplayPassPostProcess = (function (_super) {
  48077. __extends(DisplayPassPostProcess, _super);
  48078. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48079. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  48080. }
  48081. return DisplayPassPostProcess;
  48082. })(BABYLON.PostProcess);
  48083. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48084. })(BABYLON || (BABYLON = {}));
  48085. var BABYLON;
  48086. (function (BABYLON) {
  48087. var SimplificationSettings = (function () {
  48088. function SimplificationSettings(quality, distance, optimizeMesh) {
  48089. this.quality = quality;
  48090. this.distance = distance;
  48091. this.optimizeMesh = optimizeMesh;
  48092. }
  48093. return SimplificationSettings;
  48094. })();
  48095. BABYLON.SimplificationSettings = SimplificationSettings;
  48096. var SimplificationQueue = (function () {
  48097. function SimplificationQueue() {
  48098. this.running = false;
  48099. this._simplificationArray = [];
  48100. }
  48101. SimplificationQueue.prototype.addTask = function (task) {
  48102. this._simplificationArray.push(task);
  48103. };
  48104. SimplificationQueue.prototype.executeNext = function () {
  48105. var task = this._simplificationArray.pop();
  48106. if (task) {
  48107. this.running = true;
  48108. this.runSimplification(task);
  48109. }
  48110. else {
  48111. this.running = false;
  48112. }
  48113. };
  48114. SimplificationQueue.prototype.runSimplification = function (task) {
  48115. var _this = this;
  48116. if (task.parallelProcessing) {
  48117. //parallel simplifier
  48118. task.settings.forEach(function (setting) {
  48119. var simplifier = _this.getSimplifier(task);
  48120. simplifier.simplify(setting, function (newMesh) {
  48121. task.mesh.addLODLevel(setting.distance, newMesh);
  48122. newMesh.isVisible = true;
  48123. //check if it is the last
  48124. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  48125. //all done, run the success callback.
  48126. task.successCallback();
  48127. }
  48128. _this.executeNext();
  48129. });
  48130. });
  48131. }
  48132. else {
  48133. //single simplifier.
  48134. var simplifier = this.getSimplifier(task);
  48135. var runDecimation = function (setting, callback) {
  48136. simplifier.simplify(setting, function (newMesh) {
  48137. task.mesh.addLODLevel(setting.distance, newMesh);
  48138. newMesh.isVisible = true;
  48139. //run the next quality level
  48140. callback();
  48141. });
  48142. };
  48143. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  48144. runDecimation(task.settings[loop.index], function () {
  48145. loop.executeNext();
  48146. });
  48147. }, function () {
  48148. //execution ended, run the success callback.
  48149. if (task.successCallback) {
  48150. task.successCallback();
  48151. }
  48152. _this.executeNext();
  48153. });
  48154. }
  48155. };
  48156. SimplificationQueue.prototype.getSimplifier = function (task) {
  48157. switch (task.simplificationType) {
  48158. case SimplificationType.QUADRATIC:
  48159. default:
  48160. return new QuadraticErrorSimplification(task.mesh);
  48161. }
  48162. };
  48163. return SimplificationQueue;
  48164. })();
  48165. BABYLON.SimplificationQueue = SimplificationQueue;
  48166. /**
  48167. * The implemented types of simplification.
  48168. * At the moment only Quadratic Error Decimation is implemented.
  48169. */
  48170. (function (SimplificationType) {
  48171. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  48172. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  48173. var SimplificationType = BABYLON.SimplificationType;
  48174. var DecimationTriangle = (function () {
  48175. function DecimationTriangle(vertices) {
  48176. this.vertices = vertices;
  48177. this.error = new Array(4);
  48178. this.deleted = false;
  48179. this.isDirty = false;
  48180. this.deletePending = false;
  48181. this.borderFactor = 0;
  48182. }
  48183. return DecimationTriangle;
  48184. })();
  48185. BABYLON.DecimationTriangle = DecimationTriangle;
  48186. var DecimationVertex = (function () {
  48187. function DecimationVertex(position, id) {
  48188. this.position = position;
  48189. this.id = id;
  48190. this.isBorder = true;
  48191. this.q = new QuadraticMatrix();
  48192. this.triangleCount = 0;
  48193. this.triangleStart = 0;
  48194. this.originalOffsets = [];
  48195. }
  48196. DecimationVertex.prototype.updatePosition = function (newPosition) {
  48197. this.position.copyFrom(newPosition);
  48198. };
  48199. return DecimationVertex;
  48200. })();
  48201. BABYLON.DecimationVertex = DecimationVertex;
  48202. var QuadraticMatrix = (function () {
  48203. function QuadraticMatrix(data) {
  48204. this.data = new Array(10);
  48205. for (var i = 0; i < 10; ++i) {
  48206. if (data && data[i]) {
  48207. this.data[i] = data[i];
  48208. }
  48209. else {
  48210. this.data[i] = 0;
  48211. }
  48212. }
  48213. }
  48214. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  48215. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  48216. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  48217. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  48218. return det;
  48219. };
  48220. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  48221. for (var i = 0; i < 10; ++i) {
  48222. this.data[i] += matrix.data[i];
  48223. }
  48224. };
  48225. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  48226. for (var i = 0; i < 10; ++i) {
  48227. this.data[i] += data[i];
  48228. }
  48229. };
  48230. QuadraticMatrix.prototype.add = function (matrix) {
  48231. var m = new QuadraticMatrix();
  48232. for (var i = 0; i < 10; ++i) {
  48233. m.data[i] = this.data[i] + matrix.data[i];
  48234. }
  48235. return m;
  48236. };
  48237. QuadraticMatrix.FromData = function (a, b, c, d) {
  48238. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  48239. };
  48240. //returning an array to avoid garbage collection
  48241. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  48242. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  48243. };
  48244. return QuadraticMatrix;
  48245. })();
  48246. BABYLON.QuadraticMatrix = QuadraticMatrix;
  48247. var Reference = (function () {
  48248. function Reference(vertexId, triangleId) {
  48249. this.vertexId = vertexId;
  48250. this.triangleId = triangleId;
  48251. }
  48252. return Reference;
  48253. })();
  48254. BABYLON.Reference = Reference;
  48255. /**
  48256. * An implementation of the Quadratic Error simplification algorithm.
  48257. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  48258. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  48259. * @author RaananW
  48260. */
  48261. var QuadraticErrorSimplification = (function () {
  48262. function QuadraticErrorSimplification(_mesh) {
  48263. this._mesh = _mesh;
  48264. this.initialized = false;
  48265. this.syncIterations = 5000;
  48266. this.aggressiveness = 7;
  48267. this.decimationIterations = 100;
  48268. this.boundingBoxEpsilon = BABYLON.Epsilon;
  48269. }
  48270. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  48271. var _this = this;
  48272. this.initDecimatedMesh();
  48273. //iterating through the submeshes array, one after the other.
  48274. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  48275. _this.initWithMesh(loop.index, function () {
  48276. _this.runDecimation(settings, loop.index, function () {
  48277. loop.executeNext();
  48278. });
  48279. }, settings.optimizeMesh);
  48280. }, function () {
  48281. setTimeout(function () {
  48282. successCallback(_this._reconstructedMesh);
  48283. }, 0);
  48284. });
  48285. };
  48286. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  48287. var _this = this;
  48288. var gCount = 0;
  48289. triangle.vertices.forEach(function (vertex) {
  48290. var count = 0;
  48291. var vPos = vertex.position;
  48292. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  48293. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  48294. ++count;
  48295. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  48296. ++count;
  48297. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  48298. ++count;
  48299. if (count > 1) {
  48300. ++gCount;
  48301. }
  48302. ;
  48303. });
  48304. if (gCount > 1) {
  48305. console.log(triangle, gCount);
  48306. }
  48307. return gCount > 1;
  48308. };
  48309. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  48310. var _this = this;
  48311. var targetCount = ~~(this.triangles.length * settings.quality);
  48312. var deletedTriangles = 0;
  48313. var triangleCount = this.triangles.length;
  48314. var iterationFunction = function (iteration, callback) {
  48315. setTimeout(function () {
  48316. if (iteration % 5 === 0) {
  48317. _this.updateMesh(iteration === 0);
  48318. }
  48319. for (var i = 0; i < _this.triangles.length; ++i) {
  48320. _this.triangles[i].isDirty = false;
  48321. }
  48322. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  48323. var trianglesIterator = function (i) {
  48324. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  48325. var t = _this.triangles[tIdx];
  48326. if (!t)
  48327. return;
  48328. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  48329. return;
  48330. }
  48331. for (var j = 0; j < 3; ++j) {
  48332. if (t.error[j] < threshold) {
  48333. var deleted0 = [];
  48334. var deleted1 = [];
  48335. var v0 = t.vertices[j];
  48336. var v1 = t.vertices[(j + 1) % 3];
  48337. if (v0.isBorder || v1.isBorder)
  48338. continue;
  48339. var p = BABYLON.Vector3.Zero();
  48340. var n = BABYLON.Vector3.Zero();
  48341. var uv = BABYLON.Vector2.Zero();
  48342. var color = new BABYLON.Color4(0, 0, 0, 1);
  48343. _this.calculateError(v0, v1, p, n, uv, color);
  48344. var delTr = [];
  48345. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  48346. continue;
  48347. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  48348. continue;
  48349. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  48350. continue;
  48351. var uniqueArray = [];
  48352. delTr.forEach(function (deletedT) {
  48353. if (uniqueArray.indexOf(deletedT) === -1) {
  48354. deletedT.deletePending = true;
  48355. uniqueArray.push(deletedT);
  48356. }
  48357. });
  48358. if (uniqueArray.length % 2 !== 0) {
  48359. continue;
  48360. }
  48361. v0.q = v1.q.add(v0.q);
  48362. v0.updatePosition(p);
  48363. var tStart = _this.references.length;
  48364. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  48365. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  48366. var tCount = _this.references.length - tStart;
  48367. if (tCount <= v0.triangleCount) {
  48368. if (tCount) {
  48369. for (var c = 0; c < tCount; c++) {
  48370. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  48371. }
  48372. }
  48373. }
  48374. else {
  48375. v0.triangleStart = tStart;
  48376. }
  48377. v0.triangleCount = tCount;
  48378. break;
  48379. }
  48380. }
  48381. };
  48382. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  48383. }, 0);
  48384. };
  48385. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  48386. if (triangleCount - deletedTriangles <= targetCount)
  48387. loop.breakLoop();
  48388. else {
  48389. iterationFunction(loop.index, function () {
  48390. loop.executeNext();
  48391. });
  48392. }
  48393. }, function () {
  48394. setTimeout(function () {
  48395. //reconstruct this part of the mesh
  48396. _this.reconstructMesh(submeshIndex);
  48397. successCallback();
  48398. }, 0);
  48399. });
  48400. };
  48401. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  48402. var _this = this;
  48403. this.vertices = [];
  48404. this.triangles = [];
  48405. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48406. var indices = this._mesh.getIndices();
  48407. var submesh = this._mesh.subMeshes[submeshIndex];
  48408. var findInVertices = function (positionToSearch) {
  48409. if (optimizeMesh) {
  48410. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48411. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48412. return _this.vertices[ii];
  48413. }
  48414. }
  48415. }
  48416. return null;
  48417. };
  48418. var vertexReferences = [];
  48419. var vertexInit = function (i) {
  48420. var offset = i + submesh.verticesStart;
  48421. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48422. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48423. vertex.originalOffsets.push(offset);
  48424. if (vertex.id === _this.vertices.length) {
  48425. _this.vertices.push(vertex);
  48426. }
  48427. vertexReferences.push(vertex.id);
  48428. };
  48429. //var totalVertices = mesh.getTotalVertices();
  48430. var totalVertices = submesh.verticesCount;
  48431. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48432. var indicesInit = function (i) {
  48433. var offset = (submesh.indexStart / 3) + i;
  48434. var pos = (offset * 3);
  48435. var i0 = indices[pos + 0];
  48436. var i1 = indices[pos + 1];
  48437. var i2 = indices[pos + 2];
  48438. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48439. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48440. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48441. var triangle = new DecimationTriangle([v0, v1, v2]);
  48442. triangle.originalOffset = pos;
  48443. _this.triangles.push(triangle);
  48444. };
  48445. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48446. _this.init(callback);
  48447. });
  48448. });
  48449. };
  48450. QuadraticErrorSimplification.prototype.init = function (callback) {
  48451. var _this = this;
  48452. var triangleInit1 = function (i) {
  48453. var t = _this.triangles[i];
  48454. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48455. for (var j = 0; j < 3; j++) {
  48456. 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))));
  48457. }
  48458. };
  48459. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48460. var triangleInit2 = function (i) {
  48461. var t = _this.triangles[i];
  48462. for (var j = 0; j < 3; ++j) {
  48463. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48464. }
  48465. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48466. };
  48467. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48468. _this.initialized = true;
  48469. callback();
  48470. });
  48471. });
  48472. };
  48473. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48474. var newTriangles = [];
  48475. var i;
  48476. for (i = 0; i < this.vertices.length; ++i) {
  48477. this.vertices[i].triangleCount = 0;
  48478. }
  48479. var t;
  48480. var j;
  48481. for (i = 0; i < this.triangles.length; ++i) {
  48482. if (!this.triangles[i].deleted) {
  48483. t = this.triangles[i];
  48484. for (j = 0; j < 3; ++j) {
  48485. t.vertices[j].triangleCount = 1;
  48486. }
  48487. newTriangles.push(t);
  48488. }
  48489. }
  48490. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48491. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48492. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48493. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48494. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48495. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48496. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48497. var vertexCount = 0;
  48498. for (i = 0; i < this.vertices.length; ++i) {
  48499. var vertex = this.vertices[i];
  48500. vertex.id = vertexCount;
  48501. if (vertex.triangleCount) {
  48502. vertex.originalOffsets.forEach(function (originalOffset) {
  48503. newPositionData.push(vertex.position.x);
  48504. newPositionData.push(vertex.position.y);
  48505. newPositionData.push(vertex.position.z);
  48506. newNormalData.push(normalData[originalOffset * 3]);
  48507. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48508. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48509. if (uvs && uvs.length) {
  48510. newUVsData.push(uvs[(originalOffset * 2)]);
  48511. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48512. }
  48513. else if (colorsData && colorsData.length) {
  48514. newColorsData.push(colorsData[(originalOffset * 4)]);
  48515. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48516. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48517. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48518. }
  48519. ++vertexCount;
  48520. });
  48521. }
  48522. }
  48523. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48524. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48525. var submeshesArray = this._reconstructedMesh.subMeshes;
  48526. this._reconstructedMesh.subMeshes = [];
  48527. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48528. var originalIndices = this._mesh.getIndices();
  48529. for (i = 0; i < newTriangles.length; ++i) {
  48530. t = newTriangles[i]; //now get the new referencing point for each vertex
  48531. [0, 1, 2].forEach(function (idx) {
  48532. var id = originalIndices[t.originalOffset + idx];
  48533. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48534. if (offset < 0)
  48535. offset = 0;
  48536. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48537. });
  48538. }
  48539. //overwriting the old vertex buffers and indices.
  48540. this._reconstructedMesh.setIndices(newIndicesArray);
  48541. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48542. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48543. if (newUVsData.length > 0)
  48544. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48545. if (newColorsData.length > 0)
  48546. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48547. //create submesh
  48548. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48549. if (submeshIndex > 0) {
  48550. this._reconstructedMesh.subMeshes = [];
  48551. submeshesArray.forEach(function (submesh) {
  48552. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48553. });
  48554. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48555. }
  48556. };
  48557. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48558. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48559. this._reconstructedMesh.material = this._mesh.material;
  48560. this._reconstructedMesh.parent = this._mesh.parent;
  48561. this._reconstructedMesh.isVisible = false;
  48562. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48563. };
  48564. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48565. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48566. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48567. if (t.deleted)
  48568. continue;
  48569. var s = this.references[vertex1.triangleStart + i].vertexId;
  48570. var v1 = t.vertices[(s + 1) % 3];
  48571. var v2 = t.vertices[(s + 2) % 3];
  48572. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48573. deletedArray[i] = true;
  48574. delTr.push(t);
  48575. continue;
  48576. }
  48577. var d1 = v1.position.subtract(point);
  48578. d1 = d1.normalize();
  48579. var d2 = v2.position.subtract(point);
  48580. d2 = d2.normalize();
  48581. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48582. return true;
  48583. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48584. deletedArray[i] = false;
  48585. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48586. return true;
  48587. }
  48588. return false;
  48589. };
  48590. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48591. var newDeleted = deletedTriangles;
  48592. for (var i = 0; i < vertex.triangleCount; ++i) {
  48593. var ref = this.references[vertex.triangleStart + i];
  48594. var t = this.triangles[ref.triangleId];
  48595. if (t.deleted)
  48596. continue;
  48597. if (deletedArray[i] && t.deletePending) {
  48598. t.deleted = true;
  48599. newDeleted++;
  48600. continue;
  48601. }
  48602. t.vertices[ref.vertexId] = origVertex;
  48603. t.isDirty = true;
  48604. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48605. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48606. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48607. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48608. this.references.push(ref);
  48609. }
  48610. return newDeleted;
  48611. };
  48612. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48613. for (var i = 0; i < this.vertices.length; ++i) {
  48614. var vCount = [];
  48615. var vId = [];
  48616. var v = this.vertices[i];
  48617. var j;
  48618. for (j = 0; j < v.triangleCount; ++j) {
  48619. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48620. for (var ii = 0; ii < 3; ii++) {
  48621. var ofs = 0;
  48622. var vv = triangle.vertices[ii];
  48623. while (ofs < vCount.length) {
  48624. if (vId[ofs] === vv.id)
  48625. break;
  48626. ++ofs;
  48627. }
  48628. if (ofs === vCount.length) {
  48629. vCount.push(1);
  48630. vId.push(vv.id);
  48631. }
  48632. else {
  48633. vCount[ofs]++;
  48634. }
  48635. }
  48636. }
  48637. for (j = 0; j < vCount.length; ++j) {
  48638. if (vCount[j] === 1) {
  48639. this.vertices[vId[j]].isBorder = true;
  48640. }
  48641. else {
  48642. this.vertices[vId[j]].isBorder = false;
  48643. }
  48644. }
  48645. }
  48646. };
  48647. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48648. if (identifyBorders === void 0) { identifyBorders = false; }
  48649. var i;
  48650. if (!identifyBorders) {
  48651. var newTrianglesVector = [];
  48652. for (i = 0; i < this.triangles.length; ++i) {
  48653. if (!this.triangles[i].deleted) {
  48654. newTrianglesVector.push(this.triangles[i]);
  48655. }
  48656. }
  48657. this.triangles = newTrianglesVector;
  48658. }
  48659. for (i = 0; i < this.vertices.length; ++i) {
  48660. this.vertices[i].triangleCount = 0;
  48661. this.vertices[i].triangleStart = 0;
  48662. }
  48663. var t;
  48664. var j;
  48665. var v;
  48666. for (i = 0; i < this.triangles.length; ++i) {
  48667. t = this.triangles[i];
  48668. for (j = 0; j < 3; ++j) {
  48669. v = t.vertices[j];
  48670. v.triangleCount++;
  48671. }
  48672. }
  48673. var tStart = 0;
  48674. for (i = 0; i < this.vertices.length; ++i) {
  48675. this.vertices[i].triangleStart = tStart;
  48676. tStart += this.vertices[i].triangleCount;
  48677. this.vertices[i].triangleCount = 0;
  48678. }
  48679. var newReferences = new Array(this.triangles.length * 3);
  48680. for (i = 0; i < this.triangles.length; ++i) {
  48681. t = this.triangles[i];
  48682. for (j = 0; j < 3; ++j) {
  48683. v = t.vertices[j];
  48684. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48685. v.triangleCount++;
  48686. }
  48687. }
  48688. this.references = newReferences;
  48689. if (identifyBorders) {
  48690. this.identifyBorder();
  48691. }
  48692. };
  48693. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48694. var x = point.x;
  48695. var y = point.y;
  48696. var z = point.z;
  48697. 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
  48698. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48699. };
  48700. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48701. var q = vertex1.q.add(vertex2.q);
  48702. var border = vertex1.isBorder && vertex2.isBorder;
  48703. var error = 0;
  48704. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48705. if (qDet !== 0 && !border) {
  48706. if (!pointResult) {
  48707. pointResult = BABYLON.Vector3.Zero();
  48708. }
  48709. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48710. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48711. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48712. error = this.vertexError(q, pointResult);
  48713. }
  48714. else {
  48715. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48716. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48717. var error1 = this.vertexError(q, vertex1.position);
  48718. var error2 = this.vertexError(q, vertex2.position);
  48719. var error3 = this.vertexError(q, p3);
  48720. error = Math.min(error1, error2, error3);
  48721. if (error === error1) {
  48722. if (pointResult) {
  48723. pointResult.copyFrom(vertex1.position);
  48724. }
  48725. }
  48726. else if (error === error2) {
  48727. if (pointResult) {
  48728. pointResult.copyFrom(vertex2.position);
  48729. }
  48730. }
  48731. else {
  48732. if (pointResult) {
  48733. pointResult.copyFrom(p3);
  48734. }
  48735. }
  48736. }
  48737. return error;
  48738. };
  48739. return QuadraticErrorSimplification;
  48740. })();
  48741. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48742. })(BABYLON || (BABYLON = {}));
  48743. var BABYLON;
  48744. (function (BABYLON) {
  48745. var serializedGeometries = [];
  48746. var serializeGeometry = function (geometry, serializationGeometries) {
  48747. if (serializedGeometries[geometry.id]) {
  48748. return;
  48749. }
  48750. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48751. serializationGeometries.boxes.push(geometry.serialize());
  48752. }
  48753. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48754. serializationGeometries.spheres.push(geometry.serialize());
  48755. }
  48756. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48757. serializationGeometries.cylinders.push(geometry.serialize());
  48758. }
  48759. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48760. serializationGeometries.toruses.push(geometry.serialize());
  48761. }
  48762. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48763. serializationGeometries.grounds.push(geometry.serialize());
  48764. }
  48765. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48766. serializationGeometries.planes.push(geometry.serialize());
  48767. }
  48768. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48769. serializationGeometries.torusKnots.push(geometry.serialize());
  48770. }
  48771. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48772. throw new Error("Unknown primitive type");
  48773. }
  48774. else {
  48775. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48776. }
  48777. serializedGeometries[geometry.id] = true;
  48778. };
  48779. var serializeMesh = function (mesh, serializationScene) {
  48780. var serializationObject = {};
  48781. serializationObject.name = mesh.name;
  48782. serializationObject.id = mesh.id;
  48783. if (BABYLON.Tags.HasTags(mesh)) {
  48784. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  48785. }
  48786. serializationObject.position = mesh.position.asArray();
  48787. if (mesh.rotationQuaternion) {
  48788. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  48789. }
  48790. else if (mesh.rotation) {
  48791. serializationObject.rotation = mesh.rotation.asArray();
  48792. }
  48793. serializationObject.scaling = mesh.scaling.asArray();
  48794. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  48795. serializationObject.isEnabled = mesh.isEnabled();
  48796. serializationObject.isVisible = mesh.isVisible;
  48797. serializationObject.infiniteDistance = mesh.infiniteDistance;
  48798. serializationObject.pickable = mesh.isPickable;
  48799. serializationObject.receiveShadows = mesh.receiveShadows;
  48800. serializationObject.billboardMode = mesh.billboardMode;
  48801. serializationObject.visibility = mesh.visibility;
  48802. serializationObject.checkCollisions = mesh.checkCollisions;
  48803. // Parent
  48804. if (mesh.parent) {
  48805. serializationObject.parentId = mesh.parent.id;
  48806. }
  48807. // Geometry
  48808. var geometry = mesh._geometry;
  48809. if (geometry) {
  48810. var geometryId = geometry.id;
  48811. serializationObject.geometryId = geometryId;
  48812. if (!mesh.getScene().getGeometryByID(geometryId)) {
  48813. // 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
  48814. serializeGeometry(geometry, serializationScene.geometries);
  48815. }
  48816. // SubMeshes
  48817. serializationObject.subMeshes = [];
  48818. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  48819. var subMesh = mesh.subMeshes[subIndex];
  48820. serializationObject.subMeshes.push({
  48821. materialIndex: subMesh.materialIndex,
  48822. verticesStart: subMesh.verticesStart,
  48823. verticesCount: subMesh.verticesCount,
  48824. indexStart: subMesh.indexStart,
  48825. indexCount: subMesh.indexCount
  48826. });
  48827. }
  48828. }
  48829. // Material
  48830. if (mesh.material) {
  48831. serializationObject.materialId = mesh.material.id;
  48832. }
  48833. else {
  48834. mesh.material = null;
  48835. }
  48836. // Skeleton
  48837. if (mesh.skeleton) {
  48838. serializationObject.skeletonId = mesh.skeleton.id;
  48839. }
  48840. // Physics
  48841. //TODO implement correct serialization for physics impostors.
  48842. if (mesh.getPhysicsImpostor()) {
  48843. serializationObject.physicsMass = mesh.getPhysicsMass();
  48844. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  48845. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  48846. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  48847. }
  48848. // Instances
  48849. serializationObject.instances = [];
  48850. for (var index = 0; index < mesh.instances.length; index++) {
  48851. var instance = mesh.instances[index];
  48852. var serializationInstance = {
  48853. name: instance.name,
  48854. position: instance.position.asArray(),
  48855. scaling: instance.scaling.asArray()
  48856. };
  48857. if (instance.rotationQuaternion) {
  48858. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  48859. }
  48860. else if (instance.rotation) {
  48861. serializationInstance.rotation = instance.rotation.asArray();
  48862. }
  48863. serializationObject.instances.push(serializationInstance);
  48864. // Animations
  48865. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  48866. serializationInstance.ranges = instance.serializeAnimationRanges();
  48867. }
  48868. // Animations
  48869. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  48870. serializationObject.ranges = mesh.serializeAnimationRanges();
  48871. // Layer mask
  48872. serializationObject.layerMask = mesh.layerMask;
  48873. // Action Manager
  48874. if (mesh.actionManager) {
  48875. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  48876. }
  48877. return serializationObject;
  48878. };
  48879. var finalizeSingleMesh = function (mesh, serializationObject) {
  48880. //only works if the mesh is already loaded
  48881. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48882. //serialize material
  48883. if (mesh.material) {
  48884. if (mesh.material instanceof BABYLON.StandardMaterial) {
  48885. serializationObject.materials = serializationObject.materials || [];
  48886. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48887. serializationObject.materials.push(mesh.material.serialize());
  48888. }
  48889. }
  48890. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  48891. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  48892. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48893. serializationObject.multiMaterials.push(mesh.material.serialize());
  48894. }
  48895. }
  48896. }
  48897. //serialize geometry
  48898. var geometry = mesh._geometry;
  48899. if (geometry) {
  48900. if (!serializationObject.geometries) {
  48901. serializationObject.geometries = {};
  48902. serializationObject.geometries.boxes = [];
  48903. serializationObject.geometries.spheres = [];
  48904. serializationObject.geometries.cylinders = [];
  48905. serializationObject.geometries.toruses = [];
  48906. serializationObject.geometries.grounds = [];
  48907. serializationObject.geometries.planes = [];
  48908. serializationObject.geometries.torusKnots = [];
  48909. serializationObject.geometries.vertexData = [];
  48910. }
  48911. serializeGeometry(geometry, serializationObject.geometries);
  48912. }
  48913. // Skeletons
  48914. if (mesh.skeleton) {
  48915. serializationObject.skeletons = serializationObject.skeletons || [];
  48916. serializationObject.skeletons.push(mesh.skeleton.serialize());
  48917. }
  48918. //serialize the actual mesh
  48919. serializationObject.meshes = serializationObject.meshes || [];
  48920. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48921. }
  48922. };
  48923. var SceneSerializer = (function () {
  48924. function SceneSerializer() {
  48925. }
  48926. SceneSerializer.ClearCache = function () {
  48927. serializedGeometries = [];
  48928. };
  48929. SceneSerializer.Serialize = function (scene) {
  48930. var serializationObject = {};
  48931. // Scene
  48932. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  48933. serializationObject.autoClear = scene.autoClear;
  48934. serializationObject.clearColor = scene.clearColor.asArray();
  48935. serializationObject.ambientColor = scene.ambientColor.asArray();
  48936. serializationObject.gravity = scene.gravity.asArray();
  48937. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  48938. serializationObject.workerCollisions = scene.workerCollisions;
  48939. // Fog
  48940. if (scene.fogMode && scene.fogMode !== 0) {
  48941. serializationObject.fogMode = scene.fogMode;
  48942. serializationObject.fogColor = scene.fogColor.asArray();
  48943. serializationObject.fogStart = scene.fogStart;
  48944. serializationObject.fogEnd = scene.fogEnd;
  48945. serializationObject.fogDensity = scene.fogDensity;
  48946. }
  48947. //Physics
  48948. if (scene.isPhysicsEnabled()) {
  48949. serializationObject.physicsEnabled = true;
  48950. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  48951. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  48952. }
  48953. // Lights
  48954. serializationObject.lights = [];
  48955. var index;
  48956. var light;
  48957. for (index = 0; index < scene.lights.length; index++) {
  48958. light = scene.lights[index];
  48959. serializationObject.lights.push(light.serialize());
  48960. }
  48961. // Cameras
  48962. serializationObject.cameras = [];
  48963. for (index = 0; index < scene.cameras.length; index++) {
  48964. var camera = scene.cameras[index];
  48965. serializationObject.cameras.push(camera.serialize());
  48966. }
  48967. if (scene.activeCamera) {
  48968. serializationObject.activeCameraID = scene.activeCamera.id;
  48969. }
  48970. // Animations
  48971. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  48972. // Materials
  48973. serializationObject.materials = [];
  48974. serializationObject.multiMaterials = [];
  48975. var material;
  48976. for (index = 0; index < scene.materials.length; index++) {
  48977. material = scene.materials[index];
  48978. serializationObject.materials.push(material.serialize());
  48979. }
  48980. // MultiMaterials
  48981. serializationObject.multiMaterials = [];
  48982. for (index = 0; index < scene.multiMaterials.length; index++) {
  48983. var multiMaterial = scene.multiMaterials[index];
  48984. serializationObject.multiMaterials.push(multiMaterial.serialize());
  48985. }
  48986. // Skeletons
  48987. serializationObject.skeletons = [];
  48988. for (index = 0; index < scene.skeletons.length; index++) {
  48989. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  48990. }
  48991. // Geometries
  48992. serializationObject.geometries = {};
  48993. serializationObject.geometries.boxes = [];
  48994. serializationObject.geometries.spheres = [];
  48995. serializationObject.geometries.cylinders = [];
  48996. serializationObject.geometries.toruses = [];
  48997. serializationObject.geometries.grounds = [];
  48998. serializationObject.geometries.planes = [];
  48999. serializationObject.geometries.torusKnots = [];
  49000. serializationObject.geometries.vertexData = [];
  49001. serializedGeometries = [];
  49002. var geometries = scene.getGeometries();
  49003. for (index = 0; index < geometries.length; index++) {
  49004. var geometry = geometries[index];
  49005. if (geometry.isReady()) {
  49006. serializeGeometry(geometry, serializationObject.geometries);
  49007. }
  49008. }
  49009. // Meshes
  49010. serializationObject.meshes = [];
  49011. for (index = 0; index < scene.meshes.length; index++) {
  49012. var abstractMesh = scene.meshes[index];
  49013. if (abstractMesh instanceof BABYLON.Mesh) {
  49014. var mesh = abstractMesh;
  49015. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49016. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49017. }
  49018. }
  49019. }
  49020. // Particles Systems
  49021. serializationObject.particleSystems = [];
  49022. for (index = 0; index < scene.particleSystems.length; index++) {
  49023. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  49024. }
  49025. // Lens flares
  49026. serializationObject.lensFlareSystems = [];
  49027. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  49028. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  49029. }
  49030. // Shadows
  49031. serializationObject.shadowGenerators = [];
  49032. for (index = 0; index < scene.lights.length; index++) {
  49033. light = scene.lights[index];
  49034. if (light.getShadowGenerator()) {
  49035. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  49036. }
  49037. }
  49038. // Action Manager
  49039. if (scene.actionManager) {
  49040. serializationObject.actions = scene.actionManager.serialize("scene");
  49041. }
  49042. // Audio
  49043. serializationObject.sounds = [];
  49044. for (index = 0; index < scene.soundTracks.length; index++) {
  49045. var soundtrack = scene.soundTracks[index];
  49046. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  49047. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  49048. }
  49049. }
  49050. return serializationObject;
  49051. };
  49052. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  49053. if (withParents === void 0) { withParents = false; }
  49054. if (withChildren === void 0) { withChildren = false; }
  49055. var serializationObject = {};
  49056. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  49057. if (withParents || withChildren) {
  49058. //deliberate for loop! not for each, appended should be processed as well.
  49059. for (var i = 0; i < toSerialize.length; ++i) {
  49060. if (withChildren) {
  49061. toSerialize[i].getDescendants().forEach(function (node) {
  49062. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  49063. toSerialize.push(node);
  49064. }
  49065. });
  49066. }
  49067. //make sure the array doesn't contain the object already
  49068. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  49069. toSerialize.push(toSerialize[i].parent);
  49070. }
  49071. }
  49072. }
  49073. toSerialize.forEach(function (mesh) {
  49074. finalizeSingleMesh(mesh, serializationObject);
  49075. });
  49076. return serializationObject;
  49077. };
  49078. return SceneSerializer;
  49079. })();
  49080. BABYLON.SceneSerializer = SceneSerializer;
  49081. })(BABYLON || (BABYLON = {}));
  49082. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  49083. // Huge respect for a such great lib.
  49084. // Earcut license:
  49085. // Copyright (c) 2016, Mapbox
  49086. //
  49087. // Permission to use, copy, modify, and/or distribute this software for any purpose
  49088. // with or without fee is hereby granted, provided that the above copyright notice
  49089. // and this permission notice appear in all copies.
  49090. //
  49091. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  49092. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49093. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  49094. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  49095. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  49096. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  49097. // THIS SOFTWARE.
  49098. var Earcut;
  49099. (function (Earcut) {
  49100. /**
  49101. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  49102. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  49103. * @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).
  49104. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  49105. */
  49106. function earcut(data, holeIndices, dim) {
  49107. dim = dim || 2;
  49108. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  49109. if (!outerNode)
  49110. return triangles;
  49111. var minX, minY, maxX, maxY, x, y, size;
  49112. if (hasHoles)
  49113. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  49114. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  49115. if (data.length > 80 * dim) {
  49116. minX = maxX = data[0];
  49117. minY = maxY = data[1];
  49118. for (var i = dim; i < outerLen; i += dim) {
  49119. x = data[i];
  49120. y = data[i + 1];
  49121. if (x < minX)
  49122. minX = x;
  49123. if (y < minY)
  49124. minY = y;
  49125. if (x > maxX)
  49126. maxX = x;
  49127. if (y > maxY)
  49128. maxY = y;
  49129. }
  49130. // minX, minY and size are later used to transform coords into integers for z-order calculation
  49131. size = Math.max(maxX - minX, maxY - minY);
  49132. }
  49133. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  49134. return triangles;
  49135. }
  49136. Earcut.earcut = earcut;
  49137. // create a circular doubly linked list from polygon points in the specified winding order
  49138. function linkedList(data, start, end, dim, clockwise) {
  49139. var i, last;
  49140. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  49141. for (i = start; i < end; i += dim)
  49142. last = insertNode(i, data[i], data[i + 1], last);
  49143. }
  49144. else {
  49145. for (i = end - dim; i >= start; i -= dim)
  49146. last = insertNode(i, data[i], data[i + 1], last);
  49147. }
  49148. if (last && equals(last, last.next)) {
  49149. removeNode(last);
  49150. last = last.next;
  49151. }
  49152. return last;
  49153. }
  49154. // eliminate colinear or duplicate points
  49155. function filterPoints(start, end) {
  49156. if (!start)
  49157. return start;
  49158. if (!end)
  49159. end = start;
  49160. var p = start, again;
  49161. do {
  49162. again = false;
  49163. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  49164. removeNode(p);
  49165. p = end = p.prev;
  49166. if (p === p.next)
  49167. return null;
  49168. again = true;
  49169. }
  49170. else {
  49171. p = p.next;
  49172. }
  49173. } while (again || p !== end);
  49174. return end;
  49175. }
  49176. // main ear slicing loop which triangulates a polygon (given as a linked list)
  49177. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  49178. if (!ear)
  49179. return;
  49180. // interlink polygon nodes in z-order
  49181. if (!pass && size)
  49182. indexCurve(ear, minX, minY, size);
  49183. var stop = ear, prev, next;
  49184. // iterate through ears, slicing them one by one
  49185. while (ear.prev !== ear.next) {
  49186. prev = ear.prev;
  49187. next = ear.next;
  49188. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  49189. // cut off the triangle
  49190. triangles.push(prev.i / dim);
  49191. triangles.push(ear.i / dim);
  49192. triangles.push(next.i / dim);
  49193. removeNode(ear);
  49194. // skipping the next vertice leads to less sliver triangles
  49195. ear = next.next;
  49196. stop = next.next;
  49197. continue;
  49198. }
  49199. ear = next;
  49200. // if we looped through the whole remaining polygon and can't find any more ears
  49201. if (ear === stop) {
  49202. // try filtering points and slicing again
  49203. if (!pass) {
  49204. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  49205. }
  49206. else if (pass === 1) {
  49207. ear = cureLocalIntersections(ear, triangles, dim);
  49208. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  49209. }
  49210. else if (pass === 2) {
  49211. splitEarcut(ear, triangles, dim, minX, minY, size);
  49212. }
  49213. break;
  49214. }
  49215. }
  49216. }
  49217. // check whether a polygon node forms a valid ear with adjacent nodes
  49218. function isEar(ear) {
  49219. var a = ear.prev, b = ear, c = ear.next;
  49220. if (area(a, b, c) >= 0)
  49221. return false; // reflex, can't be an ear
  49222. // now make sure we don't have other points inside the potential ear
  49223. var p = ear.next.next;
  49224. while (p !== ear.prev) {
  49225. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49226. area(p.prev, p, p.next) >= 0)
  49227. return false;
  49228. p = p.next;
  49229. }
  49230. return true;
  49231. }
  49232. function isEarHashed(ear, minX, minY, size) {
  49233. var a = ear.prev, b = ear, c = ear.next;
  49234. if (area(a, b, c) >= 0)
  49235. return false; // reflex, can't be an ear
  49236. // triangle bbox; min & max are calculated like this for speed
  49237. 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);
  49238. // z-order range for the current triangle bbox;
  49239. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  49240. // first look for points inside the triangle in increasing z-order
  49241. var p = ear.nextZ;
  49242. while (p && p.z <= maxZ) {
  49243. if (p !== ear.prev &&
  49244. p !== ear.next &&
  49245. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49246. area(p.prev, p, p.next) >= 0)
  49247. return false;
  49248. p = p.nextZ;
  49249. }
  49250. // then look for points in decreasing z-order
  49251. p = ear.prevZ;
  49252. while (p && p.z >= minZ) {
  49253. if (p !== ear.prev &&
  49254. p !== ear.next &&
  49255. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49256. area(p.prev, p, p.next) >= 0)
  49257. return false;
  49258. p = p.prevZ;
  49259. }
  49260. return true;
  49261. }
  49262. // go through all polygon nodes and cure small local self-intersections
  49263. function cureLocalIntersections(start, triangles, dim) {
  49264. var p = start;
  49265. do {
  49266. var a = p.prev, b = p.next.next;
  49267. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  49268. triangles.push(a.i / dim);
  49269. triangles.push(p.i / dim);
  49270. triangles.push(b.i / dim);
  49271. // remove two nodes involved
  49272. removeNode(p);
  49273. removeNode(p.next);
  49274. p = start = b;
  49275. }
  49276. p = p.next;
  49277. } while (p !== start);
  49278. return p;
  49279. }
  49280. // try splitting polygon into two and triangulate them independently
  49281. function splitEarcut(start, triangles, dim, minX, minY, size) {
  49282. // look for a valid diagonal that divides the polygon into two
  49283. var a = start;
  49284. do {
  49285. var b = a.next.next;
  49286. while (b !== a.prev) {
  49287. if (a.i !== b.i && isValidDiagonal(a, b)) {
  49288. // split the polygon in two by the diagonal
  49289. var c = splitPolygon(a, b);
  49290. // filter colinear points around the cuts
  49291. a = filterPoints(a, a.next);
  49292. c = filterPoints(c, c.next);
  49293. // run earcut on each half
  49294. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  49295. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  49296. return;
  49297. }
  49298. b = b.next;
  49299. }
  49300. a = a.next;
  49301. } while (a !== start);
  49302. }
  49303. // link every hole into the outer loop, producing a single-ring polygon without holes
  49304. function eliminateHoles(data, holeIndices, outerNode, dim) {
  49305. var queue = [], i, len, start, end, list;
  49306. for (i = 0, len = holeIndices.length; i < len; i++) {
  49307. start = holeIndices[i] * dim;
  49308. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49309. list = linkedList(data, start, end, dim, false);
  49310. if (list === list.next)
  49311. list.steiner = true;
  49312. queue.push(getLeftmost(list));
  49313. }
  49314. queue.sort(compareX);
  49315. // process holes from left to right
  49316. for (i = 0; i < queue.length; i++) {
  49317. eliminateHole(queue[i], outerNode);
  49318. outerNode = filterPoints(outerNode, outerNode.next);
  49319. }
  49320. return outerNode;
  49321. }
  49322. function compareX(a, b) {
  49323. return a.x - b.x;
  49324. }
  49325. // find a bridge between vertices that connects hole with an outer ring and and link it
  49326. function eliminateHole(hole, outerNode) {
  49327. outerNode = findHoleBridge(hole, outerNode);
  49328. if (outerNode) {
  49329. var b = splitPolygon(outerNode, hole);
  49330. filterPoints(b, b.next);
  49331. }
  49332. }
  49333. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  49334. function findHoleBridge(hole, outerNode) {
  49335. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  49336. // find a segment intersected by a ray from the hole's leftmost point to the left;
  49337. // segment's endpoint with lesser x will be potential connection point
  49338. do {
  49339. if (hy <= p.y && hy >= p.next.y) {
  49340. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  49341. if (x <= hx && x > qx) {
  49342. qx = x;
  49343. if (x === hx) {
  49344. if (hy === p.y)
  49345. return p;
  49346. if (hy === p.next.y)
  49347. return p.next;
  49348. }
  49349. m = p.x < p.next.x ? p : p.next;
  49350. }
  49351. }
  49352. p = p.next;
  49353. } while (p !== outerNode);
  49354. if (!m)
  49355. return null;
  49356. if (hx === qx)
  49357. return m.prev; // hole touches outer segment; pick lower endpoint
  49358. // look for points inside the triangle of hole point, segment intersection and endpoint;
  49359. // if there are no points found, we have a valid connection;
  49360. // otherwise choose the point of the minimum angle with the ray as connection point
  49361. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  49362. p = m.next;
  49363. while (p !== stop) {
  49364. if (hx >= p.x &&
  49365. p.x >= mx &&
  49366. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  49367. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  49368. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  49369. m = p;
  49370. tanMin = tan;
  49371. }
  49372. }
  49373. p = p.next;
  49374. }
  49375. return m;
  49376. }
  49377. // interlink polygon nodes in z-order
  49378. function indexCurve(start, minX, minY, size) {
  49379. var p = start;
  49380. do {
  49381. if (p.z === null)
  49382. p.z = zOrder(p.x, p.y, minX, minY, size);
  49383. p.prevZ = p.prev;
  49384. p.nextZ = p.next;
  49385. p = p.next;
  49386. } while (p !== start);
  49387. p.prevZ.nextZ = null;
  49388. p.prevZ = null;
  49389. sortLinked(p);
  49390. }
  49391. // Simon Tatham's linked list merge sort algorithm
  49392. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  49393. function sortLinked(list) {
  49394. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  49395. do {
  49396. p = list;
  49397. list = null;
  49398. tail = null;
  49399. numMerges = 0;
  49400. while (p) {
  49401. numMerges++;
  49402. q = p;
  49403. pSize = 0;
  49404. for (i = 0; i < inSize; i++) {
  49405. pSize++;
  49406. q = q.nextZ;
  49407. if (!q)
  49408. break;
  49409. }
  49410. qSize = inSize;
  49411. while (pSize > 0 || (qSize > 0 && q)) {
  49412. if (pSize === 0) {
  49413. e = q;
  49414. q = q.nextZ;
  49415. qSize--;
  49416. }
  49417. else if (qSize === 0 || !q) {
  49418. e = p;
  49419. p = p.nextZ;
  49420. pSize--;
  49421. }
  49422. else if (p.z <= q.z) {
  49423. e = p;
  49424. p = p.nextZ;
  49425. pSize--;
  49426. }
  49427. else {
  49428. e = q;
  49429. q = q.nextZ;
  49430. qSize--;
  49431. }
  49432. if (tail)
  49433. tail.nextZ = e;
  49434. else
  49435. list = e;
  49436. e.prevZ = tail;
  49437. tail = e;
  49438. }
  49439. p = q;
  49440. }
  49441. tail.nextZ = null;
  49442. inSize *= 2;
  49443. } while (numMerges > 1);
  49444. return list;
  49445. }
  49446. // z-order of a point given coords and size of the data bounding box
  49447. function zOrder(x, y, minX, minY, size) {
  49448. // coords are transformed into non-negative 15-bit integer range
  49449. x = 32767 * (x - minX) / size;
  49450. y = 32767 * (y - minY) / size;
  49451. x = (x | (x << 8)) & 0x00FF00FF;
  49452. x = (x | (x << 4)) & 0x0F0F0F0F;
  49453. x = (x | (x << 2)) & 0x33333333;
  49454. x = (x | (x << 1)) & 0x55555555;
  49455. y = (y | (y << 8)) & 0x00FF00FF;
  49456. y = (y | (y << 4)) & 0x0F0F0F0F;
  49457. y = (y | (y << 2)) & 0x33333333;
  49458. y = (y | (y << 1)) & 0x55555555;
  49459. return x | (y << 1);
  49460. }
  49461. // find the leftmost node of a polygon ring
  49462. function getLeftmost(start) {
  49463. var p = start, leftmost = start;
  49464. do {
  49465. if (p.x < leftmost.x)
  49466. leftmost = p;
  49467. p = p.next;
  49468. } while (p !== start);
  49469. return leftmost;
  49470. }
  49471. // check if a point lies within a convex triangle
  49472. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49473. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49474. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49475. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49476. }
  49477. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49478. function isValidDiagonal(a, b) {
  49479. return a.next.i !== b.i &&
  49480. a.prev.i !== b.i &&
  49481. !intersectsPolygon(a, b) &&
  49482. locallyInside(a, b) &&
  49483. locallyInside(b, a) &&
  49484. middleInside(a, b);
  49485. }
  49486. // signed area of a triangle
  49487. function area(p, q, r) {
  49488. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49489. }
  49490. // check if two points are equal
  49491. function equals(p1, p2) {
  49492. return p1.x === p2.x && p1.y === p2.y;
  49493. }
  49494. // check if two segments intersect
  49495. function intersects(p1, q1, p2, q2) {
  49496. if ((equals(p1, q1) && equals(p2, q2)) ||
  49497. (equals(p1, q2) && equals(p2, q1)))
  49498. return true;
  49499. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49500. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49501. }
  49502. // check if a polygon diagonal intersects any polygon segments
  49503. function intersectsPolygon(a, b) {
  49504. var p = a;
  49505. do {
  49506. if (p.i !== a.i &&
  49507. p.next.i !== a.i &&
  49508. p.i !== b.i &&
  49509. p.next.i !== b.i &&
  49510. intersects(p, p.next, a, b))
  49511. return true;
  49512. p = p.next;
  49513. } while (p !== a);
  49514. return false;
  49515. }
  49516. // check if a polygon diagonal is locally inside the polygon
  49517. function locallyInside(a, b) {
  49518. return area(a.prev, a, a.next) < 0
  49519. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49520. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49521. }
  49522. // check if the middle point of a polygon diagonal is inside the polygon
  49523. function middleInside(a, b) {
  49524. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49525. do {
  49526. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49527. inside = !inside;
  49528. p = p.next;
  49529. } while (p !== a);
  49530. return inside;
  49531. }
  49532. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49533. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49534. function splitPolygon(a, b) {
  49535. 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;
  49536. a.next = b;
  49537. b.prev = a;
  49538. a2.next = an;
  49539. an.prev = a2;
  49540. b2.next = a2;
  49541. a2.prev = b2;
  49542. bp.next = b2;
  49543. b2.prev = bp;
  49544. return b2;
  49545. }
  49546. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49547. function insertNode(i, x, y, last) {
  49548. var p = new Node(i, x, y);
  49549. if (!last) {
  49550. p.prev = p;
  49551. p.next = p;
  49552. }
  49553. else {
  49554. p.next = last.next;
  49555. p.prev = last;
  49556. last.next.prev = p;
  49557. last.next = p;
  49558. }
  49559. return p;
  49560. }
  49561. function removeNode(p) {
  49562. p.next.prev = p.prev;
  49563. p.prev.next = p.next;
  49564. if (p.prevZ)
  49565. p.prevZ.nextZ = p.nextZ;
  49566. if (p.nextZ)
  49567. p.nextZ.prevZ = p.prevZ;
  49568. }
  49569. function Node(i, x, y) {
  49570. // vertice index in coordinates array
  49571. this.i = i;
  49572. // vertex coordinates
  49573. this.x = x;
  49574. this.y = y;
  49575. // previous and next vertice nodes in a polygon ring
  49576. this.prev = null;
  49577. this.next = null;
  49578. // z-order curve value
  49579. this.z = null;
  49580. // previous and next nodes in z-order
  49581. this.prevZ = null;
  49582. this.nextZ = null;
  49583. // indicates whether this is a steiner point
  49584. this.steiner = false;
  49585. }
  49586. /**
  49587. * return a percentage difference between the polygon area and its triangulation area;
  49588. * used to verify correctness of triangulation
  49589. */
  49590. function deviation(data, holeIndices, dim, triangles) {
  49591. var hasHoles = holeIndices && holeIndices.length;
  49592. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49593. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49594. if (hasHoles) {
  49595. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49596. var start = holeIndices[i] * dim;
  49597. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49598. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49599. }
  49600. }
  49601. var trianglesArea = 0;
  49602. for (i = 0; i < triangles.length; i += 3) {
  49603. var a = triangles[i] * dim;
  49604. var b = triangles[i + 1] * dim;
  49605. var c = triangles[i + 2] * dim;
  49606. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49607. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49608. }
  49609. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49610. }
  49611. Earcut.deviation = deviation;
  49612. ;
  49613. function signedArea(data, start, end, dim) {
  49614. var sum = 0;
  49615. for (var i = start, j = end - dim; i < end; i += dim) {
  49616. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49617. j = i;
  49618. }
  49619. return sum;
  49620. }
  49621. /**
  49622. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49623. */
  49624. function flatten(data) {
  49625. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49626. for (var i = 0; i < data.length; i++) {
  49627. for (var j = 0; j < data[i].length; j++) {
  49628. for (var d = 0; d < dim; d++)
  49629. result.vertices.push(data[i][j][d]);
  49630. }
  49631. if (i > 0) {
  49632. holeIndex += data[i - 1].length;
  49633. result.holes.push(holeIndex);
  49634. }
  49635. }
  49636. return result;
  49637. }
  49638. Earcut.flatten = flatten;
  49639. ;
  49640. })(Earcut || (Earcut = {}));
  49641. var BABYLON;
  49642. (function (BABYLON) {
  49643. // Unique ID when we import meshes from Babylon to CSG
  49644. var currentCSGMeshId = 0;
  49645. // # class Vertex
  49646. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49647. // one to provide additional features like texture coordinates and vertex
  49648. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49649. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49650. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49651. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49652. // is not used anywhere else.
  49653. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49654. var Vertex = (function () {
  49655. function Vertex(pos, normal, uv) {
  49656. this.pos = pos;
  49657. this.normal = normal;
  49658. this.uv = uv;
  49659. }
  49660. Vertex.prototype.clone = function () {
  49661. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49662. };
  49663. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49664. // orientation of a polygon is flipped.
  49665. Vertex.prototype.flip = function () {
  49666. this.normal = this.normal.scale(-1);
  49667. };
  49668. // Create a new vertex between this vertex and `other` by linearly
  49669. // interpolating all properties using a parameter of `t`. Subclasses should
  49670. // override this to interpolate additional properties.
  49671. Vertex.prototype.interpolate = function (other, t) {
  49672. 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));
  49673. };
  49674. return Vertex;
  49675. })();
  49676. // # class Plane
  49677. // Represents a plane in 3D space.
  49678. var Plane = (function () {
  49679. function Plane(normal, w) {
  49680. this.normal = normal;
  49681. this.w = w;
  49682. }
  49683. Plane.FromPoints = function (a, b, c) {
  49684. var v0 = c.subtract(a);
  49685. var v1 = b.subtract(a);
  49686. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  49687. return null;
  49688. }
  49689. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  49690. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  49691. };
  49692. Plane.prototype.clone = function () {
  49693. return new Plane(this.normal.clone(), this.w);
  49694. };
  49695. Plane.prototype.flip = function () {
  49696. this.normal.scaleInPlace(-1);
  49697. this.w = -this.w;
  49698. };
  49699. // Split `polygon` by this plane if needed, then put the polygon or polygon
  49700. // fragments in the appropriate lists. Coplanar polygons go into either
  49701. // `coplanarFront` or `coplanarBack` depending on their orientation with
  49702. // respect to this plane. Polygons in front or in back of this plane go into
  49703. // either `front` or `back`.
  49704. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  49705. var COPLANAR = 0;
  49706. var FRONT = 1;
  49707. var BACK = 2;
  49708. var SPANNING = 3;
  49709. // Classify each point as well as the entire polygon into one of the above
  49710. // four classes.
  49711. var polygonType = 0;
  49712. var types = [];
  49713. var i;
  49714. var t;
  49715. for (i = 0; i < polygon.vertices.length; i++) {
  49716. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  49717. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  49718. polygonType |= type;
  49719. types.push(type);
  49720. }
  49721. // Put the polygon in the correct list, splitting it when necessary.
  49722. switch (polygonType) {
  49723. case COPLANAR:
  49724. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  49725. break;
  49726. case FRONT:
  49727. front.push(polygon);
  49728. break;
  49729. case BACK:
  49730. back.push(polygon);
  49731. break;
  49732. case SPANNING:
  49733. var f = [], b = [];
  49734. for (i = 0; i < polygon.vertices.length; i++) {
  49735. var j = (i + 1) % polygon.vertices.length;
  49736. var ti = types[i], tj = types[j];
  49737. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49738. if (ti !== BACK)
  49739. f.push(vi);
  49740. if (ti !== FRONT)
  49741. b.push(ti !== BACK ? vi.clone() : vi);
  49742. if ((ti | tj) === SPANNING) {
  49743. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49744. var v = vi.interpolate(vj, t);
  49745. f.push(v);
  49746. b.push(v.clone());
  49747. }
  49748. }
  49749. var poly;
  49750. if (f.length >= 3) {
  49751. poly = new Polygon(f, polygon.shared);
  49752. if (poly.plane)
  49753. front.push(poly);
  49754. }
  49755. if (b.length >= 3) {
  49756. poly = new Polygon(b, polygon.shared);
  49757. if (poly.plane)
  49758. back.push(poly);
  49759. }
  49760. break;
  49761. }
  49762. };
  49763. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49764. // point is on the plane.
  49765. Plane.EPSILON = 1e-5;
  49766. return Plane;
  49767. })();
  49768. // # class Polygon
  49769. // Represents a convex polygon. The vertices used to initialize a polygon must
  49770. // be coplanar and form a convex loop.
  49771. //
  49772. // Each convex polygon has a `shared` property, which is shared between all
  49773. // polygons that are clones of each other or were split from the same polygon.
  49774. // This can be used to define per-polygon properties (such as surface color).
  49775. var Polygon = (function () {
  49776. function Polygon(vertices, shared) {
  49777. this.vertices = vertices;
  49778. this.shared = shared;
  49779. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49780. }
  49781. Polygon.prototype.clone = function () {
  49782. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49783. return new Polygon(vertices, this.shared);
  49784. };
  49785. Polygon.prototype.flip = function () {
  49786. this.vertices.reverse().map(function (v) { v.flip(); });
  49787. this.plane.flip();
  49788. };
  49789. return Polygon;
  49790. })();
  49791. // # class Node
  49792. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  49793. // by picking a polygon to split along. That polygon (and all other coplanar
  49794. // polygons) are added directly to that node and the other polygons are added to
  49795. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  49796. // no distinction between internal and leaf nodes.
  49797. var Node = (function () {
  49798. function Node(polygons) {
  49799. this.plane = null;
  49800. this.front = null;
  49801. this.back = null;
  49802. this.polygons = [];
  49803. if (polygons) {
  49804. this.build(polygons);
  49805. }
  49806. }
  49807. Node.prototype.clone = function () {
  49808. var node = new Node();
  49809. node.plane = this.plane && this.plane.clone();
  49810. node.front = this.front && this.front.clone();
  49811. node.back = this.back && this.back.clone();
  49812. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  49813. return node;
  49814. };
  49815. // Convert solid space to empty space and empty space to solid space.
  49816. Node.prototype.invert = function () {
  49817. for (var i = 0; i < this.polygons.length; i++) {
  49818. this.polygons[i].flip();
  49819. }
  49820. if (this.plane) {
  49821. this.plane.flip();
  49822. }
  49823. if (this.front) {
  49824. this.front.invert();
  49825. }
  49826. if (this.back) {
  49827. this.back.invert();
  49828. }
  49829. var temp = this.front;
  49830. this.front = this.back;
  49831. this.back = temp;
  49832. };
  49833. // Recursively remove all polygons in `polygons` that are inside this BSP
  49834. // tree.
  49835. Node.prototype.clipPolygons = function (polygons) {
  49836. if (!this.plane)
  49837. return polygons.slice();
  49838. var front = [], back = [];
  49839. for (var i = 0; i < polygons.length; i++) {
  49840. this.plane.splitPolygon(polygons[i], front, back, front, back);
  49841. }
  49842. if (this.front) {
  49843. front = this.front.clipPolygons(front);
  49844. }
  49845. if (this.back) {
  49846. back = this.back.clipPolygons(back);
  49847. }
  49848. else {
  49849. back = [];
  49850. }
  49851. return front.concat(back);
  49852. };
  49853. // Remove all polygons in this BSP tree that are inside the other BSP tree
  49854. // `bsp`.
  49855. Node.prototype.clipTo = function (bsp) {
  49856. this.polygons = bsp.clipPolygons(this.polygons);
  49857. if (this.front)
  49858. this.front.clipTo(bsp);
  49859. if (this.back)
  49860. this.back.clipTo(bsp);
  49861. };
  49862. // Return a list of all polygons in this BSP tree.
  49863. Node.prototype.allPolygons = function () {
  49864. var polygons = this.polygons.slice();
  49865. if (this.front)
  49866. polygons = polygons.concat(this.front.allPolygons());
  49867. if (this.back)
  49868. polygons = polygons.concat(this.back.allPolygons());
  49869. return polygons;
  49870. };
  49871. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  49872. // new polygons are filtered down to the bottom of the tree and become new
  49873. // nodes there. Each set of polygons is partitioned using the first polygon
  49874. // (no heuristic is used to pick a good split).
  49875. Node.prototype.build = function (polygons) {
  49876. if (!polygons.length)
  49877. return;
  49878. if (!this.plane)
  49879. this.plane = polygons[0].plane.clone();
  49880. var front = [], back = [];
  49881. for (var i = 0; i < polygons.length; i++) {
  49882. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  49883. }
  49884. if (front.length) {
  49885. if (!this.front)
  49886. this.front = new Node();
  49887. this.front.build(front);
  49888. }
  49889. if (back.length) {
  49890. if (!this.back)
  49891. this.back = new Node();
  49892. this.back.build(back);
  49893. }
  49894. };
  49895. return Node;
  49896. })();
  49897. var CSG = (function () {
  49898. function CSG() {
  49899. this.polygons = new Array();
  49900. }
  49901. // Convert BABYLON.Mesh to BABYLON.CSG
  49902. CSG.FromMesh = function (mesh) {
  49903. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  49904. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  49905. if (mesh instanceof BABYLON.Mesh) {
  49906. mesh.computeWorldMatrix(true);
  49907. matrix = mesh.getWorldMatrix();
  49908. meshPosition = mesh.position.clone();
  49909. meshRotation = mesh.rotation.clone();
  49910. if (mesh.rotationQuaternion) {
  49911. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  49912. }
  49913. meshScaling = mesh.scaling.clone();
  49914. }
  49915. else {
  49916. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  49917. }
  49918. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49919. var subMeshes = mesh.subMeshes;
  49920. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  49921. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  49922. vertices = [];
  49923. for (var j = 0; j < 3; j++) {
  49924. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  49925. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  49926. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  49927. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  49928. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  49929. vertex = new Vertex(position, normal, uv);
  49930. vertices.push(vertex);
  49931. }
  49932. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  49933. // To handle the case of degenerated triangle
  49934. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  49935. if (polygon.plane)
  49936. polygons.push(polygon);
  49937. }
  49938. }
  49939. var csg = CSG.FromPolygons(polygons);
  49940. csg.matrix = matrix;
  49941. csg.position = meshPosition;
  49942. csg.rotation = meshRotation;
  49943. csg.scaling = meshScaling;
  49944. csg.rotationQuaternion = meshRotationQuaternion;
  49945. currentCSGMeshId++;
  49946. return csg;
  49947. };
  49948. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  49949. CSG.FromPolygons = function (polygons) {
  49950. var csg = new CSG();
  49951. csg.polygons = polygons;
  49952. return csg;
  49953. };
  49954. CSG.prototype.clone = function () {
  49955. var csg = new CSG();
  49956. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  49957. csg.copyTransformAttributes(this);
  49958. return csg;
  49959. };
  49960. CSG.prototype.toPolygons = function () {
  49961. return this.polygons;
  49962. };
  49963. CSG.prototype.union = function (csg) {
  49964. var a = new Node(this.clone().polygons);
  49965. var b = new Node(csg.clone().polygons);
  49966. a.clipTo(b);
  49967. b.clipTo(a);
  49968. b.invert();
  49969. b.clipTo(a);
  49970. b.invert();
  49971. a.build(b.allPolygons());
  49972. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49973. };
  49974. CSG.prototype.unionInPlace = function (csg) {
  49975. var a = new Node(this.polygons);
  49976. var b = new Node(csg.polygons);
  49977. a.clipTo(b);
  49978. b.clipTo(a);
  49979. b.invert();
  49980. b.clipTo(a);
  49981. b.invert();
  49982. a.build(b.allPolygons());
  49983. this.polygons = a.allPolygons();
  49984. };
  49985. CSG.prototype.subtract = function (csg) {
  49986. var a = new Node(this.clone().polygons);
  49987. var b = new Node(csg.clone().polygons);
  49988. a.invert();
  49989. a.clipTo(b);
  49990. b.clipTo(a);
  49991. b.invert();
  49992. b.clipTo(a);
  49993. b.invert();
  49994. a.build(b.allPolygons());
  49995. a.invert();
  49996. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49997. };
  49998. CSG.prototype.subtractInPlace = function (csg) {
  49999. var a = new Node(this.polygons);
  50000. var b = new Node(csg.polygons);
  50001. a.invert();
  50002. a.clipTo(b);
  50003. b.clipTo(a);
  50004. b.invert();
  50005. b.clipTo(a);
  50006. b.invert();
  50007. a.build(b.allPolygons());
  50008. a.invert();
  50009. this.polygons = a.allPolygons();
  50010. };
  50011. CSG.prototype.intersect = function (csg) {
  50012. var a = new Node(this.clone().polygons);
  50013. var b = new Node(csg.clone().polygons);
  50014. a.invert();
  50015. b.clipTo(a);
  50016. b.invert();
  50017. a.clipTo(b);
  50018. b.clipTo(a);
  50019. a.build(b.allPolygons());
  50020. a.invert();
  50021. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50022. };
  50023. CSG.prototype.intersectInPlace = function (csg) {
  50024. var a = new Node(this.polygons);
  50025. var b = new Node(csg.polygons);
  50026. a.invert();
  50027. b.clipTo(a);
  50028. b.invert();
  50029. a.clipTo(b);
  50030. b.clipTo(a);
  50031. a.build(b.allPolygons());
  50032. a.invert();
  50033. this.polygons = a.allPolygons();
  50034. };
  50035. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  50036. // not modified.
  50037. CSG.prototype.inverse = function () {
  50038. var csg = this.clone();
  50039. csg.inverseInPlace();
  50040. return csg;
  50041. };
  50042. CSG.prototype.inverseInPlace = function () {
  50043. this.polygons.map(function (p) { p.flip(); });
  50044. };
  50045. // This is used to keep meshes transformations so they can be restored
  50046. // when we build back a Babylon Mesh
  50047. // NB : All CSG operations are performed in world coordinates
  50048. CSG.prototype.copyTransformAttributes = function (csg) {
  50049. this.matrix = csg.matrix;
  50050. this.position = csg.position;
  50051. this.rotation = csg.rotation;
  50052. this.scaling = csg.scaling;
  50053. this.rotationQuaternion = csg.rotationQuaternion;
  50054. return this;
  50055. };
  50056. // Build Raw mesh from CSG
  50057. // Coordinates here are in world space
  50058. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  50059. var matrix = this.matrix.clone();
  50060. matrix.invert();
  50061. 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;
  50062. if (keepSubMeshes) {
  50063. // Sort Polygons, since subMeshes are indices range
  50064. polygons.sort(function (a, b) {
  50065. if (a.shared.meshId === b.shared.meshId) {
  50066. return a.shared.subMeshId - b.shared.subMeshId;
  50067. }
  50068. else {
  50069. return a.shared.meshId - b.shared.meshId;
  50070. }
  50071. });
  50072. }
  50073. for (var i = 0, il = polygons.length; i < il; i++) {
  50074. polygon = polygons[i];
  50075. // Building SubMeshes
  50076. if (!subMesh_dict[polygon.shared.meshId]) {
  50077. subMesh_dict[polygon.shared.meshId] = {};
  50078. }
  50079. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  50080. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  50081. indexStart: +Infinity,
  50082. indexEnd: -Infinity,
  50083. materialIndex: polygon.shared.materialIndex
  50084. };
  50085. }
  50086. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  50087. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  50088. polygonIndices[0] = 0;
  50089. polygonIndices[1] = j - 1;
  50090. polygonIndices[2] = j;
  50091. for (var k = 0; k < 3; k++) {
  50092. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  50093. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  50094. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  50095. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  50096. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  50097. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  50098. // Check if 2 points can be merged
  50099. if (!(typeof vertex_idx !== 'undefined' &&
  50100. normals[vertex_idx * 3] === localNormal.x &&
  50101. normals[vertex_idx * 3 + 1] === localNormal.y &&
  50102. normals[vertex_idx * 3 + 2] === localNormal.z &&
  50103. uvs[vertex_idx * 2] === uv.x &&
  50104. uvs[vertex_idx * 2 + 1] === uv.y)) {
  50105. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  50106. uvs.push(uv.x, uv.y);
  50107. normals.push(normal.x, normal.y, normal.z);
  50108. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  50109. }
  50110. indices.push(vertex_idx);
  50111. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  50112. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  50113. currentIndex++;
  50114. }
  50115. }
  50116. }
  50117. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  50118. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  50119. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  50120. mesh.setIndices(indices);
  50121. if (keepSubMeshes) {
  50122. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  50123. var materialIndexOffset = 0, materialMaxIndex;
  50124. mesh.subMeshes = new Array();
  50125. for (var m in subMesh_dict) {
  50126. materialMaxIndex = -1;
  50127. for (var sm in subMesh_dict[m]) {
  50128. subMesh_obj = subMesh_dict[m][sm];
  50129. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  50130. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  50131. }
  50132. materialIndexOffset += ++materialMaxIndex;
  50133. }
  50134. }
  50135. return mesh;
  50136. };
  50137. // Build Mesh from CSG taking material and transforms into account
  50138. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  50139. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  50140. mesh.material = material;
  50141. mesh.position.copyFrom(this.position);
  50142. mesh.rotation.copyFrom(this.rotation);
  50143. if (this.rotationQuaternion) {
  50144. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  50145. }
  50146. mesh.scaling.copyFrom(this.scaling);
  50147. mesh.computeWorldMatrix(true);
  50148. return mesh;
  50149. };
  50150. return CSG;
  50151. })();
  50152. BABYLON.CSG = CSG;
  50153. })(BABYLON || (BABYLON = {}));
  50154. var BABYLON;
  50155. (function (BABYLON) {
  50156. var VRDistortionCorrectionPostProcess = (function (_super) {
  50157. __extends(VRDistortionCorrectionPostProcess, _super);
  50158. //ANY
  50159. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  50160. var _this = this;
  50161. _super.call(this, name, "vrDistortionCorrection", [
  50162. 'LensCenter',
  50163. 'Scale',
  50164. 'ScaleIn',
  50165. 'HmdWarpParam'
  50166. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  50167. this._isRightEye = isRightEye;
  50168. this._distortionFactors = vrMetrics.distortionK;
  50169. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  50170. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  50171. this.onSizeChangedObservable.add(function () {
  50172. _this.aspectRatio = _this.width * .5 / _this.height;
  50173. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  50174. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  50175. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  50176. });
  50177. this.onApplyObservable.add(function (effect) {
  50178. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  50179. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  50180. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  50181. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  50182. });
  50183. }
  50184. return VRDistortionCorrectionPostProcess;
  50185. })(BABYLON.PostProcess);
  50186. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  50187. })(BABYLON || (BABYLON = {}));
  50188. // Mainly based on these 2 articles :
  50189. // 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
  50190. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  50191. var BABYLON;
  50192. (function (BABYLON) {
  50193. (function (JoystickAxis) {
  50194. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  50195. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  50196. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  50197. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  50198. var JoystickAxis = BABYLON.JoystickAxis;
  50199. var VirtualJoystick = (function () {
  50200. function VirtualJoystick(leftJoystick) {
  50201. var _this = this;
  50202. if (leftJoystick) {
  50203. this._leftJoystick = true;
  50204. }
  50205. else {
  50206. this._leftJoystick = false;
  50207. }
  50208. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  50209. VirtualJoystick._globalJoystickIndex++;
  50210. // By default left & right arrow keys are moving the X
  50211. // and up & down keys are moving the Y
  50212. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50213. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50214. this.reverseLeftRight = false;
  50215. this.reverseUpDown = false;
  50216. // collections of pointers
  50217. this._touches = new BABYLON.StringDictionary();
  50218. this.deltaPosition = BABYLON.Vector3.Zero();
  50219. this._joystickSensibility = 25;
  50220. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50221. this._rotationSpeed = 25;
  50222. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  50223. this._rotateOnAxisRelativeToMesh = false;
  50224. this._onResize = function (evt) {
  50225. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50226. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50227. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  50228. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  50229. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  50230. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  50231. };
  50232. // injecting a canvas element on top of the canvas 3D game
  50233. if (!VirtualJoystick.vjCanvas) {
  50234. window.addEventListener("resize", this._onResize, false);
  50235. VirtualJoystick.vjCanvas = document.createElement("canvas");
  50236. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50237. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50238. VirtualJoystick.vjCanvas.width = window.innerWidth;
  50239. VirtualJoystick.vjCanvas.height = window.innerHeight;
  50240. VirtualJoystick.vjCanvas.style.width = "100%";
  50241. VirtualJoystick.vjCanvas.style.height = "100%";
  50242. VirtualJoystick.vjCanvas.style.position = "absolute";
  50243. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  50244. VirtualJoystick.vjCanvas.style.top = "0px";
  50245. VirtualJoystick.vjCanvas.style.left = "0px";
  50246. VirtualJoystick.vjCanvas.style.zIndex = "5";
  50247. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  50248. // Support for jQuery PEP polyfill
  50249. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  50250. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  50251. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  50252. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50253. document.body.appendChild(VirtualJoystick.vjCanvas);
  50254. }
  50255. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  50256. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  50257. this.pressed = false;
  50258. // default joystick color
  50259. this._joystickColor = "cyan";
  50260. this._joystickPointerID = -1;
  50261. // current joystick position
  50262. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  50263. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  50264. // origin joystick position
  50265. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  50266. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  50267. this._onPointerDownHandlerRef = function (evt) {
  50268. _this._onPointerDown(evt);
  50269. };
  50270. this._onPointerMoveHandlerRef = function (evt) {
  50271. _this._onPointerMove(evt);
  50272. };
  50273. this._onPointerOutHandlerRef = function (evt) {
  50274. _this._onPointerUp(evt);
  50275. };
  50276. this._onPointerUpHandlerRef = function (evt) {
  50277. _this._onPointerUp(evt);
  50278. };
  50279. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  50280. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  50281. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  50282. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  50283. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  50284. evt.preventDefault(); // Disables system menu
  50285. }, false);
  50286. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50287. }
  50288. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  50289. this._joystickSensibility = newJoystickSensibility;
  50290. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50291. };
  50292. VirtualJoystick.prototype._onPointerDown = function (e) {
  50293. var positionOnScreenCondition;
  50294. e.preventDefault();
  50295. if (this._leftJoystick === true) {
  50296. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  50297. }
  50298. else {
  50299. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  50300. }
  50301. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  50302. // First contact will be dedicated to the virtual joystick
  50303. this._joystickPointerID = e.pointerId;
  50304. this._joystickPointerStartPos.x = e.clientX;
  50305. this._joystickPointerStartPos.y = e.clientY;
  50306. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  50307. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  50308. this._deltaJoystickVector.x = 0;
  50309. this._deltaJoystickVector.y = 0;
  50310. this.pressed = true;
  50311. this._touches.add(e.pointerId.toString(), e);
  50312. }
  50313. else {
  50314. // You can only trigger the action buttons with a joystick declared
  50315. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  50316. this._action();
  50317. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  50318. }
  50319. }
  50320. };
  50321. VirtualJoystick.prototype._onPointerMove = function (e) {
  50322. // If the current pointer is the one associated to the joystick (first touch contact)
  50323. if (this._joystickPointerID == e.pointerId) {
  50324. this._joystickPointerPos.x = e.clientX;
  50325. this._joystickPointerPos.y = e.clientY;
  50326. this._deltaJoystickVector = this._joystickPointerPos.clone();
  50327. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  50328. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  50329. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  50330. switch (this._axisTargetedByLeftAndRight) {
  50331. case JoystickAxis.X:
  50332. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  50333. break;
  50334. case JoystickAxis.Y:
  50335. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  50336. break;
  50337. case JoystickAxis.Z:
  50338. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  50339. break;
  50340. }
  50341. var directionUpDown = this.reverseUpDown ? 1 : -1;
  50342. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  50343. switch (this._axisTargetedByUpAndDown) {
  50344. case JoystickAxis.X:
  50345. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  50346. break;
  50347. case JoystickAxis.Y:
  50348. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  50349. break;
  50350. case JoystickAxis.Z:
  50351. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  50352. break;
  50353. }
  50354. }
  50355. else {
  50356. var data = this._touches.get(e.pointerId.toString());
  50357. if (data) {
  50358. data.x = e.clientX;
  50359. data.y = e.clientY;
  50360. }
  50361. }
  50362. };
  50363. VirtualJoystick.prototype._onPointerUp = function (e) {
  50364. if (this._joystickPointerID == e.pointerId) {
  50365. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  50366. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  50367. this._joystickPointerID = -1;
  50368. this.pressed = false;
  50369. }
  50370. else {
  50371. var touch = this._touches.get(e.pointerId.toString());
  50372. if (touch) {
  50373. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50374. }
  50375. }
  50376. this._deltaJoystickVector.x = 0;
  50377. this._deltaJoystickVector.y = 0;
  50378. this._touches.remove(e.pointerId.toString());
  50379. };
  50380. /**
  50381. * Change the color of the virtual joystick
  50382. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  50383. */
  50384. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  50385. this._joystickColor = newColor;
  50386. };
  50387. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  50388. this._action = action;
  50389. };
  50390. // Define which axis you'd like to control for left & right
  50391. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  50392. switch (axis) {
  50393. case JoystickAxis.X:
  50394. case JoystickAxis.Y:
  50395. case JoystickAxis.Z:
  50396. this._axisTargetedByLeftAndRight = axis;
  50397. break;
  50398. default:
  50399. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50400. break;
  50401. }
  50402. };
  50403. // Define which axis you'd like to control for up & down
  50404. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  50405. switch (axis) {
  50406. case JoystickAxis.X:
  50407. case JoystickAxis.Y:
  50408. case JoystickAxis.Z:
  50409. this._axisTargetedByUpAndDown = axis;
  50410. break;
  50411. default:
  50412. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50413. break;
  50414. }
  50415. };
  50416. VirtualJoystick.prototype._clearCanvas = function () {
  50417. if (this._leftJoystick) {
  50418. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  50419. }
  50420. else {
  50421. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  50422. }
  50423. };
  50424. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  50425. var _this = this;
  50426. if (this.pressed) {
  50427. this._touches.forEach(function (touch) {
  50428. if (touch.pointerId === _this._joystickPointerID) {
  50429. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  50430. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  50431. VirtualJoystick.vjCanvasContext.beginPath();
  50432. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50433. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50434. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  50435. VirtualJoystick.vjCanvasContext.stroke();
  50436. VirtualJoystick.vjCanvasContext.closePath();
  50437. VirtualJoystick.vjCanvasContext.beginPath();
  50438. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50439. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50440. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  50441. VirtualJoystick.vjCanvasContext.stroke();
  50442. VirtualJoystick.vjCanvasContext.closePath();
  50443. VirtualJoystick.vjCanvasContext.beginPath();
  50444. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50445. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  50446. VirtualJoystick.vjCanvasContext.stroke();
  50447. VirtualJoystick.vjCanvasContext.closePath();
  50448. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  50449. }
  50450. else {
  50451. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50452. VirtualJoystick.vjCanvasContext.beginPath();
  50453. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  50454. VirtualJoystick.vjCanvasContext.beginPath();
  50455. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  50456. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50457. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  50458. VirtualJoystick.vjCanvasContext.stroke();
  50459. VirtualJoystick.vjCanvasContext.closePath();
  50460. touch.prevX = touch.x;
  50461. touch.prevY = touch.y;
  50462. }
  50463. ;
  50464. });
  50465. }
  50466. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50467. };
  50468. VirtualJoystick.prototype.releaseCanvas = function () {
  50469. if (VirtualJoystick.vjCanvas) {
  50470. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50471. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50472. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50473. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50474. window.removeEventListener("resize", this._onResize);
  50475. document.body.removeChild(VirtualJoystick.vjCanvas);
  50476. VirtualJoystick.vjCanvas = null;
  50477. }
  50478. };
  50479. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50480. VirtualJoystick._globalJoystickIndex = 0;
  50481. return VirtualJoystick;
  50482. })();
  50483. BABYLON.VirtualJoystick = VirtualJoystick;
  50484. })(BABYLON || (BABYLON = {}));
  50485. var BABYLON;
  50486. (function (BABYLON) {
  50487. // We're mainly based on the logic defined into the FreeCamera code
  50488. var VirtualJoysticksCamera = (function (_super) {
  50489. __extends(VirtualJoysticksCamera, _super);
  50490. function VirtualJoysticksCamera(name, position, scene) {
  50491. _super.call(this, name, position, scene);
  50492. this.inputs.addVirtualJoystick();
  50493. }
  50494. return VirtualJoysticksCamera;
  50495. })(BABYLON.FreeCamera);
  50496. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50497. })(BABYLON || (BABYLON = {}));
  50498. var BABYLON;
  50499. (function (BABYLON) {
  50500. var FreeCameraVirtualJoystickInput = (function () {
  50501. function FreeCameraVirtualJoystickInput() {
  50502. }
  50503. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50504. return this._leftjoystick;
  50505. };
  50506. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50507. return this._rightjoystick;
  50508. };
  50509. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50510. if (this._leftjoystick) {
  50511. var camera = this.camera;
  50512. var speed = camera._computeLocalCameraSpeed() * 50;
  50513. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50514. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50515. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50516. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50517. if (!this._leftjoystick.pressed) {
  50518. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50519. }
  50520. if (!this._rightjoystick.pressed) {
  50521. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50522. }
  50523. }
  50524. };
  50525. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50526. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50527. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50528. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50529. this._leftjoystick.setJoystickSensibility(0.15);
  50530. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50531. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50532. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50533. this._rightjoystick.reverseUpDown = true;
  50534. this._rightjoystick.setJoystickSensibility(0.05);
  50535. this._rightjoystick.setJoystickColor("yellow");
  50536. };
  50537. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50538. this._leftjoystick.releaseCanvas();
  50539. this._rightjoystick.releaseCanvas();
  50540. };
  50541. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50542. return "FreeCameraVirtualJoystickInput";
  50543. };
  50544. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50545. return "virtualJoystick";
  50546. };
  50547. return FreeCameraVirtualJoystickInput;
  50548. })();
  50549. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50550. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50551. })(BABYLON || (BABYLON = {}));
  50552. var BABYLON;
  50553. (function (BABYLON) {
  50554. var AnaglyphPostProcess = (function (_super) {
  50555. __extends(AnaglyphPostProcess, _super);
  50556. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50557. var _this = this;
  50558. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  50559. this._passedProcess = rigCameras[0]._rigPostProcess;
  50560. this.onApplyObservable.add(function (effect) {
  50561. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50562. });
  50563. }
  50564. return AnaglyphPostProcess;
  50565. })(BABYLON.PostProcess);
  50566. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50567. })(BABYLON || (BABYLON = {}));
  50568. var BABYLON;
  50569. (function (BABYLON) {
  50570. var OutlineRenderer = (function () {
  50571. function OutlineRenderer(scene) {
  50572. this._scene = scene;
  50573. }
  50574. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50575. var _this = this;
  50576. if (useOverlay === void 0) { useOverlay = false; }
  50577. var scene = this._scene;
  50578. var engine = this._scene.getEngine();
  50579. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50580. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50581. return;
  50582. }
  50583. var mesh = subMesh.getRenderingMesh();
  50584. var material = subMesh.getMaterial();
  50585. engine.enableEffect(this._effect);
  50586. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50587. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50588. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50589. // Bones
  50590. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50591. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50592. }
  50593. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50594. // Alpha test
  50595. if (material && material.needAlphaTesting()) {
  50596. var alphaTexture = material.getAlphaTestTexture();
  50597. this._effect.setTexture("diffuseSampler", alphaTexture);
  50598. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50599. }
  50600. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50601. };
  50602. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50603. var defines = [];
  50604. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50605. var mesh = subMesh.getMesh();
  50606. var material = subMesh.getMaterial();
  50607. // Alpha test
  50608. if (material && material.needAlphaTesting()) {
  50609. defines.push("#define ALPHATEST");
  50610. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50611. attribs.push(BABYLON.VertexBuffer.UVKind);
  50612. defines.push("#define UV1");
  50613. }
  50614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50615. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50616. defines.push("#define UV2");
  50617. }
  50618. }
  50619. // Bones
  50620. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50623. if (mesh.numBoneInfluencers > 4) {
  50624. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50625. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50626. }
  50627. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50628. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50629. }
  50630. else {
  50631. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50632. }
  50633. // Instances
  50634. if (useInstances) {
  50635. defines.push("#define INSTANCES");
  50636. attribs.push("world0");
  50637. attribs.push("world1");
  50638. attribs.push("world2");
  50639. attribs.push("world3");
  50640. }
  50641. // Get correct effect
  50642. var join = defines.join("\n");
  50643. if (this._cachedDefines !== join) {
  50644. this._cachedDefines = join;
  50645. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50646. }
  50647. return this._effect.isReady();
  50648. };
  50649. return OutlineRenderer;
  50650. })();
  50651. BABYLON.OutlineRenderer = OutlineRenderer;
  50652. })(BABYLON || (BABYLON = {}));
  50653. var BABYLON;
  50654. (function (BABYLON) {
  50655. var MeshAssetTask = (function () {
  50656. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50657. this.name = name;
  50658. this.meshesNames = meshesNames;
  50659. this.rootUrl = rootUrl;
  50660. this.sceneFilename = sceneFilename;
  50661. this.isCompleted = false;
  50662. }
  50663. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50664. var _this = this;
  50665. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50666. _this.loadedMeshes = meshes;
  50667. _this.loadedParticleSystems = particleSystems;
  50668. _this.loadedSkeletons = skeletons;
  50669. _this.isCompleted = true;
  50670. if (_this.onSuccess) {
  50671. _this.onSuccess(_this);
  50672. }
  50673. onSuccess();
  50674. }, null, function () {
  50675. if (_this.onError) {
  50676. _this.onError(_this);
  50677. }
  50678. onError();
  50679. });
  50680. };
  50681. return MeshAssetTask;
  50682. })();
  50683. BABYLON.MeshAssetTask = MeshAssetTask;
  50684. var TextFileAssetTask = (function () {
  50685. function TextFileAssetTask(name, url) {
  50686. this.name = name;
  50687. this.url = url;
  50688. this.isCompleted = false;
  50689. }
  50690. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50691. var _this = this;
  50692. BABYLON.Tools.LoadFile(this.url, function (data) {
  50693. _this.text = data;
  50694. _this.isCompleted = true;
  50695. if (_this.onSuccess) {
  50696. _this.onSuccess(_this);
  50697. }
  50698. onSuccess();
  50699. }, null, scene.database, false, function () {
  50700. if (_this.onError) {
  50701. _this.onError(_this);
  50702. }
  50703. onError();
  50704. });
  50705. };
  50706. return TextFileAssetTask;
  50707. })();
  50708. BABYLON.TextFileAssetTask = TextFileAssetTask;
  50709. var BinaryFileAssetTask = (function () {
  50710. function BinaryFileAssetTask(name, url) {
  50711. this.name = name;
  50712. this.url = url;
  50713. this.isCompleted = false;
  50714. }
  50715. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50716. var _this = this;
  50717. BABYLON.Tools.LoadFile(this.url, function (data) {
  50718. _this.data = data;
  50719. _this.isCompleted = true;
  50720. if (_this.onSuccess) {
  50721. _this.onSuccess(_this);
  50722. }
  50723. onSuccess();
  50724. }, null, scene.database, true, function () {
  50725. if (_this.onError) {
  50726. _this.onError(_this);
  50727. }
  50728. onError();
  50729. });
  50730. };
  50731. return BinaryFileAssetTask;
  50732. })();
  50733. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50734. var ImageAssetTask = (function () {
  50735. function ImageAssetTask(name, url) {
  50736. this.name = name;
  50737. this.url = url;
  50738. this.isCompleted = false;
  50739. }
  50740. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50741. var _this = this;
  50742. var img = new Image();
  50743. img.onload = function () {
  50744. _this.image = img;
  50745. _this.isCompleted = true;
  50746. if (_this.onSuccess) {
  50747. _this.onSuccess(_this);
  50748. }
  50749. onSuccess();
  50750. };
  50751. img.onerror = function () {
  50752. if (_this.onError) {
  50753. _this.onError(_this);
  50754. }
  50755. onError();
  50756. };
  50757. img.src = this.url;
  50758. };
  50759. return ImageAssetTask;
  50760. })();
  50761. BABYLON.ImageAssetTask = ImageAssetTask;
  50762. var TextureAssetTask = (function () {
  50763. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50765. this.name = name;
  50766. this.url = url;
  50767. this.noMipmap = noMipmap;
  50768. this.invertY = invertY;
  50769. this.samplingMode = samplingMode;
  50770. this.isCompleted = false;
  50771. }
  50772. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50773. var _this = this;
  50774. var onload = function () {
  50775. _this.isCompleted = true;
  50776. if (_this.onSuccess) {
  50777. _this.onSuccess(_this);
  50778. }
  50779. onSuccess();
  50780. };
  50781. var onerror = function () {
  50782. if (_this.onError) {
  50783. _this.onError(_this);
  50784. }
  50785. onError();
  50786. };
  50787. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  50788. };
  50789. return TextureAssetTask;
  50790. })();
  50791. BABYLON.TextureAssetTask = TextureAssetTask;
  50792. var AssetsManager = (function () {
  50793. function AssetsManager(scene) {
  50794. this._tasks = new Array();
  50795. this._waitingTasksCount = 0;
  50796. this.useDefaultLoadingScreen = true;
  50797. this._scene = scene;
  50798. }
  50799. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  50800. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  50801. this._tasks.push(task);
  50802. return task;
  50803. };
  50804. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  50805. var task = new TextFileAssetTask(taskName, url);
  50806. this._tasks.push(task);
  50807. return task;
  50808. };
  50809. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  50810. var task = new BinaryFileAssetTask(taskName, url);
  50811. this._tasks.push(task);
  50812. return task;
  50813. };
  50814. AssetsManager.prototype.addImageTask = function (taskName, url) {
  50815. var task = new ImageAssetTask(taskName, url);
  50816. this._tasks.push(task);
  50817. return task;
  50818. };
  50819. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  50820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50821. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  50822. this._tasks.push(task);
  50823. return task;
  50824. };
  50825. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  50826. this._waitingTasksCount--;
  50827. if (this._waitingTasksCount === 0) {
  50828. if (this.onFinish) {
  50829. this.onFinish(this._tasks);
  50830. }
  50831. this._scene.getEngine().hideLoadingUI();
  50832. }
  50833. };
  50834. AssetsManager.prototype._runTask = function (task) {
  50835. var _this = this;
  50836. task.run(this._scene, function () {
  50837. if (_this.onTaskSuccess) {
  50838. _this.onTaskSuccess(task);
  50839. }
  50840. _this._decreaseWaitingTasksCount();
  50841. }, function () {
  50842. if (_this.onTaskError) {
  50843. _this.onTaskError(task);
  50844. }
  50845. _this._decreaseWaitingTasksCount();
  50846. });
  50847. };
  50848. AssetsManager.prototype.reset = function () {
  50849. this._tasks = new Array();
  50850. return this;
  50851. };
  50852. AssetsManager.prototype.load = function () {
  50853. this._waitingTasksCount = this._tasks.length;
  50854. if (this._waitingTasksCount === 0) {
  50855. if (this.onFinish) {
  50856. this.onFinish(this._tasks);
  50857. }
  50858. return this;
  50859. }
  50860. if (this.useDefaultLoadingScreen) {
  50861. this._scene.getEngine().displayLoadingUI();
  50862. }
  50863. for (var index = 0; index < this._tasks.length; index++) {
  50864. var task = this._tasks[index];
  50865. this._runTask(task);
  50866. }
  50867. return this;
  50868. };
  50869. return AssetsManager;
  50870. })();
  50871. BABYLON.AssetsManager = AssetsManager;
  50872. })(BABYLON || (BABYLON = {}));
  50873. var BABYLON;
  50874. (function (BABYLON) {
  50875. var VRCameraMetrics = (function () {
  50876. function VRCameraMetrics() {
  50877. this.compensateDistortion = true;
  50878. }
  50879. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  50880. get: function () {
  50881. return this.hResolution / (2 * this.vResolution);
  50882. },
  50883. enumerable: true,
  50884. configurable: true
  50885. });
  50886. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  50887. get: function () {
  50888. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  50889. },
  50890. enumerable: true,
  50891. configurable: true
  50892. });
  50893. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  50894. get: function () {
  50895. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50896. var h = (4 * meters) / this.hScreenSize;
  50897. return BABYLON.Matrix.Translation(h, 0, 0);
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  50903. get: function () {
  50904. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50905. var h = (4 * meters) / this.hScreenSize;
  50906. return BABYLON.Matrix.Translation(-h, 0, 0);
  50907. },
  50908. enumerable: true,
  50909. configurable: true
  50910. });
  50911. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  50912. get: function () {
  50913. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  50914. },
  50915. enumerable: true,
  50916. configurable: true
  50917. });
  50918. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  50919. get: function () {
  50920. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. VRCameraMetrics.GetDefault = function () {
  50926. var result = new VRCameraMetrics();
  50927. result.hResolution = 1280;
  50928. result.vResolution = 800;
  50929. result.hScreenSize = 0.149759993;
  50930. result.vScreenSize = 0.0935999975;
  50931. result.vScreenCenter = 0.0467999987,
  50932. result.eyeToScreenDistance = 0.0410000011;
  50933. result.lensSeparationDistance = 0.0635000020;
  50934. result.interpupillaryDistance = 0.0640000030;
  50935. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  50936. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  50937. result.postProcessScaleFactor = 1.714605507808412;
  50938. result.lensCenterOffset = 0.151976421;
  50939. return result;
  50940. };
  50941. return VRCameraMetrics;
  50942. })();
  50943. BABYLON.VRCameraMetrics = VRCameraMetrics;
  50944. })(BABYLON || (BABYLON = {}));
  50945. var BABYLON;
  50946. (function (BABYLON) {
  50947. var VRDeviceOrientationFreeCamera = (function (_super) {
  50948. __extends(VRDeviceOrientationFreeCamera, _super);
  50949. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  50950. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50951. _super.call(this, name, position, scene);
  50952. this.rotationQuaternion = new BABYLON.Quaternion();
  50953. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50954. metrics.compensateDistortion = compensateDistortion;
  50955. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50956. this.inputs.addDeviceOrientation();
  50957. }
  50958. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  50959. return "VRDeviceOrientationFreeCamera";
  50960. };
  50961. return VRDeviceOrientationFreeCamera;
  50962. })(BABYLON.FreeCamera);
  50963. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50964. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50965. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50966. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  50967. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50968. _super.call(this, name, alpha, beta, radius, target, scene);
  50969. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50970. metrics.compensateDistortion = compensateDistortion;
  50971. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50972. this.inputs.addVRDeviceOrientation();
  50973. }
  50974. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  50975. return "VRDeviceOrientationArcRotateCamera";
  50976. };
  50977. return VRDeviceOrientationArcRotateCamera;
  50978. })(BABYLON.ArcRotateCamera);
  50979. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50980. })(BABYLON || (BABYLON = {}));
  50981. var BABYLON;
  50982. (function (BABYLON) {
  50983. var WebVRFreeCamera = (function (_super) {
  50984. __extends(WebVRFreeCamera, _super);
  50985. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  50986. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50987. _super.call(this, name, position, scene);
  50988. this._hmdDevice = null;
  50989. this._sensorDevice = null;
  50990. this._cacheState = null;
  50991. this._vrEnabled = false;
  50992. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  50993. metrics.compensateDistortion = compensateDistortion;
  50994. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  50995. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  50996. this.rotationQuaternion = new BABYLON.Quaternion();
  50997. }
  50998. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  50999. var size = devices.length;
  51000. var i = 0;
  51001. // Reset devices.
  51002. this._sensorDevice = null;
  51003. this._hmdDevice = null;
  51004. // Search for a HmdDevice.
  51005. while (i < size && this._hmdDevice === null) {
  51006. if (devices[i] instanceof HMDVRDevice) {
  51007. this._hmdDevice = devices[i];
  51008. }
  51009. i++;
  51010. }
  51011. i = 0;
  51012. while (i < size && this._sensorDevice === null) {
  51013. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  51014. this._sensorDevice = devices[i];
  51015. }
  51016. i++;
  51017. }
  51018. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  51019. };
  51020. WebVRFreeCamera.prototype._checkInputs = function () {
  51021. if (this._vrEnabled) {
  51022. this._cacheState = this._sensorDevice.getState();
  51023. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  51024. //Flip in XY plane
  51025. this.rotationQuaternion.z *= -1;
  51026. this.rotationQuaternion.w *= -1;
  51027. }
  51028. _super.prototype._checkInputs.call(this);
  51029. };
  51030. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  51031. _super.prototype.attachControl.call(this, element, noPreventDefault);
  51032. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  51033. if (navigator.getVRDevices) {
  51034. navigator.getVRDevices().then(this._getWebVRDevices);
  51035. }
  51036. else if (navigator.mozGetVRDevices) {
  51037. navigator.mozGetVRDevices(this._getWebVRDevices);
  51038. }
  51039. };
  51040. WebVRFreeCamera.prototype.detachControl = function (element) {
  51041. _super.prototype.detachControl.call(this, element);
  51042. this._vrEnabled = false;
  51043. };
  51044. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  51045. if (!this._hmdDevice)
  51046. return;
  51047. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  51048. };
  51049. WebVRFreeCamera.prototype.getTypeName = function () {
  51050. return "WebVRFreeCamera";
  51051. };
  51052. return WebVRFreeCamera;
  51053. })(BABYLON.FreeCamera);
  51054. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51055. })(BABYLON || (BABYLON = {}));
  51056. var BABYLON;
  51057. (function (BABYLON) {
  51058. // Standard optimizations
  51059. var SceneOptimization = (function () {
  51060. function SceneOptimization(priority) {
  51061. if (priority === void 0) { priority = 0; }
  51062. this.priority = priority;
  51063. this.apply = function (scene) {
  51064. return true; // Return true if everything that can be done was applied
  51065. };
  51066. }
  51067. return SceneOptimization;
  51068. })();
  51069. BABYLON.SceneOptimization = SceneOptimization;
  51070. var TextureOptimization = (function (_super) {
  51071. __extends(TextureOptimization, _super);
  51072. function TextureOptimization(priority, maximumSize) {
  51073. var _this = this;
  51074. if (priority === void 0) { priority = 0; }
  51075. if (maximumSize === void 0) { maximumSize = 1024; }
  51076. _super.call(this, priority);
  51077. this.priority = priority;
  51078. this.maximumSize = maximumSize;
  51079. this.apply = function (scene) {
  51080. var allDone = true;
  51081. for (var index = 0; index < scene.textures.length; index++) {
  51082. var texture = scene.textures[index];
  51083. if (!texture.canRescale) {
  51084. continue;
  51085. }
  51086. var currentSize = texture.getSize();
  51087. var maxDimension = Math.max(currentSize.width, currentSize.height);
  51088. if (maxDimension > _this.maximumSize) {
  51089. texture.scale(0.5);
  51090. allDone = false;
  51091. }
  51092. }
  51093. return allDone;
  51094. };
  51095. }
  51096. return TextureOptimization;
  51097. })(SceneOptimization);
  51098. BABYLON.TextureOptimization = TextureOptimization;
  51099. var HardwareScalingOptimization = (function (_super) {
  51100. __extends(HardwareScalingOptimization, _super);
  51101. function HardwareScalingOptimization(priority, maximumScale) {
  51102. var _this = this;
  51103. if (priority === void 0) { priority = 0; }
  51104. if (maximumScale === void 0) { maximumScale = 2; }
  51105. _super.call(this, priority);
  51106. this.priority = priority;
  51107. this.maximumScale = maximumScale;
  51108. this._currentScale = 1;
  51109. this.apply = function (scene) {
  51110. _this._currentScale++;
  51111. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  51112. return _this._currentScale >= _this.maximumScale;
  51113. };
  51114. }
  51115. return HardwareScalingOptimization;
  51116. })(SceneOptimization);
  51117. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  51118. var ShadowsOptimization = (function (_super) {
  51119. __extends(ShadowsOptimization, _super);
  51120. function ShadowsOptimization() {
  51121. _super.apply(this, arguments);
  51122. this.apply = function (scene) {
  51123. scene.shadowsEnabled = false;
  51124. return true;
  51125. };
  51126. }
  51127. return ShadowsOptimization;
  51128. })(SceneOptimization);
  51129. BABYLON.ShadowsOptimization = ShadowsOptimization;
  51130. var PostProcessesOptimization = (function (_super) {
  51131. __extends(PostProcessesOptimization, _super);
  51132. function PostProcessesOptimization() {
  51133. _super.apply(this, arguments);
  51134. this.apply = function (scene) {
  51135. scene.postProcessesEnabled = false;
  51136. return true;
  51137. };
  51138. }
  51139. return PostProcessesOptimization;
  51140. })(SceneOptimization);
  51141. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  51142. var LensFlaresOptimization = (function (_super) {
  51143. __extends(LensFlaresOptimization, _super);
  51144. function LensFlaresOptimization() {
  51145. _super.apply(this, arguments);
  51146. this.apply = function (scene) {
  51147. scene.lensFlaresEnabled = false;
  51148. return true;
  51149. };
  51150. }
  51151. return LensFlaresOptimization;
  51152. })(SceneOptimization);
  51153. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  51154. var ParticlesOptimization = (function (_super) {
  51155. __extends(ParticlesOptimization, _super);
  51156. function ParticlesOptimization() {
  51157. _super.apply(this, arguments);
  51158. this.apply = function (scene) {
  51159. scene.particlesEnabled = false;
  51160. return true;
  51161. };
  51162. }
  51163. return ParticlesOptimization;
  51164. })(SceneOptimization);
  51165. BABYLON.ParticlesOptimization = ParticlesOptimization;
  51166. var RenderTargetsOptimization = (function (_super) {
  51167. __extends(RenderTargetsOptimization, _super);
  51168. function RenderTargetsOptimization() {
  51169. _super.apply(this, arguments);
  51170. this.apply = function (scene) {
  51171. scene.renderTargetsEnabled = false;
  51172. return true;
  51173. };
  51174. }
  51175. return RenderTargetsOptimization;
  51176. })(SceneOptimization);
  51177. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  51178. var MergeMeshesOptimization = (function (_super) {
  51179. __extends(MergeMeshesOptimization, _super);
  51180. function MergeMeshesOptimization() {
  51181. var _this = this;
  51182. _super.apply(this, arguments);
  51183. this._canBeMerged = function (abstractMesh) {
  51184. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  51185. return false;
  51186. }
  51187. var mesh = abstractMesh;
  51188. if (!mesh.isVisible || !mesh.isEnabled()) {
  51189. return false;
  51190. }
  51191. if (mesh.instances.length > 0) {
  51192. return false;
  51193. }
  51194. if (mesh.skeleton || mesh.hasLODLevels) {
  51195. return false;
  51196. }
  51197. if (mesh.parent) {
  51198. return false;
  51199. }
  51200. return true;
  51201. };
  51202. this.apply = function (scene, updateSelectionTree) {
  51203. var globalPool = scene.meshes.slice(0);
  51204. var globalLength = globalPool.length;
  51205. for (var index = 0; index < globalLength; index++) {
  51206. var currentPool = new Array();
  51207. var current = globalPool[index];
  51208. // Checks
  51209. if (!_this._canBeMerged(current)) {
  51210. continue;
  51211. }
  51212. currentPool.push(current);
  51213. // Find compatible meshes
  51214. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  51215. var otherMesh = globalPool[subIndex];
  51216. if (!_this._canBeMerged(otherMesh)) {
  51217. continue;
  51218. }
  51219. if (otherMesh.material !== current.material) {
  51220. continue;
  51221. }
  51222. if (otherMesh.checkCollisions !== current.checkCollisions) {
  51223. continue;
  51224. }
  51225. currentPool.push(otherMesh);
  51226. globalLength--;
  51227. globalPool.splice(subIndex, 1);
  51228. subIndex--;
  51229. }
  51230. if (currentPool.length < 2) {
  51231. continue;
  51232. }
  51233. // Merge meshes
  51234. BABYLON.Mesh.MergeMeshes(currentPool);
  51235. }
  51236. if (updateSelectionTree != undefined) {
  51237. if (updateSelectionTree) {
  51238. scene.createOrUpdateSelectionOctree();
  51239. }
  51240. }
  51241. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  51242. scene.createOrUpdateSelectionOctree();
  51243. }
  51244. return true;
  51245. };
  51246. }
  51247. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51248. get: function () {
  51249. return MergeMeshesOptimization._UpdateSelectionTree;
  51250. },
  51251. set: function (value) {
  51252. MergeMeshesOptimization._UpdateSelectionTree = value;
  51253. },
  51254. enumerable: true,
  51255. configurable: true
  51256. });
  51257. MergeMeshesOptimization._UpdateSelectionTree = false;
  51258. return MergeMeshesOptimization;
  51259. })(SceneOptimization);
  51260. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51261. // Options
  51262. var SceneOptimizerOptions = (function () {
  51263. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51264. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51265. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51266. this.targetFrameRate = targetFrameRate;
  51267. this.trackerDuration = trackerDuration;
  51268. this.optimizations = new Array();
  51269. }
  51270. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51271. var result = new SceneOptimizerOptions(targetFrameRate);
  51272. var priority = 0;
  51273. result.optimizations.push(new MergeMeshesOptimization(priority));
  51274. result.optimizations.push(new ShadowsOptimization(priority));
  51275. result.optimizations.push(new LensFlaresOptimization(priority));
  51276. // Next priority
  51277. priority++;
  51278. result.optimizations.push(new PostProcessesOptimization(priority));
  51279. result.optimizations.push(new ParticlesOptimization(priority));
  51280. // Next priority
  51281. priority++;
  51282. result.optimizations.push(new TextureOptimization(priority, 1024));
  51283. return result;
  51284. };
  51285. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51286. var result = new SceneOptimizerOptions(targetFrameRate);
  51287. var priority = 0;
  51288. result.optimizations.push(new MergeMeshesOptimization(priority));
  51289. result.optimizations.push(new ShadowsOptimization(priority));
  51290. result.optimizations.push(new LensFlaresOptimization(priority));
  51291. // Next priority
  51292. priority++;
  51293. result.optimizations.push(new PostProcessesOptimization(priority));
  51294. result.optimizations.push(new ParticlesOptimization(priority));
  51295. // Next priority
  51296. priority++;
  51297. result.optimizations.push(new TextureOptimization(priority, 512));
  51298. // Next priority
  51299. priority++;
  51300. result.optimizations.push(new RenderTargetsOptimization(priority));
  51301. // Next priority
  51302. priority++;
  51303. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51304. return result;
  51305. };
  51306. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51307. var result = new SceneOptimizerOptions(targetFrameRate);
  51308. var priority = 0;
  51309. result.optimizations.push(new MergeMeshesOptimization(priority));
  51310. result.optimizations.push(new ShadowsOptimization(priority));
  51311. result.optimizations.push(new LensFlaresOptimization(priority));
  51312. // Next priority
  51313. priority++;
  51314. result.optimizations.push(new PostProcessesOptimization(priority));
  51315. result.optimizations.push(new ParticlesOptimization(priority));
  51316. // Next priority
  51317. priority++;
  51318. result.optimizations.push(new TextureOptimization(priority, 256));
  51319. // Next priority
  51320. priority++;
  51321. result.optimizations.push(new RenderTargetsOptimization(priority));
  51322. // Next priority
  51323. priority++;
  51324. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51325. return result;
  51326. };
  51327. return SceneOptimizerOptions;
  51328. })();
  51329. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51330. // Scene optimizer tool
  51331. var SceneOptimizer = (function () {
  51332. function SceneOptimizer() {
  51333. }
  51334. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51335. // TODO: add an epsilon
  51336. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51337. if (onSuccess) {
  51338. onSuccess();
  51339. }
  51340. return;
  51341. }
  51342. // Apply current level of optimizations
  51343. var allDone = true;
  51344. var noOptimizationApplied = true;
  51345. for (var index = 0; index < options.optimizations.length; index++) {
  51346. var optimization = options.optimizations[index];
  51347. if (optimization.priority === currentPriorityLevel) {
  51348. noOptimizationApplied = false;
  51349. allDone = allDone && optimization.apply(scene);
  51350. }
  51351. }
  51352. // If no optimization was applied, this is a failure :(
  51353. if (noOptimizationApplied) {
  51354. if (onFailure) {
  51355. onFailure();
  51356. }
  51357. return;
  51358. }
  51359. // If all optimizations were done, move to next level
  51360. if (allDone) {
  51361. currentPriorityLevel++;
  51362. }
  51363. // Let's the system running for a specific amount of time before checking FPS
  51364. scene.executeWhenReady(function () {
  51365. setTimeout(function () {
  51366. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51367. }, options.trackerDuration);
  51368. });
  51369. };
  51370. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51371. if (!options) {
  51372. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51373. }
  51374. // Let's the system running for a specific amount of time before checking FPS
  51375. scene.executeWhenReady(function () {
  51376. setTimeout(function () {
  51377. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51378. }, options.trackerDuration);
  51379. });
  51380. };
  51381. return SceneOptimizer;
  51382. })();
  51383. BABYLON.SceneOptimizer = SceneOptimizer;
  51384. })(BABYLON || (BABYLON = {}));
  51385. var BABYLON;
  51386. (function (BABYLON) {
  51387. var Internals;
  51388. (function (Internals) {
  51389. var MeshLODLevel = (function () {
  51390. function MeshLODLevel(distance, mesh) {
  51391. this.distance = distance;
  51392. this.mesh = mesh;
  51393. }
  51394. return MeshLODLevel;
  51395. })();
  51396. Internals.MeshLODLevel = MeshLODLevel;
  51397. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51398. })(BABYLON || (BABYLON = {}));
  51399. var BABYLON;
  51400. (function (BABYLON) {
  51401. var RawTexture = (function (_super) {
  51402. __extends(RawTexture, _super);
  51403. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51405. if (invertY === void 0) { invertY = false; }
  51406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51407. _super.call(this, null, scene, !generateMipMaps, invertY);
  51408. this.format = format;
  51409. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51410. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51411. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51412. }
  51413. RawTexture.prototype.update = function (data) {
  51414. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51415. };
  51416. // Statics
  51417. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51418. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51419. if (invertY === void 0) { invertY = false; }
  51420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51421. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51422. };
  51423. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51424. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51425. if (invertY === void 0) { invertY = false; }
  51426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51427. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51428. };
  51429. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51430. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51431. if (invertY === void 0) { invertY = false; }
  51432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51433. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51434. };
  51435. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51437. if (invertY === void 0) { invertY = false; }
  51438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51439. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51440. };
  51441. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51442. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51443. if (invertY === void 0) { invertY = false; }
  51444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51445. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51446. };
  51447. return RawTexture;
  51448. })(BABYLON.Texture);
  51449. BABYLON.RawTexture = RawTexture;
  51450. })(BABYLON || (BABYLON = {}));
  51451. var BABYLON;
  51452. (function (BABYLON) {
  51453. var IndexedVector2 = (function (_super) {
  51454. __extends(IndexedVector2, _super);
  51455. function IndexedVector2(original, index) {
  51456. _super.call(this, original.x, original.y);
  51457. this.index = index;
  51458. }
  51459. return IndexedVector2;
  51460. })(BABYLON.Vector2);
  51461. var PolygonPoints = (function () {
  51462. function PolygonPoints() {
  51463. this.elements = new Array();
  51464. }
  51465. PolygonPoints.prototype.add = function (originalPoints) {
  51466. var _this = this;
  51467. var result = new Array();
  51468. originalPoints.forEach(function (point) {
  51469. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51470. var newPoint = new IndexedVector2(point, _this.elements.length);
  51471. result.push(newPoint);
  51472. _this.elements.push(newPoint);
  51473. }
  51474. });
  51475. return result;
  51476. };
  51477. PolygonPoints.prototype.computeBounds = function () {
  51478. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51479. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51480. this.elements.forEach(function (point) {
  51481. // x
  51482. if (point.x < lmin.x) {
  51483. lmin.x = point.x;
  51484. }
  51485. else if (point.x > lmax.x) {
  51486. lmax.x = point.x;
  51487. }
  51488. // y
  51489. if (point.y < lmin.y) {
  51490. lmin.y = point.y;
  51491. }
  51492. else if (point.y > lmax.y) {
  51493. lmax.y = point.y;
  51494. }
  51495. });
  51496. return {
  51497. min: lmin,
  51498. max: lmax,
  51499. width: lmax.x - lmin.x,
  51500. height: lmax.y - lmin.y
  51501. };
  51502. };
  51503. return PolygonPoints;
  51504. })();
  51505. var Polygon = (function () {
  51506. function Polygon() {
  51507. }
  51508. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51509. return [
  51510. new BABYLON.Vector2(xmin, ymin),
  51511. new BABYLON.Vector2(xmax, ymin),
  51512. new BABYLON.Vector2(xmax, ymax),
  51513. new BABYLON.Vector2(xmin, ymax)
  51514. ];
  51515. };
  51516. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51517. if (cx === void 0) { cx = 0; }
  51518. if (cy === void 0) { cy = 0; }
  51519. if (numberOfSides === void 0) { numberOfSides = 32; }
  51520. var result = new Array();
  51521. var angle = 0;
  51522. var increment = (Math.PI * 2) / numberOfSides;
  51523. for (var i = 0; i < numberOfSides; i++) {
  51524. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51525. angle -= increment;
  51526. }
  51527. return result;
  51528. };
  51529. Polygon.Parse = function (input) {
  51530. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51531. var i, result = [];
  51532. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51533. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51534. }
  51535. return result;
  51536. };
  51537. Polygon.StartingAt = function (x, y) {
  51538. return BABYLON.Path2.StartingAt(x, y);
  51539. };
  51540. return Polygon;
  51541. })();
  51542. BABYLON.Polygon = Polygon;
  51543. var PolygonMeshBuilder = (function () {
  51544. function PolygonMeshBuilder(name, contours, scene) {
  51545. this._points = new PolygonPoints();
  51546. this._outlinepoints = new PolygonPoints();
  51547. this._holes = [];
  51548. this._epoints = new Array();
  51549. this._eholes = new Array();
  51550. this._name = name;
  51551. this._scene = scene;
  51552. var points;
  51553. if (contours instanceof BABYLON.Path2) {
  51554. points = contours.getPoints();
  51555. }
  51556. else {
  51557. points = contours;
  51558. }
  51559. this._addToepoint(points);
  51560. this._points.add(points);
  51561. this._outlinepoints.add(points);
  51562. }
  51563. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51564. for (var _i = 0; _i < points.length; _i++) {
  51565. var p = points[_i];
  51566. this._epoints.push(p.x, p.y);
  51567. }
  51568. };
  51569. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51570. this._points.add(hole);
  51571. var holepoints = new PolygonPoints();
  51572. holepoints.add(hole);
  51573. this._holes.push(holepoints);
  51574. this._eholes.push(this._epoints.length / 2);
  51575. this._addToepoint(hole);
  51576. return this;
  51577. };
  51578. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51579. var _this = this;
  51580. if (updatable === void 0) { updatable = false; }
  51581. var result = new BABYLON.Mesh(this._name, this._scene);
  51582. var normals = [];
  51583. var positions = [];
  51584. var uvs = [];
  51585. var bounds = this._points.computeBounds();
  51586. this._points.elements.forEach(function (p) {
  51587. normals.push(0, 1.0, 0);
  51588. positions.push(p.x, 0, p.y);
  51589. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51590. });
  51591. var indices = [];
  51592. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51593. for (var i = 0; i < res.length; i++) {
  51594. indices.push(res[i]);
  51595. }
  51596. if (depth > 0) {
  51597. var positionscount = (positions.length / 3); //get the current pointcount
  51598. this._points.elements.forEach(function (p) {
  51599. normals.push(0, -1.0, 0);
  51600. positions.push(p.x, -depth, p.y);
  51601. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51602. });
  51603. var totalCount = indices.length;
  51604. for (var i = 0; i < totalCount; i += 3) {
  51605. var i0 = indices[i + 0];
  51606. var i1 = indices[i + 1];
  51607. var i2 = indices[i + 2];
  51608. indices.push(i2 + positionscount);
  51609. indices.push(i1 + positionscount);
  51610. indices.push(i0 + positionscount);
  51611. }
  51612. //Add the sides
  51613. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51614. this._holes.forEach(function (hole) {
  51615. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51616. });
  51617. }
  51618. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51619. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51620. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51621. result.setIndices(indices);
  51622. return result;
  51623. };
  51624. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51625. var StartIndex = positions.length / 3;
  51626. var ulength = 0;
  51627. for (var i = 0; i < points.elements.length; i++) {
  51628. var p = points.elements[i];
  51629. var p1;
  51630. if ((i + 1) > points.elements.length - 1) {
  51631. p1 = points.elements[0];
  51632. }
  51633. else {
  51634. p1 = points.elements[i + 1];
  51635. }
  51636. positions.push(p.x, 0, p.y);
  51637. positions.push(p.x, -depth, p.y);
  51638. positions.push(p1.x, 0, p1.y);
  51639. positions.push(p1.x, -depth, p1.y);
  51640. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51641. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51642. var v3 = v2.subtract(v1);
  51643. var v4 = new BABYLON.Vector3(0, 1, 0);
  51644. var vn = BABYLON.Vector3.Cross(v3, v4);
  51645. vn = vn.normalize();
  51646. uvs.push(ulength / bounds.width, 0);
  51647. uvs.push(ulength / bounds.width, 1);
  51648. ulength += v3.length();
  51649. uvs.push((ulength / bounds.width), 0);
  51650. uvs.push((ulength / bounds.width), 1);
  51651. if (!flip) {
  51652. normals.push(-vn.x, -vn.y, -vn.z);
  51653. normals.push(-vn.x, -vn.y, -vn.z);
  51654. normals.push(-vn.x, -vn.y, -vn.z);
  51655. normals.push(-vn.x, -vn.y, -vn.z);
  51656. indices.push(StartIndex);
  51657. indices.push(StartIndex + 1);
  51658. indices.push(StartIndex + 2);
  51659. indices.push(StartIndex + 1);
  51660. indices.push(StartIndex + 3);
  51661. indices.push(StartIndex + 2);
  51662. }
  51663. else {
  51664. normals.push(vn.x, vn.y, vn.z);
  51665. normals.push(vn.x, vn.y, vn.z);
  51666. normals.push(vn.x, vn.y, vn.z);
  51667. normals.push(vn.x, vn.y, vn.z);
  51668. indices.push(StartIndex);
  51669. indices.push(StartIndex + 2);
  51670. indices.push(StartIndex + 1);
  51671. indices.push(StartIndex + 1);
  51672. indices.push(StartIndex + 2);
  51673. indices.push(StartIndex + 3);
  51674. }
  51675. StartIndex += 4;
  51676. }
  51677. ;
  51678. };
  51679. return PolygonMeshBuilder;
  51680. })();
  51681. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51682. })(BABYLON || (BABYLON = {}));
  51683. var BABYLON;
  51684. (function (BABYLON) {
  51685. var Octree = (function () {
  51686. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51687. if (maxDepth === void 0) { maxDepth = 2; }
  51688. this.maxDepth = maxDepth;
  51689. this.dynamicContent = new Array();
  51690. this._maxBlockCapacity = maxBlockCapacity || 64;
  51691. this._selectionContent = new BABYLON.SmartArray(1024);
  51692. this._creationFunc = creationFunc;
  51693. }
  51694. // Methods
  51695. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51696. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51697. };
  51698. Octree.prototype.addMesh = function (entry) {
  51699. for (var index = 0; index < this.blocks.length; index++) {
  51700. var block = this.blocks[index];
  51701. block.addEntry(entry);
  51702. }
  51703. };
  51704. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51705. this._selectionContent.reset();
  51706. for (var index = 0; index < this.blocks.length; index++) {
  51707. var block = this.blocks[index];
  51708. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51709. }
  51710. if (allowDuplicate) {
  51711. this._selectionContent.concat(this.dynamicContent);
  51712. }
  51713. else {
  51714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51715. }
  51716. return this._selectionContent;
  51717. };
  51718. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51719. this._selectionContent.reset();
  51720. for (var index = 0; index < this.blocks.length; index++) {
  51721. var block = this.blocks[index];
  51722. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51723. }
  51724. if (allowDuplicate) {
  51725. this._selectionContent.concat(this.dynamicContent);
  51726. }
  51727. else {
  51728. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51729. }
  51730. return this._selectionContent;
  51731. };
  51732. Octree.prototype.intersectsRay = function (ray) {
  51733. this._selectionContent.reset();
  51734. for (var index = 0; index < this.blocks.length; index++) {
  51735. var block = this.blocks[index];
  51736. block.intersectsRay(ray, this._selectionContent);
  51737. }
  51738. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51739. return this._selectionContent;
  51740. };
  51741. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51742. target.blocks = new Array();
  51743. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51744. // Segmenting space
  51745. for (var x = 0; x < 2; x++) {
  51746. for (var y = 0; y < 2; y++) {
  51747. for (var z = 0; z < 2; z++) {
  51748. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51749. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51750. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51751. block.addEntries(entries);
  51752. target.blocks.push(block);
  51753. }
  51754. }
  51755. }
  51756. };
  51757. Octree.CreationFuncForMeshes = function (entry, block) {
  51758. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51759. block.entries.push(entry);
  51760. }
  51761. };
  51762. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51763. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51764. block.entries.push(entry);
  51765. }
  51766. };
  51767. return Octree;
  51768. })();
  51769. BABYLON.Octree = Octree;
  51770. })(BABYLON || (BABYLON = {}));
  51771. var BABYLON;
  51772. (function (BABYLON) {
  51773. var OctreeBlock = (function () {
  51774. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51775. this.entries = new Array();
  51776. this._boundingVectors = new Array();
  51777. this._capacity = capacity;
  51778. this._depth = depth;
  51779. this._maxDepth = maxDepth;
  51780. this._creationFunc = creationFunc;
  51781. this._minPoint = minPoint;
  51782. this._maxPoint = maxPoint;
  51783. this._boundingVectors.push(minPoint.clone());
  51784. this._boundingVectors.push(maxPoint.clone());
  51785. this._boundingVectors.push(minPoint.clone());
  51786. this._boundingVectors[2].x = maxPoint.x;
  51787. this._boundingVectors.push(minPoint.clone());
  51788. this._boundingVectors[3].y = maxPoint.y;
  51789. this._boundingVectors.push(minPoint.clone());
  51790. this._boundingVectors[4].z = maxPoint.z;
  51791. this._boundingVectors.push(maxPoint.clone());
  51792. this._boundingVectors[5].z = minPoint.z;
  51793. this._boundingVectors.push(maxPoint.clone());
  51794. this._boundingVectors[6].x = minPoint.x;
  51795. this._boundingVectors.push(maxPoint.clone());
  51796. this._boundingVectors[7].y = minPoint.y;
  51797. }
  51798. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  51799. // Property
  51800. get: function () {
  51801. return this._capacity;
  51802. },
  51803. enumerable: true,
  51804. configurable: true
  51805. });
  51806. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  51807. get: function () {
  51808. return this._minPoint;
  51809. },
  51810. enumerable: true,
  51811. configurable: true
  51812. });
  51813. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  51814. get: function () {
  51815. return this._maxPoint;
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. // Methods
  51821. OctreeBlock.prototype.addEntry = function (entry) {
  51822. if (this.blocks) {
  51823. for (var index = 0; index < this.blocks.length; index++) {
  51824. var block = this.blocks[index];
  51825. block.addEntry(entry);
  51826. }
  51827. return;
  51828. }
  51829. this._creationFunc(entry, this);
  51830. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  51831. this.createInnerBlocks();
  51832. }
  51833. };
  51834. OctreeBlock.prototype.addEntries = function (entries) {
  51835. for (var index = 0; index < entries.length; index++) {
  51836. var mesh = entries[index];
  51837. this.addEntry(mesh);
  51838. }
  51839. };
  51840. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  51841. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  51842. if (this.blocks) {
  51843. for (var index = 0; index < this.blocks.length; index++) {
  51844. var block = this.blocks[index];
  51845. block.select(frustumPlanes, selection, allowDuplicate);
  51846. }
  51847. return;
  51848. }
  51849. if (allowDuplicate) {
  51850. selection.concat(this.entries);
  51851. }
  51852. else {
  51853. selection.concatWithNoDuplicate(this.entries);
  51854. }
  51855. }
  51856. };
  51857. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  51858. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  51859. if (this.blocks) {
  51860. for (var index = 0; index < this.blocks.length; index++) {
  51861. var block = this.blocks[index];
  51862. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  51863. }
  51864. return;
  51865. }
  51866. if (allowDuplicate) {
  51867. selection.concat(this.entries);
  51868. }
  51869. else {
  51870. selection.concatWithNoDuplicate(this.entries);
  51871. }
  51872. }
  51873. };
  51874. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  51875. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  51876. if (this.blocks) {
  51877. for (var index = 0; index < this.blocks.length; index++) {
  51878. var block = this.blocks[index];
  51879. block.intersectsRay(ray, selection);
  51880. }
  51881. return;
  51882. }
  51883. selection.concatWithNoDuplicate(this.entries);
  51884. }
  51885. };
  51886. OctreeBlock.prototype.createInnerBlocks = function () {
  51887. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  51888. };
  51889. return OctreeBlock;
  51890. })();
  51891. BABYLON.OctreeBlock = OctreeBlock;
  51892. })(BABYLON || (BABYLON = {}));
  51893. var BABYLON;
  51894. (function (BABYLON) {
  51895. var BlurPostProcess = (function (_super) {
  51896. __extends(BlurPostProcess, _super);
  51897. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  51898. var _this = this;
  51899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51900. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  51901. this.direction = direction;
  51902. this.blurWidth = blurWidth;
  51903. this.onApplyObservable.add(function (effect) {
  51904. effect.setFloat2("screenSize", _this.width, _this.height);
  51905. effect.setVector2("direction", _this.direction);
  51906. effect.setFloat("blurWidth", _this.blurWidth);
  51907. });
  51908. }
  51909. return BlurPostProcess;
  51910. })(BABYLON.PostProcess);
  51911. BABYLON.BlurPostProcess = BlurPostProcess;
  51912. })(BABYLON || (BABYLON = {}));
  51913. var BABYLON;
  51914. (function (BABYLON) {
  51915. var RefractionPostProcess = (function (_super) {
  51916. __extends(RefractionPostProcess, _super);
  51917. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51918. var _this = this;
  51919. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  51920. this.color = color;
  51921. this.depth = depth;
  51922. this.colorLevel = colorLevel;
  51923. this.onActivateObservable.add(function (cam) {
  51924. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51925. });
  51926. this.onApplyObservable.add(function (effect) {
  51927. effect.setColor3("baseColor", _this.color);
  51928. effect.setFloat("depth", _this.depth);
  51929. effect.setFloat("colorLevel", _this.colorLevel);
  51930. effect.setTexture("refractionSampler", _this._refRexture);
  51931. });
  51932. }
  51933. // Methods
  51934. RefractionPostProcess.prototype.dispose = function (camera) {
  51935. if (this._refRexture) {
  51936. this._refRexture.dispose();
  51937. }
  51938. _super.prototype.dispose.call(this, camera);
  51939. };
  51940. return RefractionPostProcess;
  51941. })(BABYLON.PostProcess);
  51942. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51943. })(BABYLON || (BABYLON = {}));
  51944. var BABYLON;
  51945. (function (BABYLON) {
  51946. var BlackAndWhitePostProcess = (function (_super) {
  51947. __extends(BlackAndWhitePostProcess, _super);
  51948. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51949. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  51950. }
  51951. return BlackAndWhitePostProcess;
  51952. })(BABYLON.PostProcess);
  51953. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51954. })(BABYLON || (BABYLON = {}));
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. var ConvolutionPostProcess = (function (_super) {
  51958. __extends(ConvolutionPostProcess, _super);
  51959. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51960. var _this = this;
  51961. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  51962. this.kernel = kernel;
  51963. this.onApply = function (effect) {
  51964. effect.setFloat2("screenSize", _this.width, _this.height);
  51965. effect.setArray("kernel", _this.kernel);
  51966. };
  51967. }
  51968. // Statics
  51969. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51970. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51971. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51972. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51973. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51974. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51975. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51976. return ConvolutionPostProcess;
  51977. })(BABYLON.PostProcess);
  51978. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51979. })(BABYLON || (BABYLON = {}));
  51980. var BABYLON;
  51981. (function (BABYLON) {
  51982. var FilterPostProcess = (function (_super) {
  51983. __extends(FilterPostProcess, _super);
  51984. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51985. var _this = this;
  51986. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  51987. this.kernelMatrix = kernelMatrix;
  51988. this.onApply = function (effect) {
  51989. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51990. };
  51991. }
  51992. return FilterPostProcess;
  51993. })(BABYLON.PostProcess);
  51994. BABYLON.FilterPostProcess = FilterPostProcess;
  51995. })(BABYLON || (BABYLON = {}));
  51996. var BABYLON;
  51997. (function (BABYLON) {
  51998. var FxaaPostProcess = (function (_super) {
  51999. __extends(FxaaPostProcess, _super);
  52000. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52001. var _this = this;
  52002. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  52003. this.onSizeChangedObservable.add(function () {
  52004. _this.texelWidth = 1.0 / _this.width;
  52005. _this.texelHeight = 1.0 / _this.height;
  52006. });
  52007. this.onApplyObservable.add(function (effect) {
  52008. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52009. });
  52010. }
  52011. return FxaaPostProcess;
  52012. })(BABYLON.PostProcess);
  52013. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52014. })(BABYLON || (BABYLON = {}));
  52015. var BABYLON;
  52016. (function (BABYLON) {
  52017. var StereoscopicInterlacePostProcess = (function (_super) {
  52018. __extends(StereoscopicInterlacePostProcess, _super);
  52019. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52020. var _this = this;
  52021. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  52022. this._passedProcess = rigCameras[0]._rigPostProcess;
  52023. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  52024. this.onSizeChangedObservable.add(function () {
  52025. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52026. });
  52027. this.onApplyObservable.add(function (effect) {
  52028. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52029. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52030. });
  52031. }
  52032. return StereoscopicInterlacePostProcess;
  52033. })(BABYLON.PostProcess);
  52034. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52035. })(BABYLON || (BABYLON = {}));
  52036. var BABYLON;
  52037. (function (BABYLON) {
  52038. var LensFlare = (function () {
  52039. function LensFlare(size, position, color, imgUrl, system) {
  52040. this.size = size;
  52041. this.position = position;
  52042. this.dispose = function () {
  52043. if (this.texture) {
  52044. this.texture.dispose();
  52045. }
  52046. // Remove from scene
  52047. var index = this._system.lensFlares.indexOf(this);
  52048. this._system.lensFlares.splice(index, 1);
  52049. };
  52050. this.color = color || new BABYLON.Color3(1, 1, 1);
  52051. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52052. this._system = system;
  52053. system.lensFlares.push(this);
  52054. }
  52055. return LensFlare;
  52056. })();
  52057. BABYLON.LensFlare = LensFlare;
  52058. })(BABYLON || (BABYLON = {}));
  52059. var BABYLON;
  52060. (function (BABYLON) {
  52061. var LensFlareSystem = (function () {
  52062. function LensFlareSystem(name, emitter, scene) {
  52063. this.name = name;
  52064. this.lensFlares = new Array();
  52065. this.borderLimit = 300;
  52066. this.layerMask = 0x0FFFFFFF;
  52067. this._vertexBuffers = {};
  52068. this._isEnabled = true;
  52069. this._scene = scene;
  52070. this._emitter = emitter;
  52071. this.id = name;
  52072. scene.lensFlareSystems.push(this);
  52073. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52074. var engine = scene.getEngine();
  52075. // VBO
  52076. var vertices = [];
  52077. vertices.push(1, 1);
  52078. vertices.push(-1, 1);
  52079. vertices.push(-1, -1);
  52080. vertices.push(1, -1);
  52081. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52082. // Indices
  52083. var indices = [];
  52084. indices.push(0);
  52085. indices.push(1);
  52086. indices.push(2);
  52087. indices.push(0);
  52088. indices.push(2);
  52089. indices.push(3);
  52090. this._indexBuffer = engine.createIndexBuffer(indices);
  52091. // Effects
  52092. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52093. }
  52094. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52095. get: function () {
  52096. return this._isEnabled;
  52097. },
  52098. set: function (value) {
  52099. this._isEnabled = value;
  52100. },
  52101. enumerable: true,
  52102. configurable: true
  52103. });
  52104. LensFlareSystem.prototype.getScene = function () {
  52105. return this._scene;
  52106. };
  52107. LensFlareSystem.prototype.getEmitter = function () {
  52108. return this._emitter;
  52109. };
  52110. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52111. this._emitter = newEmitter;
  52112. };
  52113. LensFlareSystem.prototype.getEmitterPosition = function () {
  52114. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52115. };
  52116. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52117. var position = this.getEmitterPosition();
  52118. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52119. this._positionX = position.x;
  52120. this._positionY = position.y;
  52121. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52122. if (position.z > 0) {
  52123. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52124. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52125. return true;
  52126. }
  52127. }
  52128. return false;
  52129. };
  52130. LensFlareSystem.prototype._isVisible = function () {
  52131. if (!this._isEnabled) {
  52132. return false;
  52133. }
  52134. var emitterPosition = this.getEmitterPosition();
  52135. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  52136. var distance = direction.length();
  52137. direction.normalize();
  52138. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  52139. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52140. return !pickInfo.hit || pickInfo.distance > distance;
  52141. };
  52142. LensFlareSystem.prototype.render = function () {
  52143. if (!this._effect.isReady())
  52144. return false;
  52145. var engine = this._scene.getEngine();
  52146. var viewport = this._scene.activeCamera.viewport;
  52147. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52148. // Position
  52149. if (!this.computeEffectivePosition(globalViewport)) {
  52150. return false;
  52151. }
  52152. // Visibility
  52153. if (!this._isVisible()) {
  52154. return false;
  52155. }
  52156. // Intensity
  52157. var awayX;
  52158. var awayY;
  52159. if (this._positionX < this.borderLimit + globalViewport.x) {
  52160. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52161. }
  52162. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52163. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52164. }
  52165. else {
  52166. awayX = 0;
  52167. }
  52168. if (this._positionY < this.borderLimit + globalViewport.y) {
  52169. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52170. }
  52171. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52172. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52173. }
  52174. else {
  52175. awayY = 0;
  52176. }
  52177. var away = (awayX > awayY) ? awayX : awayY;
  52178. if (away > this.borderLimit) {
  52179. away = this.borderLimit;
  52180. }
  52181. var intensity = 1.0 - (away / this.borderLimit);
  52182. if (intensity < 0) {
  52183. return false;
  52184. }
  52185. if (intensity > 1.0) {
  52186. intensity = 1.0;
  52187. }
  52188. // Position
  52189. var centerX = globalViewport.x + globalViewport.width / 2;
  52190. var centerY = globalViewport.y + globalViewport.height / 2;
  52191. var distX = centerX - this._positionX;
  52192. var distY = centerY - this._positionY;
  52193. // Effects
  52194. engine.enableEffect(this._effect);
  52195. engine.setState(false);
  52196. engine.setDepthBuffer(false);
  52197. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52198. // VBOs
  52199. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52200. // Flares
  52201. for (var index = 0; index < this.lensFlares.length; index++) {
  52202. var flare = this.lensFlares[index];
  52203. var x = centerX - (distX * flare.position);
  52204. var y = centerY - (distY * flare.position);
  52205. var cw = flare.size;
  52206. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52207. var cx = 2 * (x / globalViewport.width) - 1.0;
  52208. var cy = 1.0 - 2 * (y / globalViewport.height);
  52209. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52210. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52211. // Texture
  52212. this._effect.setTexture("textureSampler", flare.texture);
  52213. // Color
  52214. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52215. // Draw order
  52216. engine.draw(true, 0, 6);
  52217. }
  52218. engine.setDepthBuffer(true);
  52219. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52220. return true;
  52221. };
  52222. LensFlareSystem.prototype.dispose = function () {
  52223. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52224. if (vertexBuffer) {
  52225. vertexBuffer.dispose();
  52226. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52227. }
  52228. if (this._indexBuffer) {
  52229. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52230. this._indexBuffer = null;
  52231. }
  52232. while (this.lensFlares.length) {
  52233. this.lensFlares[0].dispose();
  52234. }
  52235. // Remove from scene
  52236. var index = this._scene.lensFlareSystems.indexOf(this);
  52237. this._scene.lensFlareSystems.splice(index, 1);
  52238. };
  52239. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52240. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52241. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52242. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52243. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52244. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52245. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52246. var parsedFlare = parsedLensFlareSystem.flares[index];
  52247. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52248. }
  52249. return lensFlareSystem;
  52250. };
  52251. LensFlareSystem.prototype.serialize = function () {
  52252. var serializationObject = {};
  52253. serializationObject.id = this.id;
  52254. serializationObject.name = this.name;
  52255. serializationObject.emitterId = this.getEmitter().id;
  52256. serializationObject.borderLimit = this.borderLimit;
  52257. serializationObject.flares = [];
  52258. for (var index = 0; index < this.lensFlares.length; index++) {
  52259. var flare = this.lensFlares[index];
  52260. serializationObject.flares.push({
  52261. size: flare.size,
  52262. position: flare.position,
  52263. color: flare.color.asArray(),
  52264. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52265. });
  52266. }
  52267. return serializationObject;
  52268. };
  52269. return LensFlareSystem;
  52270. })();
  52271. BABYLON.LensFlareSystem = LensFlareSystem;
  52272. })(BABYLON || (BABYLON = {}));
  52273. var BABYLON;
  52274. (function (BABYLON) {
  52275. // We're mainly based on the logic defined into the FreeCamera code
  52276. var DeviceOrientationCamera = (function (_super) {
  52277. __extends(DeviceOrientationCamera, _super);
  52278. //-- end properties for backward compatibility for inputs
  52279. function DeviceOrientationCamera(name, position, scene) {
  52280. _super.call(this, name, position, scene);
  52281. this.inputs.addDeviceOrientation();
  52282. }
  52283. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  52284. //-- Begin properties for backward compatibility for inputs
  52285. get: function () {
  52286. return 0;
  52287. },
  52288. set: function (value) {
  52289. },
  52290. enumerable: true,
  52291. configurable: true
  52292. });
  52293. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  52294. get: function () {
  52295. return 0;
  52296. },
  52297. set: function (value) {
  52298. },
  52299. enumerable: true,
  52300. configurable: true
  52301. });
  52302. DeviceOrientationCamera.prototype.getTypeName = function () {
  52303. return "DeviceOrientationCamera";
  52304. };
  52305. return DeviceOrientationCamera;
  52306. })(BABYLON.FreeCamera);
  52307. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52308. })(BABYLON || (BABYLON = {}));
  52309. var BABYLON;
  52310. (function (BABYLON) {
  52311. // We're mainly based on the logic defined into the FreeCamera code
  52312. var UniversalCamera = (function (_super) {
  52313. __extends(UniversalCamera, _super);
  52314. //-- end properties for backward compatibility for inputs
  52315. function UniversalCamera(name, position, scene) {
  52316. _super.call(this, name, position, scene);
  52317. this.inputs.addGamepad();
  52318. }
  52319. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52320. //-- Begin properties for backward compatibility for inputs
  52321. get: function () {
  52322. var gamepad = this.inputs.attached["gamepad"];
  52323. if (gamepad)
  52324. return gamepad.gamepadAngularSensibility;
  52325. },
  52326. set: function (value) {
  52327. var gamepad = this.inputs.attached["gamepad"];
  52328. if (gamepad)
  52329. gamepad.gamepadAngularSensibility = value;
  52330. },
  52331. enumerable: true,
  52332. configurable: true
  52333. });
  52334. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52335. get: function () {
  52336. var gamepad = this.inputs.attached["gamepad"];
  52337. if (gamepad)
  52338. return gamepad.gamepadMoveSensibility;
  52339. },
  52340. set: function (value) {
  52341. var gamepad = this.inputs.attached["gamepad"];
  52342. if (gamepad)
  52343. gamepad.gamepadMoveSensibility = value;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. UniversalCamera.prototype.getTypeName = function () {
  52349. return "UniversalCamera";
  52350. };
  52351. return UniversalCamera;
  52352. })(BABYLON.TouchCamera);
  52353. BABYLON.UniversalCamera = UniversalCamera;
  52354. })(BABYLON || (BABYLON = {}));
  52355. var BABYLON;
  52356. (function (BABYLON) {
  52357. var Gamepads = (function () {
  52358. function Gamepads(ongamedpadconnected) {
  52359. var _this = this;
  52360. this.babylonGamepads = [];
  52361. this.oneGamepadConnected = false;
  52362. this.isMonitoring = false;
  52363. this.gamepadEventSupported = 'GamepadEvent' in window;
  52364. this.gamepadSupportAvailable = (navigator.getGamepads ||
  52365. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  52366. this._callbackGamepadConnected = ongamedpadconnected;
  52367. if (this.gamepadSupportAvailable) {
  52368. // Checking if the gamepad connected event is supported (like in Firefox)
  52369. if (this.gamepadEventSupported) {
  52370. this._onGamepadConnectedEvent = function (evt) {
  52371. _this._onGamepadConnected(evt);
  52372. };
  52373. this._onGamepadDisonnectedEvent = function (evt) {
  52374. _this._onGamepadDisconnected(evt);
  52375. };
  52376. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52377. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52378. }
  52379. else {
  52380. this._startMonitoringGamepads();
  52381. }
  52382. }
  52383. }
  52384. Gamepads.prototype.dispose = function () {
  52385. if (Gamepads.gamepadDOMInfo) {
  52386. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52387. }
  52388. if (this._onGamepadConnectedEvent) {
  52389. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52390. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52391. this._onGamepadConnectedEvent = null;
  52392. this._onGamepadDisonnectedEvent = null;
  52393. }
  52394. };
  52395. Gamepads.prototype._onGamepadConnected = function (evt) {
  52396. var newGamepad = this._addNewGamepad(evt.gamepad);
  52397. if (this._callbackGamepadConnected)
  52398. this._callbackGamepadConnected(newGamepad);
  52399. this._startMonitoringGamepads();
  52400. };
  52401. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52402. if (!this.oneGamepadConnected) {
  52403. this.oneGamepadConnected = true;
  52404. if (Gamepads.gamepadDOMInfo) {
  52405. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52406. Gamepads.gamepadDOMInfo = null;
  52407. }
  52408. }
  52409. var newGamepad;
  52410. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52411. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  52412. }
  52413. else {
  52414. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52415. }
  52416. this.babylonGamepads.push(newGamepad);
  52417. return newGamepad;
  52418. };
  52419. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52420. // Remove the gamepad from the list of gamepads to monitor.
  52421. for (var i in this.babylonGamepads) {
  52422. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52423. this.babylonGamepads.splice(+i, 1);
  52424. break;
  52425. }
  52426. }
  52427. // If no gamepads are left, stop the polling loop.
  52428. if (this.babylonGamepads.length == 0) {
  52429. this._stopMonitoringGamepads();
  52430. }
  52431. };
  52432. Gamepads.prototype._startMonitoringGamepads = function () {
  52433. if (!this.isMonitoring) {
  52434. this.isMonitoring = true;
  52435. this._checkGamepadsStatus();
  52436. }
  52437. };
  52438. Gamepads.prototype._stopMonitoringGamepads = function () {
  52439. this.isMonitoring = false;
  52440. };
  52441. Gamepads.prototype._checkGamepadsStatus = function () {
  52442. var _this = this;
  52443. // updating gamepad objects
  52444. this._updateGamepadObjects();
  52445. for (var i in this.babylonGamepads) {
  52446. this.babylonGamepads[i].update();
  52447. }
  52448. if (this.isMonitoring) {
  52449. if (window.requestAnimationFrame) {
  52450. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52451. }
  52452. else if (window.mozRequestAnimationFrame) {
  52453. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52454. }
  52455. else if (window.webkitRequestAnimationFrame) {
  52456. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52457. }
  52458. }
  52459. };
  52460. // This function is called only on Chrome, which does not yet support
  52461. // connection/disconnection events, but requires you to monitor
  52462. // an array for changes.
  52463. Gamepads.prototype._updateGamepadObjects = function () {
  52464. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52465. for (var i = 0; i < gamepads.length; i++) {
  52466. if (gamepads[i]) {
  52467. if (!(gamepads[i].index in this.babylonGamepads)) {
  52468. var newGamepad = this._addNewGamepad(gamepads[i]);
  52469. if (this._callbackGamepadConnected) {
  52470. this._callbackGamepadConnected(newGamepad);
  52471. }
  52472. }
  52473. else {
  52474. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52475. }
  52476. }
  52477. }
  52478. };
  52479. return Gamepads;
  52480. })();
  52481. BABYLON.Gamepads = Gamepads;
  52482. var StickValues = (function () {
  52483. function StickValues(x, y) {
  52484. this.x = x;
  52485. this.y = y;
  52486. }
  52487. return StickValues;
  52488. })();
  52489. BABYLON.StickValues = StickValues;
  52490. var Gamepad = (function () {
  52491. function Gamepad(id, index, browserGamepad) {
  52492. this.id = id;
  52493. this.index = index;
  52494. this.browserGamepad = browserGamepad;
  52495. if (this.browserGamepad.axes.length >= 2) {
  52496. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52497. }
  52498. if (this.browserGamepad.axes.length >= 4) {
  52499. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52500. }
  52501. }
  52502. Gamepad.prototype.onleftstickchanged = function (callback) {
  52503. this._onleftstickchanged = callback;
  52504. };
  52505. Gamepad.prototype.onrightstickchanged = function (callback) {
  52506. this._onrightstickchanged = callback;
  52507. };
  52508. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52509. get: function () {
  52510. return this._leftStick;
  52511. },
  52512. set: function (newValues) {
  52513. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52514. this._onleftstickchanged(newValues);
  52515. }
  52516. this._leftStick = newValues;
  52517. },
  52518. enumerable: true,
  52519. configurable: true
  52520. });
  52521. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52522. get: function () {
  52523. return this._rightStick;
  52524. },
  52525. set: function (newValues) {
  52526. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52527. this._onrightstickchanged(newValues);
  52528. }
  52529. this._rightStick = newValues;
  52530. },
  52531. enumerable: true,
  52532. configurable: true
  52533. });
  52534. Gamepad.prototype.update = function () {
  52535. if (this._leftStick) {
  52536. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52537. }
  52538. if (this._rightStick) {
  52539. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52540. }
  52541. };
  52542. return Gamepad;
  52543. })();
  52544. BABYLON.Gamepad = Gamepad;
  52545. var GenericPad = (function (_super) {
  52546. __extends(GenericPad, _super);
  52547. function GenericPad(id, index, gamepad) {
  52548. _super.call(this, id, index, gamepad);
  52549. this.id = id;
  52550. this.index = index;
  52551. this.gamepad = gamepad;
  52552. this._buttons = new Array(gamepad.buttons.length);
  52553. }
  52554. GenericPad.prototype.onbuttondown = function (callback) {
  52555. this._onbuttondown = callback;
  52556. };
  52557. GenericPad.prototype.onbuttonup = function (callback) {
  52558. this._onbuttonup = callback;
  52559. };
  52560. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52561. if (newValue !== currentValue) {
  52562. if (this._onbuttondown && newValue === 1) {
  52563. this._onbuttondown(buttonIndex);
  52564. }
  52565. if (this._onbuttonup && newValue === 0) {
  52566. this._onbuttonup(buttonIndex);
  52567. }
  52568. }
  52569. return newValue;
  52570. };
  52571. GenericPad.prototype.update = function () {
  52572. _super.prototype.update.call(this);
  52573. for (var index = 0; index < this._buttons.length; index++) {
  52574. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52575. }
  52576. };
  52577. return GenericPad;
  52578. })(Gamepad);
  52579. BABYLON.GenericPad = GenericPad;
  52580. (function (Xbox360Button) {
  52581. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52582. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52583. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52584. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52585. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52586. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52587. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52588. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52589. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52590. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52591. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52592. var Xbox360Button = BABYLON.Xbox360Button;
  52593. (function (Xbox360Dpad) {
  52594. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52595. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52596. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52597. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52598. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52599. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  52600. var Xbox360Pad = (function (_super) {
  52601. __extends(Xbox360Pad, _super);
  52602. function Xbox360Pad() {
  52603. _super.apply(this, arguments);
  52604. this._leftTrigger = 0;
  52605. this._rightTrigger = 0;
  52606. this._buttonA = 0;
  52607. this._buttonB = 0;
  52608. this._buttonX = 0;
  52609. this._buttonY = 0;
  52610. this._buttonBack = 0;
  52611. this._buttonStart = 0;
  52612. this._buttonLB = 0;
  52613. this._buttonRB = 0;
  52614. this._buttonLeftStick = 0;
  52615. this._buttonRightStick = 0;
  52616. this._dPadUp = 0;
  52617. this._dPadDown = 0;
  52618. this._dPadLeft = 0;
  52619. this._dPadRight = 0;
  52620. }
  52621. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52622. this._onlefttriggerchanged = callback;
  52623. };
  52624. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52625. this._onrighttriggerchanged = callback;
  52626. };
  52627. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52628. get: function () {
  52629. return this._leftTrigger;
  52630. },
  52631. set: function (newValue) {
  52632. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52633. this._onlefttriggerchanged(newValue);
  52634. }
  52635. this._leftTrigger = newValue;
  52636. },
  52637. enumerable: true,
  52638. configurable: true
  52639. });
  52640. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52641. get: function () {
  52642. return this._rightTrigger;
  52643. },
  52644. set: function (newValue) {
  52645. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52646. this._onrighttriggerchanged(newValue);
  52647. }
  52648. this._rightTrigger = newValue;
  52649. },
  52650. enumerable: true,
  52651. configurable: true
  52652. });
  52653. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52654. this._onbuttondown = callback;
  52655. };
  52656. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52657. this._onbuttonup = callback;
  52658. };
  52659. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52660. this._ondpaddown = callback;
  52661. };
  52662. Xbox360Pad.prototype.ondpadup = function (callback) {
  52663. this._ondpadup = callback;
  52664. };
  52665. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52666. if (newValue !== currentValue) {
  52667. if (this._onbuttondown && newValue === 1) {
  52668. this._onbuttondown(buttonType);
  52669. }
  52670. if (this._onbuttonup && newValue === 0) {
  52671. this._onbuttonup(buttonType);
  52672. }
  52673. }
  52674. return newValue;
  52675. };
  52676. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52677. if (newValue !== currentValue) {
  52678. if (this._ondpaddown && newValue === 1) {
  52679. this._ondpaddown(buttonType);
  52680. }
  52681. if (this._ondpadup && newValue === 0) {
  52682. this._ondpadup(buttonType);
  52683. }
  52684. }
  52685. return newValue;
  52686. };
  52687. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52688. get: function () {
  52689. return this._buttonA;
  52690. },
  52691. set: function (value) {
  52692. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52693. },
  52694. enumerable: true,
  52695. configurable: true
  52696. });
  52697. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52698. get: function () {
  52699. return this._buttonB;
  52700. },
  52701. set: function (value) {
  52702. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52703. },
  52704. enumerable: true,
  52705. configurable: true
  52706. });
  52707. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52708. get: function () {
  52709. return this._buttonX;
  52710. },
  52711. set: function (value) {
  52712. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52713. },
  52714. enumerable: true,
  52715. configurable: true
  52716. });
  52717. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52718. get: function () {
  52719. return this._buttonY;
  52720. },
  52721. set: function (value) {
  52722. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52723. },
  52724. enumerable: true,
  52725. configurable: true
  52726. });
  52727. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52728. get: function () {
  52729. return this._buttonStart;
  52730. },
  52731. set: function (value) {
  52732. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52733. },
  52734. enumerable: true,
  52735. configurable: true
  52736. });
  52737. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52738. get: function () {
  52739. return this._buttonBack;
  52740. },
  52741. set: function (value) {
  52742. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52743. },
  52744. enumerable: true,
  52745. configurable: true
  52746. });
  52747. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52748. get: function () {
  52749. return this._buttonLB;
  52750. },
  52751. set: function (value) {
  52752. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52753. },
  52754. enumerable: true,
  52755. configurable: true
  52756. });
  52757. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52758. get: function () {
  52759. return this._buttonRB;
  52760. },
  52761. set: function (value) {
  52762. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52763. },
  52764. enumerable: true,
  52765. configurable: true
  52766. });
  52767. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52768. get: function () {
  52769. return this._buttonLeftStick;
  52770. },
  52771. set: function (value) {
  52772. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52773. },
  52774. enumerable: true,
  52775. configurable: true
  52776. });
  52777. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52778. get: function () {
  52779. return this._buttonRightStick;
  52780. },
  52781. set: function (value) {
  52782. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52783. },
  52784. enumerable: true,
  52785. configurable: true
  52786. });
  52787. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52788. get: function () {
  52789. return this._dPadUp;
  52790. },
  52791. set: function (value) {
  52792. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52793. },
  52794. enumerable: true,
  52795. configurable: true
  52796. });
  52797. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52798. get: function () {
  52799. return this._dPadDown;
  52800. },
  52801. set: function (value) {
  52802. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52803. },
  52804. enumerable: true,
  52805. configurable: true
  52806. });
  52807. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52808. get: function () {
  52809. return this._dPadLeft;
  52810. },
  52811. set: function (value) {
  52812. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52813. },
  52814. enumerable: true,
  52815. configurable: true
  52816. });
  52817. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52818. get: function () {
  52819. return this._dPadRight;
  52820. },
  52821. set: function (value) {
  52822. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52823. },
  52824. enumerable: true,
  52825. configurable: true
  52826. });
  52827. Xbox360Pad.prototype.update = function () {
  52828. _super.prototype.update.call(this);
  52829. this.buttonA = this.browserGamepad.buttons[0].value;
  52830. this.buttonB = this.browserGamepad.buttons[1].value;
  52831. this.buttonX = this.browserGamepad.buttons[2].value;
  52832. this.buttonY = this.browserGamepad.buttons[3].value;
  52833. this.buttonLB = this.browserGamepad.buttons[4].value;
  52834. this.buttonRB = this.browserGamepad.buttons[5].value;
  52835. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52836. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52837. this.buttonBack = this.browserGamepad.buttons[8].value;
  52838. this.buttonStart = this.browserGamepad.buttons[9].value;
  52839. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52840. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52841. this.dPadUp = this.browserGamepad.buttons[12].value;
  52842. this.dPadDown = this.browserGamepad.buttons[13].value;
  52843. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52844. this.dPadRight = this.browserGamepad.buttons[15].value;
  52845. };
  52846. return Xbox360Pad;
  52847. })(Gamepad);
  52848. BABYLON.Xbox360Pad = Xbox360Pad;
  52849. })(BABYLON || (BABYLON = {}));
  52850. var BABYLON;
  52851. (function (BABYLON) {
  52852. // We're mainly based on the logic defined into the FreeCamera code
  52853. var GamepadCamera = (function (_super) {
  52854. __extends(GamepadCamera, _super);
  52855. //-- end properties for backward compatibility for inputs
  52856. function GamepadCamera(name, position, scene) {
  52857. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  52858. _super.call(this, name, position, scene);
  52859. }
  52860. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52861. //-- Begin properties for backward compatibility for inputs
  52862. get: function () {
  52863. var gamepad = this.inputs.attached["gamepad"];
  52864. if (gamepad)
  52865. return gamepad.gamepadAngularSensibility;
  52866. },
  52867. set: function (value) {
  52868. var gamepad = this.inputs.attached["gamepad"];
  52869. if (gamepad)
  52870. gamepad.gamepadAngularSensibility = value;
  52871. },
  52872. enumerable: true,
  52873. configurable: true
  52874. });
  52875. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52876. get: function () {
  52877. var gamepad = this.inputs.attached["gamepad"];
  52878. if (gamepad)
  52879. return gamepad.gamepadMoveSensibility;
  52880. },
  52881. set: function (value) {
  52882. var gamepad = this.inputs.attached["gamepad"];
  52883. if (gamepad)
  52884. gamepad.gamepadMoveSensibility = value;
  52885. },
  52886. enumerable: true,
  52887. configurable: true
  52888. });
  52889. GamepadCamera.prototype.getTypeName = function () {
  52890. return "GamepadCamera";
  52891. };
  52892. return GamepadCamera;
  52893. })(BABYLON.UniversalCamera);
  52894. BABYLON.GamepadCamera = GamepadCamera;
  52895. })(BABYLON || (BABYLON = {}));
  52896. var BABYLON;
  52897. (function (BABYLON) {
  52898. var Analyser = (function () {
  52899. function Analyser(scene) {
  52900. this.SMOOTHING = 0.75;
  52901. this.FFT_SIZE = 512;
  52902. this.BARGRAPHAMPLITUDE = 256;
  52903. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  52904. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  52905. this._scene = scene;
  52906. this._audioEngine = BABYLON.Engine.audioEngine;
  52907. if (this._audioEngine.canUseWebAudio) {
  52908. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  52909. this._webAudioAnalyser.minDecibels = -140;
  52910. this._webAudioAnalyser.maxDecibels = 0;
  52911. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52912. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52913. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  52914. }
  52915. }
  52916. Analyser.prototype.getFrequencyBinCount = function () {
  52917. if (this._audioEngine.canUseWebAudio) {
  52918. return this._webAudioAnalyser.frequencyBinCount;
  52919. }
  52920. else {
  52921. return 0;
  52922. }
  52923. };
  52924. Analyser.prototype.getByteFrequencyData = function () {
  52925. if (this._audioEngine.canUseWebAudio) {
  52926. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52927. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52928. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  52929. }
  52930. return this._byteFreqs;
  52931. };
  52932. Analyser.prototype.getByteTimeDomainData = function () {
  52933. if (this._audioEngine.canUseWebAudio) {
  52934. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52935. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52936. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  52937. }
  52938. return this._byteTime;
  52939. };
  52940. Analyser.prototype.getFloatFrequencyData = function () {
  52941. if (this._audioEngine.canUseWebAudio) {
  52942. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52943. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52944. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  52945. }
  52946. return this._floatFreqs;
  52947. };
  52948. Analyser.prototype.drawDebugCanvas = function () {
  52949. var _this = this;
  52950. if (this._audioEngine.canUseWebAudio) {
  52951. if (!this._debugCanvas) {
  52952. this._debugCanvas = document.createElement("canvas");
  52953. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  52954. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  52955. this._debugCanvas.style.position = "absolute";
  52956. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  52957. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  52958. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52959. document.body.appendChild(this._debugCanvas);
  52960. this._registerFunc = function () {
  52961. _this.drawDebugCanvas();
  52962. };
  52963. this._scene.registerBeforeRender(this._registerFunc);
  52964. }
  52965. if (this._registerFunc) {
  52966. var workingArray = this.getByteFrequencyData();
  52967. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52968. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52969. // Draw the frequency domain chart.
  52970. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52971. var value = workingArray[i];
  52972. var percent = value / this.BARGRAPHAMPLITUDE;
  52973. var height = this.DEBUGCANVASSIZE.height * percent;
  52974. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52975. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52976. var hue = i / this.getFrequencyBinCount() * 360;
  52977. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52978. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52979. }
  52980. }
  52981. }
  52982. };
  52983. Analyser.prototype.stopDebugCanvas = function () {
  52984. if (this._debugCanvas) {
  52985. this._scene.unregisterBeforeRender(this._registerFunc);
  52986. this._registerFunc = null;
  52987. document.body.removeChild(this._debugCanvas);
  52988. this._debugCanvas = null;
  52989. this._debugCanvasContext = null;
  52990. }
  52991. };
  52992. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52993. if (this._audioEngine.canUseWebAudio) {
  52994. inputAudioNode.connect(this._webAudioAnalyser);
  52995. this._webAudioAnalyser.connect(outputAudioNode);
  52996. }
  52997. };
  52998. Analyser.prototype.dispose = function () {
  52999. if (this._audioEngine.canUseWebAudio) {
  53000. this._webAudioAnalyser.disconnect();
  53001. }
  53002. };
  53003. return Analyser;
  53004. })();
  53005. BABYLON.Analyser = Analyser;
  53006. })(BABYLON || (BABYLON = {}));
  53007. var BABYLON;
  53008. (function (BABYLON) {
  53009. var DepthRenderer = (function () {
  53010. function DepthRenderer(scene, type) {
  53011. var _this = this;
  53012. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53013. this._viewMatrix = BABYLON.Matrix.Zero();
  53014. this._projectionMatrix = BABYLON.Matrix.Zero();
  53015. this._transformMatrix = BABYLON.Matrix.Zero();
  53016. this._worldViewProjection = BABYLON.Matrix.Zero();
  53017. this._scene = scene;
  53018. var engine = scene.getEngine();
  53019. // Render target
  53020. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53021. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53022. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53023. this._depthMap.refreshRate = 1;
  53024. this._depthMap.renderParticles = false;
  53025. this._depthMap.renderList = null;
  53026. // set default depth value to 1.0 (far away)
  53027. this._depthMap.onClearObservable.add(function (engine) {
  53028. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  53029. });
  53030. // Custom render function
  53031. var renderSubMesh = function (subMesh) {
  53032. var mesh = subMesh.getRenderingMesh();
  53033. var scene = _this._scene;
  53034. var engine = scene.getEngine();
  53035. // Culling
  53036. engine.setState(subMesh.getMaterial().backFaceCulling);
  53037. // Managing instances
  53038. var batch = mesh._getInstancesRenderList(subMesh._id);
  53039. if (batch.mustReturn) {
  53040. return;
  53041. }
  53042. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53043. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53044. engine.enableEffect(_this._effect);
  53045. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53046. var material = subMesh.getMaterial();
  53047. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53048. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53049. // Alpha test
  53050. if (material && material.needAlphaTesting()) {
  53051. var alphaTexture = material.getAlphaTestTexture();
  53052. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53053. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53054. }
  53055. // Bones
  53056. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53057. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53058. }
  53059. // Draw
  53060. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53061. }
  53062. };
  53063. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53064. var index;
  53065. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53066. renderSubMesh(opaqueSubMeshes.data[index]);
  53067. }
  53068. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53069. renderSubMesh(alphaTestSubMeshes.data[index]);
  53070. }
  53071. };
  53072. }
  53073. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53074. var material = subMesh.getMaterial();
  53075. if (material.disableDepthWrite) {
  53076. return false;
  53077. }
  53078. var defines = [];
  53079. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53080. var mesh = subMesh.getMesh();
  53081. var scene = mesh.getScene();
  53082. // Alpha test
  53083. if (material && material.needAlphaTesting()) {
  53084. defines.push("#define ALPHATEST");
  53085. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53086. attribs.push(BABYLON.VertexBuffer.UVKind);
  53087. defines.push("#define UV1");
  53088. }
  53089. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53090. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53091. defines.push("#define UV2");
  53092. }
  53093. }
  53094. // Bones
  53095. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53096. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53097. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53098. if (mesh.numBoneInfluencers > 4) {
  53099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53101. }
  53102. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53103. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53104. }
  53105. else {
  53106. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53107. }
  53108. // Instances
  53109. if (useInstances) {
  53110. defines.push("#define INSTANCES");
  53111. attribs.push("world0");
  53112. attribs.push("world1");
  53113. attribs.push("world2");
  53114. attribs.push("world3");
  53115. }
  53116. // Get correct effect
  53117. var join = defines.join("\n");
  53118. if (this._cachedDefines !== join) {
  53119. this._cachedDefines = join;
  53120. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53121. }
  53122. return this._effect.isReady();
  53123. };
  53124. DepthRenderer.prototype.getDepthMap = function () {
  53125. return this._depthMap;
  53126. };
  53127. // Methods
  53128. DepthRenderer.prototype.dispose = function () {
  53129. this._depthMap.dispose();
  53130. };
  53131. return DepthRenderer;
  53132. })();
  53133. BABYLON.DepthRenderer = DepthRenderer;
  53134. })(BABYLON || (BABYLON = {}));
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var SSAORenderingPipeline = (function (_super) {
  53138. __extends(SSAORenderingPipeline, _super);
  53139. /**
  53140. * @constructor
  53141. * @param {string} name - The rendering pipeline name
  53142. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53143. * @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 }
  53144. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53145. */
  53146. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53147. var _this = this;
  53148. _super.call(this, scene.getEngine(), name);
  53149. // Members
  53150. /**
  53151. * The PassPostProcess id in the pipeline that contains the original scene color
  53152. * @type {string}
  53153. */
  53154. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53155. /**
  53156. * The SSAO PostProcess id in the pipeline
  53157. * @type {string}
  53158. */
  53159. this.SSAORenderEffect = "SSAORenderEffect";
  53160. /**
  53161. * The horizontal blur PostProcess id in the pipeline
  53162. * @type {string}
  53163. */
  53164. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53165. /**
  53166. * The vertical blur PostProcess id in the pipeline
  53167. * @type {string}
  53168. */
  53169. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53170. /**
  53171. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53172. * @type {string}
  53173. */
  53174. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53175. /**
  53176. * The output strength of the SSAO post-process. Default value is 1.0.
  53177. * @type {number}
  53178. */
  53179. this.totalStrength = 1.0;
  53180. /**
  53181. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53182. * @type {number}
  53183. */
  53184. this.radius = 0.0001;
  53185. /**
  53186. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53187. * Must not be equal to fallOff and superior to fallOff.
  53188. * Default value is 0.975
  53189. * @type {number}
  53190. */
  53191. this.area = 0.0075;
  53192. /**
  53193. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53194. * Must not be equal to area and inferior to area.
  53195. * Default value is 0.0
  53196. * @type {number}
  53197. */
  53198. this.fallOff = 0.000001;
  53199. /**
  53200. * The base color of the SSAO post-process
  53201. * The final result is "base + ssao" between [0, 1]
  53202. * @type {number}
  53203. */
  53204. this.base = 0.5;
  53205. this._firstUpdate = true;
  53206. this._scene = scene;
  53207. // Set up assets
  53208. this._createRandomTexture();
  53209. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53210. var ssaoRatio = ratio.ssaoRatio || ratio;
  53211. var combineRatio = ratio.combineRatio || ratio;
  53212. this._ratio = {
  53213. ssaoRatio: ssaoRatio,
  53214. combineRatio: combineRatio
  53215. };
  53216. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53217. this._createSSAOPostProcess(ssaoRatio);
  53218. this._createBlurPostProcess(ssaoRatio);
  53219. this._createSSAOCombinePostProcess(combineRatio);
  53220. // Set up pipeline
  53221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53226. // Finish
  53227. scene.postProcessRenderPipelineManager.addPipeline(this);
  53228. if (cameras)
  53229. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53230. }
  53231. // Public Methods
  53232. /**
  53233. * Returns the horizontal blur PostProcess
  53234. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  53235. */
  53236. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  53237. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  53238. return null;
  53239. };
  53240. /**
  53241. * Returns the vertical blur PostProcess
  53242. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  53243. */
  53244. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  53245. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  53246. return null;
  53247. };
  53248. /**
  53249. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53250. */
  53251. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53252. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53253. for (var i = 0; i < this._scene.cameras.length; i++) {
  53254. var camera = this._scene.cameras[i];
  53255. this._originalColorPostProcess.dispose(camera);
  53256. this._ssaoPostProcess.dispose(camera);
  53257. this._blurHPostProcess.dispose(camera);
  53258. this._blurVPostProcess.dispose(camera);
  53259. this._ssaoCombinePostProcess.dispose(camera);
  53260. }
  53261. this._randomTexture.dispose();
  53262. if (disableDepthRender)
  53263. this._scene.disableDepthRenderer();
  53264. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53265. };
  53266. // Private Methods
  53267. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53268. var _this = this;
  53269. /*
  53270. var samplerOffsets = [
  53271. -8.0, -6.0, -4.0, -2.0,
  53272. 0.0,
  53273. 2.0, 4.0, 6.0, 8.0
  53274. ];
  53275. */
  53276. var samples = 16;
  53277. var samplerOffsets = [];
  53278. for (var i = -8; i < 8; i++) {
  53279. samplerOffsets.push(i * 2);
  53280. }
  53281. 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");
  53282. this._blurHPostProcess.onApply = function (effect) {
  53283. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53284. effect.setTexture("depthSampler", _this._depthTexture);
  53285. if (_this._firstUpdate) {
  53286. effect.setArray("samplerOffsets", samplerOffsets);
  53287. }
  53288. };
  53289. 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");
  53290. this._blurVPostProcess.onApply = function (effect) {
  53291. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53292. effect.setTexture("depthSampler", _this._depthTexture);
  53293. if (_this._firstUpdate) {
  53294. effect.setArray("samplerOffsets", samplerOffsets);
  53295. _this._firstUpdate = false;
  53296. }
  53297. };
  53298. };
  53299. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53300. var _this = this;
  53301. var numSamples = 16;
  53302. var sampleSphere = [
  53303. 0.5381, 0.1856, -0.4319,
  53304. 0.1379, 0.2486, 0.4430,
  53305. 0.3371, 0.5679, -0.0057,
  53306. -0.6999, -0.0451, -0.0019,
  53307. 0.0689, -0.1598, -0.8547,
  53308. 0.0560, 0.0069, -0.1843,
  53309. -0.0146, 0.1402, 0.0762,
  53310. 0.0100, -0.1924, -0.0344,
  53311. -0.3577, -0.5301, -0.4358,
  53312. -0.3169, 0.1063, 0.0158,
  53313. 0.0103, -0.5869, 0.0046,
  53314. -0.0897, -0.4940, 0.3287,
  53315. 0.7119, -0.0154, -0.0918,
  53316. -0.0533, 0.0596, -0.5411,
  53317. 0.0352, -0.0631, 0.5460,
  53318. -0.4776, 0.2847, -0.0271
  53319. ];
  53320. var samplesFactor = 1.0 / numSamples;
  53321. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53322. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53323. "area", "fallOff", "base", "range", "viewport"
  53324. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53325. var viewport = new BABYLON.Vector2(0, 0);
  53326. this._ssaoPostProcess.onApply = function (effect) {
  53327. if (_this._firstUpdate) {
  53328. effect.setArray3("sampleSphere", sampleSphere);
  53329. effect.setFloat("samplesFactor", samplesFactor);
  53330. effect.setFloat("randTextureTiles", 4.0);
  53331. }
  53332. effect.setFloat("totalStrength", _this.totalStrength);
  53333. effect.setFloat("radius", _this.radius);
  53334. effect.setFloat("area", _this.area);
  53335. effect.setFloat("fallOff", _this.fallOff);
  53336. effect.setFloat("base", _this.base);
  53337. effect.setTexture("textureSampler", _this._depthTexture);
  53338. effect.setTexture("randomSampler", _this._randomTexture);
  53339. };
  53340. };
  53341. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53342. var _this = this;
  53343. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53344. this._ssaoCombinePostProcess.onApply = function (effect) {
  53345. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53346. };
  53347. };
  53348. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53349. var size = 512;
  53350. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53351. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53352. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53353. var context = this._randomTexture.getContext();
  53354. var rand = function (min, max) {
  53355. return Math.random() * (max - min) + min;
  53356. };
  53357. var randVector = BABYLON.Vector3.Zero();
  53358. for (var x = 0; x < size; x++) {
  53359. for (var y = 0; y < size; y++) {
  53360. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53361. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53362. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53363. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53364. context.fillRect(x, y, 1, 1);
  53365. }
  53366. }
  53367. this._randomTexture.update(false);
  53368. };
  53369. __decorate([
  53370. BABYLON.serialize()
  53371. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53372. __decorate([
  53373. BABYLON.serialize()
  53374. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53375. __decorate([
  53376. BABYLON.serialize()
  53377. ], SSAORenderingPipeline.prototype, "area", void 0);
  53378. __decorate([
  53379. BABYLON.serialize()
  53380. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53381. __decorate([
  53382. BABYLON.serialize()
  53383. ], SSAORenderingPipeline.prototype, "base", void 0);
  53384. __decorate([
  53385. BABYLON.serialize()
  53386. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53387. return SSAORenderingPipeline;
  53388. })(BABYLON.PostProcessRenderPipeline);
  53389. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53390. })(BABYLON || (BABYLON = {}));
  53391. var BABYLON;
  53392. (function (BABYLON) {
  53393. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53394. var VolumetricLightScatteringPostProcess = (function (_super) {
  53395. __extends(VolumetricLightScatteringPostProcess, _super);
  53396. /**
  53397. * @constructor
  53398. * @param {string} name - The post-process name
  53399. * @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)
  53400. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53401. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53402. * @param {number} samples - The post-process quality, default 100
  53403. * @param {number} samplingMode - The post-process filtering mode
  53404. * @param {BABYLON.Engine} engine - The babylon engine
  53405. * @param {boolean} reusable - If the post-process is reusable
  53406. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53407. */
  53408. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53409. var _this = this;
  53410. if (samples === void 0) { samples = 100; }
  53411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53412. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  53413. this._screenCoordinates = BABYLON.Vector2.Zero();
  53414. /**
  53415. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53416. * @type {Vector3}
  53417. */
  53418. this.customMeshPosition = BABYLON.Vector3.Zero();
  53419. /**
  53420. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53421. * @type {boolean}
  53422. */
  53423. this.useCustomMeshPosition = false;
  53424. /**
  53425. * If the post-process should inverse the light scattering direction
  53426. * @type {boolean}
  53427. */
  53428. this.invert = true;
  53429. /**
  53430. * Array containing the excluded meshes not rendered in the internal pass
  53431. */
  53432. this.excludedMeshes = new Array();
  53433. /**
  53434. * Controls the overall intensity of the post-process
  53435. * @type {number}
  53436. */
  53437. this.exposure = 0.3;
  53438. /**
  53439. * Dissipates each sample's contribution in range [0, 1]
  53440. * @type {number}
  53441. */
  53442. this.decay = 0.96815;
  53443. /**
  53444. * Controls the overall intensity of each sample
  53445. * @type {number}
  53446. */
  53447. this.weight = 0.58767;
  53448. /**
  53449. * Controls the density of each sample
  53450. * @type {number}
  53451. */
  53452. this.density = 0.926;
  53453. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53454. var engine = scene.getEngine();
  53455. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53456. // Configure mesh
  53457. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53458. // Configure
  53459. this._createPass(scene, ratio.passRatio || ratio);
  53460. this.onActivate = function (camera) {
  53461. if (!_this.isSupported) {
  53462. _this.dispose(camera);
  53463. }
  53464. _this.onActivate = null;
  53465. };
  53466. this.onApplyObservable.add(function (effect) {
  53467. _this._updateMeshScreenCoordinates(scene);
  53468. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53469. effect.setFloat("exposure", _this.exposure);
  53470. effect.setFloat("decay", _this.decay);
  53471. effect.setFloat("weight", _this.weight);
  53472. effect.setFloat("density", _this.density);
  53473. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53474. });
  53475. }
  53476. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53477. get: function () {
  53478. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53479. return false;
  53480. },
  53481. set: function (useDiffuseColor) {
  53482. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53483. },
  53484. enumerable: true,
  53485. configurable: true
  53486. });
  53487. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53488. var mesh = subMesh.getMesh();
  53489. // Render this.mesh as default
  53490. if (mesh === this.mesh) {
  53491. return mesh.material.isReady(mesh);
  53492. }
  53493. var defines = [];
  53494. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53495. var material = subMesh.getMaterial();
  53496. var needUV = false;
  53497. // Alpha test
  53498. if (material) {
  53499. if (material.needAlphaTesting()) {
  53500. defines.push("#define ALPHATEST");
  53501. }
  53502. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53503. attribs.push(BABYLON.VertexBuffer.UVKind);
  53504. defines.push("#define UV1");
  53505. }
  53506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53507. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53508. defines.push("#define UV2");
  53509. }
  53510. }
  53511. // Bones
  53512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53515. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53516. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53517. }
  53518. else {
  53519. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53520. }
  53521. // Instances
  53522. if (useInstances) {
  53523. defines.push("#define INSTANCES");
  53524. attribs.push("world0");
  53525. attribs.push("world1");
  53526. attribs.push("world2");
  53527. attribs.push("world3");
  53528. }
  53529. // Get correct effect
  53530. var join = defines.join("\n");
  53531. if (this._cachedDefines !== join) {
  53532. this._cachedDefines = join;
  53533. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53534. }
  53535. return this._volumetricLightScatteringPass.isReady();
  53536. };
  53537. /**
  53538. * Sets the new light position for light scattering effect
  53539. * @param {BABYLON.Vector3} The new custom light position
  53540. */
  53541. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53542. this.customMeshPosition = position;
  53543. };
  53544. /**
  53545. * Returns the light position for light scattering effect
  53546. * @return {BABYLON.Vector3} The custom light position
  53547. */
  53548. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53549. return this.customMeshPosition;
  53550. };
  53551. /**
  53552. * Disposes the internal assets and detaches the post-process from the camera
  53553. */
  53554. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53555. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53556. if (rttIndex !== -1) {
  53557. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53558. }
  53559. this._volumetricLightScatteringRTT.dispose();
  53560. _super.prototype.dispose.call(this, camera);
  53561. };
  53562. /**
  53563. * Returns the render target texture used by the post-process
  53564. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53565. */
  53566. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53567. return this._volumetricLightScatteringRTT;
  53568. };
  53569. // Private methods
  53570. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53571. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53572. return true;
  53573. }
  53574. return false;
  53575. };
  53576. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53577. var _this = this;
  53578. var engine = scene.getEngine();
  53579. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53580. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53581. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53582. this._volumetricLightScatteringRTT.renderList = null;
  53583. this._volumetricLightScatteringRTT.renderParticles = false;
  53584. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53585. // Custom render function for submeshes
  53586. var renderSubMesh = function (subMesh) {
  53587. var mesh = subMesh.getRenderingMesh();
  53588. if (_this._meshExcluded(mesh)) {
  53589. return;
  53590. }
  53591. var scene = mesh.getScene();
  53592. var engine = scene.getEngine();
  53593. // Culling
  53594. engine.setState(subMesh.getMaterial().backFaceCulling);
  53595. // Managing instances
  53596. var batch = mesh._getInstancesRenderList(subMesh._id);
  53597. if (batch.mustReturn) {
  53598. return;
  53599. }
  53600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53602. var effect = _this._volumetricLightScatteringPass;
  53603. if (mesh === _this.mesh) {
  53604. effect = subMesh.getMaterial().getEffect();
  53605. }
  53606. engine.enableEffect(effect);
  53607. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53608. if (mesh === _this.mesh) {
  53609. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53610. }
  53611. else {
  53612. var material = subMesh.getMaterial();
  53613. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53614. // Alpha test
  53615. if (material && material.needAlphaTesting()) {
  53616. var alphaTexture = material.getAlphaTestTexture();
  53617. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53618. if (alphaTexture) {
  53619. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53620. }
  53621. }
  53622. // Bones
  53623. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53624. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53625. }
  53626. }
  53627. // Draw
  53628. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53629. }
  53630. };
  53631. // Render target texture callbacks
  53632. var savedSceneClearColor;
  53633. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53634. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53635. savedSceneClearColor = scene.clearColor;
  53636. scene.clearColor = sceneClearColor;
  53637. });
  53638. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53639. scene.clearColor = savedSceneClearColor;
  53640. });
  53641. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53642. var engine = scene.getEngine();
  53643. var index;
  53644. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53645. renderSubMesh(opaqueSubMeshes.data[index]);
  53646. }
  53647. engine.setAlphaTesting(true);
  53648. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53649. renderSubMesh(alphaTestSubMeshes.data[index]);
  53650. }
  53651. engine.setAlphaTesting(false);
  53652. if (transparentSubMeshes.length) {
  53653. // Sort sub meshes
  53654. for (index = 0; index < transparentSubMeshes.length; index++) {
  53655. var submesh = transparentSubMeshes.data[index];
  53656. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53657. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53658. }
  53659. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53660. sortedArray.sort(function (a, b) {
  53661. // Alpha index first
  53662. if (a._alphaIndex > b._alphaIndex) {
  53663. return 1;
  53664. }
  53665. if (a._alphaIndex < b._alphaIndex) {
  53666. return -1;
  53667. }
  53668. // Then distance to camera
  53669. if (a._distanceToCamera < b._distanceToCamera) {
  53670. return 1;
  53671. }
  53672. if (a._distanceToCamera > b._distanceToCamera) {
  53673. return -1;
  53674. }
  53675. return 0;
  53676. });
  53677. // Render sub meshes
  53678. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53679. for (index = 0; index < sortedArray.length; index++) {
  53680. renderSubMesh(sortedArray[index]);
  53681. }
  53682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53683. }
  53684. };
  53685. };
  53686. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53687. var transform = scene.getTransformMatrix();
  53688. var meshPosition;
  53689. if (this.useCustomMeshPosition) {
  53690. meshPosition = this.customMeshPosition;
  53691. }
  53692. else if (this.attachedNode) {
  53693. meshPosition = this.attachedNode.position;
  53694. }
  53695. else {
  53696. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53697. }
  53698. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53699. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53700. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53701. if (this.invert)
  53702. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53703. };
  53704. // Static methods
  53705. /**
  53706. * Creates a default mesh for the Volumeric Light Scattering post-process
  53707. * @param {string} The mesh name
  53708. * @param {BABYLON.Scene} The scene where to create the mesh
  53709. * @return {BABYLON.Mesh} the default mesh
  53710. */
  53711. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53712. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53713. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53714. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53715. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53716. mesh.material = material;
  53717. return mesh;
  53718. };
  53719. __decorate([
  53720. BABYLON.serializeAsVector3()
  53721. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53722. __decorate([
  53723. BABYLON.serialize()
  53724. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53725. __decorate([
  53726. BABYLON.serialize()
  53727. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53728. __decorate([
  53729. BABYLON.serializeAsMeshReference()
  53730. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53731. __decorate([
  53732. BABYLON.serialize()
  53733. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53734. __decorate([
  53735. BABYLON.serialize()
  53736. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53737. __decorate([
  53738. BABYLON.serialize()
  53739. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53740. __decorate([
  53741. BABYLON.serialize()
  53742. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53743. __decorate([
  53744. BABYLON.serialize()
  53745. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53746. return VolumetricLightScatteringPostProcess;
  53747. })(BABYLON.PostProcess);
  53748. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53749. })(BABYLON || (BABYLON = {}));
  53750. // BABYLON.JS Chromatic Aberration GLSL Shader
  53751. // Author: Olivier Guyot
  53752. // Separates very slightly R, G and B colors on the edges of the screen
  53753. // Inspired by Francois Tarlier & Martins Upitis
  53754. var BABYLON;
  53755. (function (BABYLON) {
  53756. var LensRenderingPipeline = (function (_super) {
  53757. __extends(LensRenderingPipeline, _super);
  53758. /**
  53759. * @constructor
  53760. *
  53761. * Effect parameters are as follow:
  53762. * {
  53763. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53764. * edge_blur: number; // from 0 to x (1 for realism)
  53765. * distortion: number; // from 0 to x (1 for realism)
  53766. * grain_amount: number; // from 0 to 1
  53767. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53768. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53769. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53770. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53771. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53772. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53773. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53774. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53775. * }
  53776. * Note: if an effect parameter is unset, effect is disabled
  53777. *
  53778. * @param {string} name - The rendering pipeline name
  53779. * @param {object} parameters - An object containing all parameters (see above)
  53780. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53781. * @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)
  53782. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53783. */
  53784. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53785. var _this = this;
  53786. if (ratio === void 0) { ratio = 1.0; }
  53787. _super.call(this, scene.getEngine(), name);
  53788. // Lens effects can be of the following:
  53789. // - chromatic aberration (slight shift of RGB colors)
  53790. // - blur on the edge of the lens
  53791. // - lens distortion
  53792. // - depth-of-field blur & highlights enhancing
  53793. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53794. // - grain effect (noise or custom texture)
  53795. // Two additional texture samplers are needed:
  53796. // - depth map (for depth-of-field)
  53797. // - grain texture
  53798. /**
  53799. * The chromatic aberration PostProcess id in the pipeline
  53800. * @type {string}
  53801. */
  53802. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53803. /**
  53804. * The highlights enhancing PostProcess id in the pipeline
  53805. * @type {string}
  53806. */
  53807. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53808. /**
  53809. * The depth-of-field PostProcess id in the pipeline
  53810. * @type {string}
  53811. */
  53812. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  53813. this._scene = scene;
  53814. // Fetch texture samplers
  53815. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53816. if (parameters.grain_texture) {
  53817. this._grainTexture = parameters.grain_texture;
  53818. }
  53819. else {
  53820. this._createGrainTexture();
  53821. }
  53822. // save parameters
  53823. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  53824. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  53825. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  53826. this._distortion = parameters.distortion ? parameters.distortion : 0;
  53827. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  53828. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  53829. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53830. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53831. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53832. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53833. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53834. // Create effects
  53835. this._createChromaticAberrationPostProcess(ratio);
  53836. this._createHighlightsPostProcess(ratio);
  53837. this._createDepthOfFieldPostProcess(ratio / 4);
  53838. // Set up pipeline
  53839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53842. if (this._highlightsGain === -1) {
  53843. this._disableEffect(this.HighlightsEnhancingEffect, null);
  53844. }
  53845. // Finish
  53846. scene.postProcessRenderPipelineManager.addPipeline(this);
  53847. if (cameras) {
  53848. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53849. }
  53850. }
  53851. // public methods (self explanatory)
  53852. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53853. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53854. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53855. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53856. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53857. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53858. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53859. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53860. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53861. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53862. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53863. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53864. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53865. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53866. };
  53867. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53868. this._highlightsPostProcess.updateEffect();
  53869. };
  53870. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53871. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53872. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53873. this._highlightsGain = amount;
  53874. };
  53875. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53876. if (this._highlightsGain === -1) {
  53877. this._highlightsGain = 1.0;
  53878. }
  53879. this._highlightsThreshold = amount;
  53880. };
  53881. LensRenderingPipeline.prototype.disableHighlights = function () {
  53882. this._highlightsGain = -1;
  53883. };
  53884. /**
  53885. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53886. */
  53887. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53888. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53889. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53890. this._chromaticAberrationPostProcess = undefined;
  53891. this._highlightsPostProcess = undefined;
  53892. this._depthOfFieldPostProcess = undefined;
  53893. this._grainTexture.dispose();
  53894. if (disableDepthRender)
  53895. this._scene.disableDepthRenderer();
  53896. };
  53897. // colors shifting and distortion
  53898. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53899. var _this = this;
  53900. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53901. [], // samplers
  53902. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53903. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53904. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53905. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53906. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53907. };
  53908. };
  53909. // highlights enhancing
  53910. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53911. var _this = this;
  53912. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53913. [], // samplers
  53914. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53915. this._highlightsPostProcess.onApply = function (effect) {
  53916. effect.setFloat('gain', _this._highlightsGain);
  53917. effect.setFloat('threshold', _this._highlightsThreshold);
  53918. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53921. };
  53922. };
  53923. // colors shifting and distortion
  53924. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53925. var _this = this;
  53926. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53927. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53928. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53929. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53930. this._depthOfFieldPostProcess.onApply = function (effect) {
  53931. effect.setTexture("depthSampler", _this._depthTexture);
  53932. effect.setTexture("grainSampler", _this._grainTexture);
  53933. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53934. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53935. effect.setFloat('grain_amount', _this._grainAmount);
  53936. effect.setBool('blur_noise', _this._blurNoise);
  53937. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53938. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53939. effect.setFloat('distortion', _this._distortion);
  53940. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53941. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53942. effect.setFloat('aperture', _this._dofAperture);
  53943. effect.setFloat('darken', _this._dofDarken);
  53944. effect.setFloat('edge_blur', _this._edgeBlur);
  53945. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53946. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53947. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53948. };
  53949. };
  53950. // creates a black and white random noise texture, 512x512
  53951. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53952. var size = 512;
  53953. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53954. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53955. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53956. var context = this._grainTexture.getContext();
  53957. var rand = function (min, max) {
  53958. return Math.random() * (max - min) + min;
  53959. };
  53960. var value;
  53961. for (var x = 0; x < size; x++) {
  53962. for (var y = 0; y < size; y++) {
  53963. value = Math.floor(rand(0.42, 0.58) * 255);
  53964. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53965. context.fillRect(x, y, 1, 1);
  53966. }
  53967. }
  53968. this._grainTexture.update(false);
  53969. };
  53970. return LensRenderingPipeline;
  53971. })(BABYLON.PostProcessRenderPipeline);
  53972. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53973. })(BABYLON || (BABYLON = {}));
  53974. //
  53975. // This post-process allows the modification of rendered colors by using
  53976. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53977. //
  53978. // The object needs to be provided an url to a texture containing the color
  53979. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53980. // Use an image editing software to tweak the LUT to match your needs.
  53981. //
  53982. // For an example of a color LUT, see here:
  53983. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53984. // For explanations on color grading, see here:
  53985. // http://udn.epicgames.com/Three/ColorGrading.html
  53986. //
  53987. var BABYLON;
  53988. (function (BABYLON) {
  53989. var ColorCorrectionPostProcess = (function (_super) {
  53990. __extends(ColorCorrectionPostProcess, _super);
  53991. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53992. var _this = this;
  53993. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  53994. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53995. this._colorTableTexture.anisotropicFilteringLevel = 1;
  53996. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53997. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53998. this.onApply = function (effect) {
  53999. effect.setTexture("colorTable", _this._colorTableTexture);
  54000. };
  54001. }
  54002. return ColorCorrectionPostProcess;
  54003. })(BABYLON.PostProcess);
  54004. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54005. })(BABYLON || (BABYLON = {}));
  54006. var BABYLON;
  54007. (function (BABYLON) {
  54008. var AnaglyphFreeCamera = (function (_super) {
  54009. __extends(AnaglyphFreeCamera, _super);
  54010. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54011. _super.call(this, name, position, scene);
  54012. this.interaxialDistance = interaxialDistance;
  54013. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54014. }
  54015. AnaglyphFreeCamera.prototype.getTypeName = function () {
  54016. return "AnaglyphFreeCamera";
  54017. };
  54018. return AnaglyphFreeCamera;
  54019. })(BABYLON.FreeCamera);
  54020. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54021. var AnaglyphArcRotateCamera = (function (_super) {
  54022. __extends(AnaglyphArcRotateCamera, _super);
  54023. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54024. _super.call(this, name, alpha, beta, radius, target, scene);
  54025. this.interaxialDistance = interaxialDistance;
  54026. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54027. }
  54028. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  54029. return "AnaglyphArcRotateCamera";
  54030. };
  54031. return AnaglyphArcRotateCamera;
  54032. })(BABYLON.ArcRotateCamera);
  54033. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54034. var AnaglyphGamepadCamera = (function (_super) {
  54035. __extends(AnaglyphGamepadCamera, _super);
  54036. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54037. _super.call(this, name, position, scene);
  54038. this.interaxialDistance = interaxialDistance;
  54039. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54040. }
  54041. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  54042. return "AnaglyphGamepadCamera";
  54043. };
  54044. return AnaglyphGamepadCamera;
  54045. })(BABYLON.GamepadCamera);
  54046. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54047. var AnaglyphUniversalCamera = (function (_super) {
  54048. __extends(AnaglyphUniversalCamera, _super);
  54049. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54050. _super.call(this, name, position, scene);
  54051. this.interaxialDistance = interaxialDistance;
  54052. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54053. }
  54054. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  54055. return "AnaglyphUniversalCamera";
  54056. };
  54057. return AnaglyphUniversalCamera;
  54058. })(BABYLON.UniversalCamera);
  54059. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54060. var StereoscopicFreeCamera = (function (_super) {
  54061. __extends(StereoscopicFreeCamera, _super);
  54062. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54063. _super.call(this, name, position, scene);
  54064. this.interaxialDistance = interaxialDistance;
  54065. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54066. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54067. }
  54068. StereoscopicFreeCamera.prototype.getTypeName = function () {
  54069. return "StereoscopicFreeCamera";
  54070. };
  54071. return StereoscopicFreeCamera;
  54072. })(BABYLON.FreeCamera);
  54073. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54074. var StereoscopicArcRotateCamera = (function (_super) {
  54075. __extends(StereoscopicArcRotateCamera, _super);
  54076. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54077. _super.call(this, name, alpha, beta, radius, target, scene);
  54078. this.interaxialDistance = interaxialDistance;
  54079. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54080. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54081. }
  54082. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  54083. return "StereoscopicArcRotateCamera";
  54084. };
  54085. return StereoscopicArcRotateCamera;
  54086. })(BABYLON.ArcRotateCamera);
  54087. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54088. var StereoscopicGamepadCamera = (function (_super) {
  54089. __extends(StereoscopicGamepadCamera, _super);
  54090. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54091. _super.call(this, name, position, scene);
  54092. this.interaxialDistance = interaxialDistance;
  54093. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54094. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54095. }
  54096. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  54097. return "StereoscopicGamepadCamera";
  54098. };
  54099. return StereoscopicGamepadCamera;
  54100. })(BABYLON.GamepadCamera);
  54101. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54102. var StereoscopicUniversalCamera = (function (_super) {
  54103. __extends(StereoscopicUniversalCamera, _super);
  54104. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54105. _super.call(this, name, position, scene);
  54106. this.interaxialDistance = interaxialDistance;
  54107. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54108. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54109. }
  54110. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  54111. return "StereoscopicUniversalCamera";
  54112. };
  54113. return StereoscopicUniversalCamera;
  54114. })(BABYLON.UniversalCamera);
  54115. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54116. })(BABYLON || (BABYLON = {}));
  54117. var BABYLON;
  54118. (function (BABYLON) {
  54119. var HDRRenderingPipeline = (function (_super) {
  54120. __extends(HDRRenderingPipeline, _super);
  54121. /**
  54122. * @constructor
  54123. * @param {string} name - The rendering pipeline name
  54124. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54125. * @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)
  54126. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54127. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54128. */
  54129. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54130. var _this = this;
  54131. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54132. _super.call(this, scene.getEngine(), name);
  54133. /**
  54134. * Public members
  54135. */
  54136. // Gaussian Blur
  54137. /**
  54138. * Gaussian blur coefficient
  54139. * @type {number}
  54140. */
  54141. this.gaussCoeff = 0.3;
  54142. /**
  54143. * Gaussian blur mean
  54144. * @type {number}
  54145. */
  54146. this.gaussMean = 1.0;
  54147. /**
  54148. * Gaussian blur standard deviation
  54149. * @type {number}
  54150. */
  54151. this.gaussStandDev = 0.8;
  54152. /**
  54153. * Gaussian blur multiplier. Multiplies the blur effect
  54154. * @type {number}
  54155. */
  54156. this.gaussMultiplier = 4.0;
  54157. // HDR
  54158. /**
  54159. * Exposure, controls the overall intensity of the pipeline
  54160. * @type {number}
  54161. */
  54162. this.exposure = 1.0;
  54163. /**
  54164. * Minimum luminance that the post-process can output. Luminance is >= 0
  54165. * @type {number}
  54166. */
  54167. this.minimumLuminance = 1.0;
  54168. /**
  54169. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54170. * @type {number}
  54171. */
  54172. this.maximumLuminance = 1e20;
  54173. /**
  54174. * Increase rate for luminance: eye adaptation speed to dark
  54175. * @type {number}
  54176. */
  54177. this.luminanceIncreaserate = 0.5;
  54178. /**
  54179. * Decrease rate for luminance: eye adaptation speed to bright
  54180. * @type {number}
  54181. */
  54182. this.luminanceDecreaseRate = 0.5;
  54183. // Bright pass
  54184. /**
  54185. * Minimum luminance needed to compute HDR
  54186. * @type {number}
  54187. */
  54188. this.brightThreshold = 0.8;
  54189. this._needUpdate = true;
  54190. this._scene = scene;
  54191. // Bright pass
  54192. this._createBrightPassPostProcess(scene, ratio);
  54193. // Down sample X4
  54194. this._createDownSampleX4PostProcess(scene, ratio);
  54195. // Create gaussian blur post-processes
  54196. this._createGaussianBlurPostProcess(scene, ratio);
  54197. // Texture adder
  54198. this._createTextureAdderPostProcess(scene, ratio);
  54199. // Luminance generator
  54200. this._createLuminanceGeneratorPostProcess(scene);
  54201. // HDR
  54202. this._createHDRPostProcess(scene, ratio);
  54203. // Pass postprocess
  54204. if (originalPostProcess === null) {
  54205. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54206. }
  54207. else {
  54208. this._originalPostProcess = originalPostProcess;
  54209. }
  54210. // Configure pipeline
  54211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54217. var addDownSamplerPostProcess = function (id) {
  54218. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54219. };
  54220. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54221. addDownSamplerPostProcess(i);
  54222. }
  54223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54224. // Finish
  54225. scene.postProcessRenderPipelineManager.addPipeline(this);
  54226. if (cameras !== null) {
  54227. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54228. }
  54229. this.update();
  54230. }
  54231. /**
  54232. * Tells the pipeline to update its post-processes
  54233. */
  54234. HDRRenderingPipeline.prototype.update = function () {
  54235. this._needUpdate = true;
  54236. };
  54237. /**
  54238. * Returns the current calculated luminance
  54239. */
  54240. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54241. return this._hdrCurrentLuminance;
  54242. };
  54243. /**
  54244. * Returns the currently drawn luminance
  54245. */
  54246. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54247. return this._hdrOutputLuminance;
  54248. };
  54249. /**
  54250. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54251. */
  54252. HDRRenderingPipeline.prototype.dispose = function () {
  54253. this._originalPostProcess = undefined;
  54254. this._brightPassPostProcess = undefined;
  54255. this._downSampleX4PostProcess = undefined;
  54256. this._guassianBlurHPostProcess = undefined;
  54257. this._guassianBlurVPostProcess = undefined;
  54258. this._textureAdderPostProcess = undefined;
  54259. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54260. this._downSamplePostProcesses[i] = undefined;
  54261. }
  54262. this._hdrPostProcess = undefined;
  54263. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54264. };
  54265. /**
  54266. * Creates the HDR post-process and computes the luminance adaptation
  54267. */
  54268. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54269. var _this = this;
  54270. var hdrLastLuminance = 0.0;
  54271. this._hdrOutputLuminance = -1.0;
  54272. this._hdrCurrentLuminance = 1.0;
  54273. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54274. this._hdrPostProcess.onApply = function (effect) {
  54275. if (_this._hdrOutputLuminance < 0.0) {
  54276. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54277. }
  54278. else {
  54279. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54280. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54281. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54282. }
  54283. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54284. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54285. }
  54286. else {
  54287. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54288. }
  54289. }
  54290. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54291. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54292. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54293. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54294. effect.setFloat("exposure", _this.exposure);
  54295. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54296. _this._needUpdate = false;
  54297. };
  54298. };
  54299. /**
  54300. * Texture Adder post-process
  54301. */
  54302. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54303. var _this = this;
  54304. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54305. this._textureAdderPostProcess.onApply = function (effect) {
  54306. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54307. };
  54308. };
  54309. /**
  54310. * Down sample X4 post-process
  54311. */
  54312. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54313. var _this = this;
  54314. var downSampleX4Offsets = new Array(32);
  54315. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54316. this._downSampleX4PostProcess.onApply = function (effect) {
  54317. if (_this._needUpdate) {
  54318. var id = 0;
  54319. for (var i = -2; i < 2; i++) {
  54320. for (var j = -2; j < 2; j++) {
  54321. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54322. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54323. id += 2;
  54324. }
  54325. }
  54326. }
  54327. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54328. };
  54329. };
  54330. /**
  54331. * Bright pass post-process
  54332. */
  54333. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54334. var _this = this;
  54335. var brightOffsets = new Array(8);
  54336. var brightPassCallback = function (effect) {
  54337. if (_this._needUpdate) {
  54338. var sU = (1.0 / _this._brightPassPostProcess.width);
  54339. var sV = (1.0 / _this._brightPassPostProcess.height);
  54340. brightOffsets[0] = -0.5 * sU;
  54341. brightOffsets[1] = 0.5 * sV;
  54342. brightOffsets[2] = 0.5 * sU;
  54343. brightOffsets[3] = 0.5 * sV;
  54344. brightOffsets[4] = -0.5 * sU;
  54345. brightOffsets[5] = -0.5 * sV;
  54346. brightOffsets[6] = 0.5 * sU;
  54347. brightOffsets[7] = -0.5 * sV;
  54348. }
  54349. effect.setArray2("dsOffsets", brightOffsets);
  54350. effect.setFloat("brightThreshold", _this.brightThreshold);
  54351. };
  54352. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54353. this._brightPassPostProcess.onApply = brightPassCallback;
  54354. };
  54355. /**
  54356. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54357. */
  54358. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54359. var _this = this;
  54360. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54361. var luminanceOffsets = new Array(8);
  54362. var downSampleOffsets = new Array(18);
  54363. var halfDestPixelSize;
  54364. this._downSamplePostProcesses = new Array(lumSteps);
  54365. // Utils for luminance
  54366. var luminanceUpdateSourceOffsets = function (width, height) {
  54367. var sU = (1.0 / width);
  54368. var sV = (1.0 / height);
  54369. luminanceOffsets[0] = -0.5 * sU;
  54370. luminanceOffsets[1] = 0.5 * sV;
  54371. luminanceOffsets[2] = 0.5 * sU;
  54372. luminanceOffsets[3] = 0.5 * sV;
  54373. luminanceOffsets[4] = -0.5 * sU;
  54374. luminanceOffsets[5] = -0.5 * sV;
  54375. luminanceOffsets[6] = 0.5 * sU;
  54376. luminanceOffsets[7] = -0.5 * sV;
  54377. };
  54378. var luminanceUpdateDestOffsets = function (width, height) {
  54379. var id = 0;
  54380. for (var x = -1; x < 2; x++) {
  54381. for (var y = -1; y < 2; y++) {
  54382. downSampleOffsets[id] = (x) / width;
  54383. downSampleOffsets[id + 1] = (y) / height;
  54384. id += 2;
  54385. }
  54386. }
  54387. };
  54388. // Luminance callback
  54389. var luminanceCallback = function (effect) {
  54390. if (_this._needUpdate) {
  54391. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54392. }
  54393. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54394. effect.setArray2("lumOffsets", luminanceOffsets);
  54395. };
  54396. // Down sample callbacks
  54397. var downSampleCallback = function (indice) {
  54398. var i = indice;
  54399. return function (effect) {
  54400. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54401. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54402. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54403. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54404. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54405. effect.setArray2("dsOffsets", downSampleOffsets);
  54406. };
  54407. };
  54408. var downSampleAfterRenderCallback = function (effect) {
  54409. // Unpack result
  54410. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54411. 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);
  54412. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54413. };
  54414. // Create luminance post-process
  54415. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54416. 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);
  54417. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54418. // Create down sample post-processes
  54419. for (var i = lumSteps - 2; i >= 0; i--) {
  54420. var length = Math.pow(3, i);
  54421. ratio = { width: length, height: length };
  54422. var defines = "#define DOWN_SAMPLE\n";
  54423. if (i === 0) {
  54424. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54425. }
  54426. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54427. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54428. if (i === 0) {
  54429. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54430. }
  54431. }
  54432. };
  54433. /**
  54434. * Gaussian blur post-processes. Horizontal and Vertical
  54435. */
  54436. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54437. var _this = this;
  54438. var blurOffsetsW = new Array(9);
  54439. var blurOffsetsH = new Array(9);
  54440. var blurWeights = new Array(9);
  54441. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54442. // Utils for gaussian blur
  54443. var calculateBlurOffsets = function (height) {
  54444. var lastOutputDimensions = {
  54445. width: scene.getEngine().getRenderWidth(),
  54446. height: scene.getEngine().getRenderHeight()
  54447. };
  54448. for (var i = 0; i < 9; i++) {
  54449. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54450. if (height) {
  54451. blurOffsetsH[i] = value;
  54452. }
  54453. else {
  54454. blurOffsetsW[i] = value;
  54455. }
  54456. }
  54457. };
  54458. var calculateWeights = function () {
  54459. var x = 0.0;
  54460. for (var i = 0; i < 9; i++) {
  54461. x = (i - 4.0) / 4.0;
  54462. 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));
  54463. }
  54464. };
  54465. // Callback
  54466. var gaussianBlurCallback = function (height) {
  54467. return function (effect) {
  54468. if (_this._needUpdate) {
  54469. calculateWeights();
  54470. calculateBlurOffsets(height);
  54471. }
  54472. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54473. effect.setArray("blurWeights", blurWeights);
  54474. effect.setFloat("multiplier", _this.gaussMultiplier);
  54475. };
  54476. };
  54477. // Create horizontal gaussian blur post-processes
  54478. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54479. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54480. // Create vertical gaussian blur post-process
  54481. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54482. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54483. };
  54484. // Luminance generator
  54485. HDRRenderingPipeline.LUM_STEPS = 6;
  54486. return HDRRenderingPipeline;
  54487. })(BABYLON.PostProcessRenderPipeline);
  54488. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54489. })(BABYLON || (BABYLON = {}));
  54490. var BABYLON;
  54491. (function (BABYLON) {
  54492. var FaceAdjacencies = (function () {
  54493. function FaceAdjacencies() {
  54494. this.edges = new Array();
  54495. this.edgesConnectedCount = 0;
  54496. }
  54497. return FaceAdjacencies;
  54498. })();
  54499. var EdgesRenderer = (function () {
  54500. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54501. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54502. if (epsilon === void 0) { epsilon = 0.95; }
  54503. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54504. this.edgesWidthScalerForOrthographic = 1000.0;
  54505. this.edgesWidthScalerForPerspective = 50.0;
  54506. this._linesPositions = new Array();
  54507. this._linesNormals = new Array();
  54508. this._linesIndices = new Array();
  54509. this._buffers = {};
  54510. this._checkVerticesInsteadOfIndices = false;
  54511. this._source = source;
  54512. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54513. this._epsilon = epsilon;
  54514. this._prepareRessources();
  54515. this._generateEdgesLines();
  54516. }
  54517. EdgesRenderer.prototype._prepareRessources = function () {
  54518. if (this._lineShader) {
  54519. return;
  54520. }
  54521. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54522. attributes: ["position", "normal"],
  54523. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54524. });
  54525. this._lineShader.disableDepthWrite = true;
  54526. this._lineShader.backFaceCulling = false;
  54527. };
  54528. EdgesRenderer.prototype.dispose = function () {
  54529. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54530. if (buffer) {
  54531. buffer.dispose();
  54532. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54533. }
  54534. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54535. if (buffer) {
  54536. buffer.dispose();
  54537. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54538. }
  54539. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54540. this._lineShader.dispose();
  54541. };
  54542. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54543. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54544. return 0;
  54545. }
  54546. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54547. return 1;
  54548. }
  54549. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54550. return 2;
  54551. }
  54552. return -1;
  54553. };
  54554. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54555. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54556. return 0;
  54557. }
  54558. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54559. return 1;
  54560. }
  54561. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54562. return 2;
  54563. }
  54564. return -1;
  54565. };
  54566. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54567. var needToCreateLine;
  54568. if (edge === undefined) {
  54569. needToCreateLine = true;
  54570. }
  54571. else {
  54572. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54573. needToCreateLine = dotProduct < this._epsilon;
  54574. }
  54575. if (needToCreateLine) {
  54576. var offset = this._linesPositions.length / 3;
  54577. var normal = p0.subtract(p1);
  54578. normal.normalize();
  54579. // Positions
  54580. this._linesPositions.push(p0.x);
  54581. this._linesPositions.push(p0.y);
  54582. this._linesPositions.push(p0.z);
  54583. this._linesPositions.push(p0.x);
  54584. this._linesPositions.push(p0.y);
  54585. this._linesPositions.push(p0.z);
  54586. this._linesPositions.push(p1.x);
  54587. this._linesPositions.push(p1.y);
  54588. this._linesPositions.push(p1.z);
  54589. this._linesPositions.push(p1.x);
  54590. this._linesPositions.push(p1.y);
  54591. this._linesPositions.push(p1.z);
  54592. // Normals
  54593. this._linesNormals.push(p1.x);
  54594. this._linesNormals.push(p1.y);
  54595. this._linesNormals.push(p1.z);
  54596. this._linesNormals.push(-1);
  54597. this._linesNormals.push(p1.x);
  54598. this._linesNormals.push(p1.y);
  54599. this._linesNormals.push(p1.z);
  54600. this._linesNormals.push(1);
  54601. this._linesNormals.push(p0.x);
  54602. this._linesNormals.push(p0.y);
  54603. this._linesNormals.push(p0.z);
  54604. this._linesNormals.push(-1);
  54605. this._linesNormals.push(p0.x);
  54606. this._linesNormals.push(p0.y);
  54607. this._linesNormals.push(p0.z);
  54608. this._linesNormals.push(1);
  54609. // Indices
  54610. this._linesIndices.push(offset);
  54611. this._linesIndices.push(offset + 1);
  54612. this._linesIndices.push(offset + 2);
  54613. this._linesIndices.push(offset);
  54614. this._linesIndices.push(offset + 2);
  54615. this._linesIndices.push(offset + 3);
  54616. }
  54617. };
  54618. EdgesRenderer.prototype._generateEdgesLines = function () {
  54619. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54620. var indices = this._source.getIndices();
  54621. // First let's find adjacencies
  54622. var adjacencies = new Array();
  54623. var faceNormals = new Array();
  54624. var index;
  54625. var faceAdjacencies;
  54626. // Prepare faces
  54627. for (index = 0; index < indices.length; index += 3) {
  54628. faceAdjacencies = new FaceAdjacencies();
  54629. var p0Index = indices[index];
  54630. var p1Index = indices[index + 1];
  54631. var p2Index = indices[index + 2];
  54632. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54633. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54634. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54635. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54636. faceNormal.normalize();
  54637. faceNormals.push(faceNormal);
  54638. adjacencies.push(faceAdjacencies);
  54639. }
  54640. // Scan
  54641. for (index = 0; index < adjacencies.length; index++) {
  54642. faceAdjacencies = adjacencies[index];
  54643. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54644. var otherFaceAdjacencies = adjacencies[otherIndex];
  54645. if (faceAdjacencies.edgesConnectedCount === 3) {
  54646. break;
  54647. }
  54648. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54649. continue;
  54650. }
  54651. var otherP0 = indices[otherIndex * 3];
  54652. var otherP1 = indices[otherIndex * 3 + 1];
  54653. var otherP2 = indices[otherIndex * 3 + 2];
  54654. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  54655. var otherEdgeIndex;
  54656. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  54657. continue;
  54658. }
  54659. switch (edgeIndex) {
  54660. case 0:
  54661. if (this._checkVerticesInsteadOfIndices) {
  54662. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54663. }
  54664. else {
  54665. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  54666. }
  54667. break;
  54668. case 1:
  54669. if (this._checkVerticesInsteadOfIndices) {
  54670. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54671. }
  54672. else {
  54673. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  54674. }
  54675. break;
  54676. case 2:
  54677. if (this._checkVerticesInsteadOfIndices) {
  54678. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54679. }
  54680. else {
  54681. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  54682. }
  54683. break;
  54684. }
  54685. if (otherEdgeIndex === -1) {
  54686. continue;
  54687. }
  54688. faceAdjacencies.edges[edgeIndex] = otherIndex;
  54689. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  54690. faceAdjacencies.edgesConnectedCount++;
  54691. otherFaceAdjacencies.edgesConnectedCount++;
  54692. if (faceAdjacencies.edgesConnectedCount === 3) {
  54693. break;
  54694. }
  54695. }
  54696. }
  54697. }
  54698. // Create lines
  54699. for (index = 0; index < adjacencies.length; index++) {
  54700. // 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
  54701. var current = adjacencies[index];
  54702. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  54703. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  54704. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  54705. }
  54706. // Merge into a single mesh
  54707. var engine = this._source.getScene().getEngine();
  54708. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  54709. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  54710. this._ib = engine.createIndexBuffer(this._linesIndices);
  54711. this._indicesCount = this._linesIndices.length;
  54712. };
  54713. EdgesRenderer.prototype.render = function () {
  54714. if (!this._lineShader.isReady()) {
  54715. return;
  54716. }
  54717. var scene = this._source.getScene();
  54718. var engine = scene.getEngine();
  54719. this._lineShader._preBind();
  54720. // VBOs
  54721. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  54722. scene.resetCachedMaterial();
  54723. this._lineShader.setColor4("color", this._source.edgesColor);
  54724. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  54725. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  54726. }
  54727. else {
  54728. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  54729. }
  54730. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  54731. this._lineShader.bind(this._source.getWorldMatrix());
  54732. // Draw order
  54733. engine.draw(true, 0, this._indicesCount);
  54734. this._lineShader.unbind();
  54735. engine.setDepthWrite(true);
  54736. };
  54737. return EdgesRenderer;
  54738. })();
  54739. BABYLON.EdgesRenderer = EdgesRenderer;
  54740. })(BABYLON || (BABYLON = {}));
  54741. var BABYLON;
  54742. (function (BABYLON) {
  54743. (function (TonemappingOperator) {
  54744. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54745. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54746. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54747. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54748. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54749. var TonemappingOperator = BABYLON.TonemappingOperator;
  54750. ;
  54751. var TonemapPostProcess = (function (_super) {
  54752. __extends(TonemapPostProcess, _super);
  54753. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54754. var _this = this;
  54755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54756. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54757. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  54758. this._operator = _operator;
  54759. this.exposureAdjustment = exposureAdjustment;
  54760. var defines = "#define ";
  54761. if (this._operator === TonemappingOperator.Hable)
  54762. defines += "HABLE_TONEMAPPING";
  54763. else if (this._operator === TonemappingOperator.Reinhard)
  54764. defines += "REINHARD_TONEMAPPING";
  54765. else if (this._operator === TonemappingOperator.HejiDawson)
  54766. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54767. else if (this._operator === TonemappingOperator.Photographic)
  54768. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54769. //sadly a second call to create the effect.
  54770. this.updateEffect(defines);
  54771. this.onApply = function (effect) {
  54772. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54773. };
  54774. }
  54775. return TonemapPostProcess;
  54776. })(BABYLON.PostProcess);
  54777. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54778. })(BABYLON || (BABYLON = {}));
  54779. var BABYLON;
  54780. (function (BABYLON) {
  54781. var ReflectionProbe = (function () {
  54782. function ReflectionProbe(name, size, scene, generateMipMaps) {
  54783. var _this = this;
  54784. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54785. this.name = name;
  54786. this._viewMatrix = BABYLON.Matrix.Identity();
  54787. this._target = BABYLON.Vector3.Zero();
  54788. this._add = BABYLON.Vector3.Zero();
  54789. this.invertYAxis = false;
  54790. this.position = BABYLON.Vector3.Zero();
  54791. this._scene = scene;
  54792. this._scene.reflectionProbes.push(this);
  54793. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  54794. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  54795. switch (faceIndex) {
  54796. case 0:
  54797. _this._add.copyFromFloats(1, 0, 0);
  54798. break;
  54799. case 1:
  54800. _this._add.copyFromFloats(-1, 0, 0);
  54801. break;
  54802. case 2:
  54803. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  54804. break;
  54805. case 3:
  54806. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  54807. break;
  54808. case 4:
  54809. _this._add.copyFromFloats(0, 0, 1);
  54810. break;
  54811. case 5:
  54812. _this._add.copyFromFloats(0, 0, -1);
  54813. break;
  54814. }
  54815. if (_this._attachedMesh) {
  54816. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  54817. }
  54818. _this.position.addToRef(_this._add, _this._target);
  54819. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  54820. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  54821. });
  54822. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  54823. scene.updateTransformMatrix(true);
  54824. });
  54825. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  54826. }
  54827. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  54828. get: function () {
  54829. return this._renderTargetTexture.refreshRate;
  54830. },
  54831. set: function (value) {
  54832. this._renderTargetTexture.refreshRate = value;
  54833. },
  54834. enumerable: true,
  54835. configurable: true
  54836. });
  54837. ReflectionProbe.prototype.getScene = function () {
  54838. return this._scene;
  54839. };
  54840. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  54841. get: function () {
  54842. return this._renderTargetTexture;
  54843. },
  54844. enumerable: true,
  54845. configurable: true
  54846. });
  54847. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  54848. get: function () {
  54849. return this._renderTargetTexture.renderList;
  54850. },
  54851. enumerable: true,
  54852. configurable: true
  54853. });
  54854. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  54855. this._attachedMesh = mesh;
  54856. };
  54857. ReflectionProbe.prototype.dispose = function () {
  54858. var index = this._scene.reflectionProbes.indexOf(this);
  54859. if (index !== -1) {
  54860. // Remove from the scene if found
  54861. this._scene.reflectionProbes.splice(index, 1);
  54862. }
  54863. if (this._renderTargetTexture) {
  54864. this._renderTargetTexture.dispose();
  54865. this._renderTargetTexture = null;
  54866. }
  54867. };
  54868. return ReflectionProbe;
  54869. })();
  54870. BABYLON.ReflectionProbe = ReflectionProbe;
  54871. })(BABYLON || (BABYLON = {}));
  54872. var BABYLON;
  54873. (function (BABYLON) {
  54874. var SolidParticle = (function () {
  54875. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  54876. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  54877. this.position = BABYLON.Vector3.Zero(); // position
  54878. this.rotation = BABYLON.Vector3.Zero(); // rotation
  54879. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  54880. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  54881. this.velocity = BABYLON.Vector3.Zero(); // velocity
  54882. this.alive = true; // alive
  54883. this.isVisible = true; // visibility
  54884. this.idx = particleIndex;
  54885. this._pos = positionIndex;
  54886. this._model = model;
  54887. this.shapeId = shapeId;
  54888. this.idxInShape = idxInShape;
  54889. }
  54890. Object.defineProperty(SolidParticle.prototype, "scale", {
  54891. //legacy support, changed scale to scaling
  54892. get: function () {
  54893. return this.scaling;
  54894. },
  54895. set: function (scale) {
  54896. this.scaling = scale;
  54897. },
  54898. enumerable: true,
  54899. configurable: true
  54900. });
  54901. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54902. //legacy support, changed quaternion to rotationQuaternion
  54903. get: function () {
  54904. return this.rotationQuaternion;
  54905. },
  54906. set: function (q) {
  54907. this.rotationQuaternion = q;
  54908. },
  54909. enumerable: true,
  54910. configurable: true
  54911. });
  54912. return SolidParticle;
  54913. })();
  54914. BABYLON.SolidParticle = SolidParticle;
  54915. var ModelShape = (function () {
  54916. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  54917. this.shapeID = id;
  54918. this._shape = shape;
  54919. this._shapeUV = shapeUV;
  54920. this._positionFunction = posFunction;
  54921. this._vertexFunction = vtxFunction;
  54922. }
  54923. return ModelShape;
  54924. })();
  54925. BABYLON.ModelShape = ModelShape;
  54926. })(BABYLON || (BABYLON = {}));
  54927. var BABYLON;
  54928. (function (BABYLON) {
  54929. /**
  54930. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54931. */
  54932. var SolidParticleSystem = (function () {
  54933. /**
  54934. * Creates a SPS (Solid Particle System) object.
  54935. * `name` (String) is the SPS name, this will be the underlying mesh name.
  54936. * `scene` (Scene) is the scene in which the SPS is added.
  54937. * `updatable` (default true) : if the SPS must be updatable or immutable.
  54938. * `isPickable` (default false) : if the solid particles must be pickable.
  54939. */
  54940. function SolidParticleSystem(name, scene, options) {
  54941. // public members
  54942. /**
  54943. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54944. * Example : var p = SPS.particles[i];
  54945. */
  54946. this.particles = new Array();
  54947. /**
  54948. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54949. */
  54950. this.nbParticles = 0;
  54951. /**
  54952. * If the particles must ever face the camera (default false). Useful for planar particles.
  54953. */
  54954. this.billboard = false;
  54955. /**
  54956. * This a counter ofr your own usage. It's not set by any SPS functions.
  54957. */
  54958. this.counter = 0;
  54959. /**
  54960. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54961. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54962. */
  54963. this.vars = {};
  54964. this._positions = new Array();
  54965. this._indices = new Array();
  54966. this._normals = new Array();
  54967. this._colors = new Array();
  54968. this._uvs = new Array();
  54969. this._index = 0; // indices index
  54970. this._updatable = true;
  54971. this._pickable = false;
  54972. this._isVisibilityBoxLocked = false;
  54973. this._alwaysVisible = false;
  54974. this._shapeCounter = 0;
  54975. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  54976. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54977. this._computeParticleColor = true;
  54978. this._computeParticleTexture = true;
  54979. this._computeParticleRotation = true;
  54980. this._computeParticleVertex = false;
  54981. this._computeBoundingBox = false;
  54982. this._cam_axisZ = BABYLON.Vector3.Zero();
  54983. this._cam_axisY = BABYLON.Vector3.Zero();
  54984. this._cam_axisX = BABYLON.Vector3.Zero();
  54985. this._axisX = BABYLON.Axis.X;
  54986. this._axisY = BABYLON.Axis.Y;
  54987. this._axisZ = BABYLON.Axis.Z;
  54988. this._fakeCamPos = BABYLON.Vector3.Zero();
  54989. this._rotMatrix = new BABYLON.Matrix();
  54990. this._invertMatrix = new BABYLON.Matrix();
  54991. this._rotated = BABYLON.Vector3.Zero();
  54992. this._quaternion = new BABYLON.Quaternion();
  54993. this._vertex = BABYLON.Vector3.Zero();
  54994. this._normal = BABYLON.Vector3.Zero();
  54995. this._yaw = 0.0;
  54996. this._pitch = 0.0;
  54997. this._roll = 0.0;
  54998. this._halfroll = 0.0;
  54999. this._halfpitch = 0.0;
  55000. this._halfyaw = 0.0;
  55001. this._sinRoll = 0.0;
  55002. this._cosRoll = 0.0;
  55003. this._sinPitch = 0.0;
  55004. this._cosPitch = 0.0;
  55005. this._sinYaw = 0.0;
  55006. this._cosYaw = 0.0;
  55007. this._w = 0.0;
  55008. this._minimum = BABYLON.Tmp.Vector3[0];
  55009. this._maximum = BABYLON.Tmp.Vector3[1];
  55010. this.name = name;
  55011. this._scene = scene;
  55012. this._camera = scene.activeCamera;
  55013. this._pickable = options ? options.isPickable : false;
  55014. if (options && options.updatable) {
  55015. this._updatable = options.updatable;
  55016. }
  55017. else {
  55018. this._updatable = true;
  55019. }
  55020. if (this._pickable) {
  55021. this.pickedParticles = [];
  55022. }
  55023. }
  55024. /**
  55025. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55026. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55027. */
  55028. SolidParticleSystem.prototype.buildMesh = function () {
  55029. if (this.nbParticles === 0) {
  55030. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55031. this.addShape(triangle, 1);
  55032. triangle.dispose();
  55033. }
  55034. this._positions32 = new Float32Array(this._positions);
  55035. this._uvs32 = new Float32Array(this._uvs);
  55036. this._colors32 = new Float32Array(this._colors);
  55037. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55038. this._normals32 = new Float32Array(this._normals);
  55039. this._fixedNormal32 = new Float32Array(this._normals);
  55040. var vertexData = new BABYLON.VertexData();
  55041. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55042. vertexData.indices = this._indices;
  55043. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55044. if (this._uvs32) {
  55045. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55046. ;
  55047. }
  55048. if (this._colors32) {
  55049. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55050. }
  55051. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55052. vertexData.applyToMesh(mesh, this._updatable);
  55053. this.mesh = mesh;
  55054. this.mesh.isPickable = this._pickable;
  55055. // free memory
  55056. this._positions = null;
  55057. this._normals = null;
  55058. this._uvs = null;
  55059. this._colors = null;
  55060. if (!this._updatable) {
  55061. this.particles.length = 0;
  55062. }
  55063. return mesh;
  55064. };
  55065. /**
  55066. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55067. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55068. * Thus the particles generated from `digest()` have their property `position` set yet.
  55069. * `mesh` ( Mesh ) is the mesh to be digested
  55070. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55071. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55072. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55073. */
  55074. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55075. var size = (options && options.facetNb) || 1;
  55076. var number = (options && options.number);
  55077. var delta = (options && options.delta) || 0;
  55078. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55079. var meshInd = mesh.getIndices();
  55080. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55081. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55082. var f = 0; // facet counter
  55083. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55084. // compute size from number
  55085. if (number) {
  55086. number = (number > totalFacets) ? totalFacets : number;
  55087. size = Math.round(totalFacets / number);
  55088. delta = 0;
  55089. }
  55090. else {
  55091. size = (size > totalFacets) ? totalFacets : size;
  55092. }
  55093. var facetPos = []; // submesh positions
  55094. var facetInd = []; // submesh indices
  55095. var facetUV = []; // submesh UV
  55096. var facetCol = []; // submesh colors
  55097. var barycenter = BABYLON.Tmp.Vector3[0];
  55098. var rand;
  55099. var sizeO = size;
  55100. while (f < totalFacets) {
  55101. size = sizeO + Math.floor((1 + delta) * Math.random());
  55102. if (f > totalFacets - size) {
  55103. size = totalFacets - f;
  55104. }
  55105. // reset temp arrays
  55106. facetPos.length = 0;
  55107. facetInd.length = 0;
  55108. facetUV.length = 0;
  55109. facetCol.length = 0;
  55110. // iterate over "size" facets
  55111. var fi = 0;
  55112. for (var j = f * 3; j < (f + size) * 3; j++) {
  55113. facetInd.push(fi);
  55114. var i = meshInd[j];
  55115. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55116. if (meshUV) {
  55117. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55118. }
  55119. if (meshCol) {
  55120. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55121. }
  55122. fi++;
  55123. }
  55124. // create a model shape for each single particle
  55125. var idx = this.nbParticles;
  55126. var shape = this._posToShape(facetPos);
  55127. var shapeUV = this._uvsToShapeUV(facetUV);
  55128. // compute the barycenter of the shape
  55129. var v;
  55130. for (v = 0; v < shape.length; v++) {
  55131. barycenter.addInPlace(shape[v]);
  55132. }
  55133. barycenter.scaleInPlace(1 / shape.length);
  55134. // shift the shape from its barycenter to the origin
  55135. for (v = 0; v < shape.length; v++) {
  55136. shape[v].subtractInPlace(barycenter);
  55137. }
  55138. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55139. // add the particle in the SPS
  55140. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  55141. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  55142. // initialize the particle position
  55143. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55144. this._index += shape.length;
  55145. idx++;
  55146. this.nbParticles++;
  55147. this._shapeCounter++;
  55148. f += size;
  55149. }
  55150. return this;
  55151. };
  55152. //reset copy
  55153. SolidParticleSystem.prototype._resetCopy = function () {
  55154. this._copy.position.x = 0;
  55155. this._copy.position.y = 0;
  55156. this._copy.position.z = 0;
  55157. this._copy.rotation.x = 0;
  55158. this._copy.rotation.y = 0;
  55159. this._copy.rotation.z = 0;
  55160. this._copy.rotationQuaternion = null;
  55161. this._copy.scaling.x = 1;
  55162. this._copy.scaling.y = 1;
  55163. this._copy.scaling.z = 1;
  55164. this._copy.uvs.x = 0;
  55165. this._copy.uvs.y = 0;
  55166. this._copy.uvs.z = 1;
  55167. this._copy.uvs.w = 1;
  55168. this._copy.color = null;
  55169. };
  55170. // _meshBuilder : inserts the shape model in the global SPS mesh
  55171. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  55172. var i;
  55173. var u = 0;
  55174. var c = 0;
  55175. this._resetCopy();
  55176. if (options && options.positionFunction) {
  55177. options.positionFunction(this._copy, idx, idxInShape);
  55178. }
  55179. if (this._copy.rotationQuaternion) {
  55180. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55181. }
  55182. else {
  55183. this._yaw = this._copy.rotation.y;
  55184. this._pitch = this._copy.rotation.x;
  55185. this._roll = this._copy.rotation.z;
  55186. this._quaternionRotationYPR();
  55187. }
  55188. this._quaternionToRotationMatrix();
  55189. for (i = 0; i < shape.length; i++) {
  55190. this._vertex.x = shape[i].x;
  55191. this._vertex.y = shape[i].y;
  55192. this._vertex.z = shape[i].z;
  55193. if (options && options.vertexFunction) {
  55194. options.vertexFunction(this._copy, this._vertex, i);
  55195. }
  55196. this._vertex.x *= this._copy.scaling.x;
  55197. this._vertex.y *= this._copy.scaling.y;
  55198. this._vertex.z *= this._copy.scaling.z;
  55199. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55200. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55201. if (meshUV) {
  55202. 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);
  55203. u += 2;
  55204. }
  55205. if (this._copy.color) {
  55206. this._color = this._copy.color;
  55207. }
  55208. else if (meshCol && meshCol[c] !== undefined) {
  55209. this._color.r = meshCol[c];
  55210. this._color.g = meshCol[c + 1];
  55211. this._color.b = meshCol[c + 2];
  55212. this._color.a = meshCol[c + 3];
  55213. }
  55214. else {
  55215. this._color.r = 1;
  55216. this._color.g = 1;
  55217. this._color.b = 1;
  55218. this._color.a = 1;
  55219. }
  55220. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55221. c += 4;
  55222. }
  55223. for (i = 0; i < meshInd.length; i++) {
  55224. indices.push(p + meshInd[i]);
  55225. }
  55226. if (this._pickable) {
  55227. var nbfaces = meshInd.length / 3;
  55228. for (i = 0; i < nbfaces; i++) {
  55229. this.pickedParticles.push({ idx: idx, faceId: i });
  55230. }
  55231. }
  55232. };
  55233. // returns a shape array from positions array
  55234. SolidParticleSystem.prototype._posToShape = function (positions) {
  55235. var shape = [];
  55236. for (var i = 0; i < positions.length; i += 3) {
  55237. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55238. }
  55239. return shape;
  55240. };
  55241. // returns a shapeUV array from a Vector4 uvs
  55242. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55243. var shapeUV = [];
  55244. if (uvs) {
  55245. for (var i = 0; i < uvs.length; i++)
  55246. shapeUV.push(uvs[i]);
  55247. }
  55248. return shapeUV;
  55249. };
  55250. // adds a new particle object in the particles array
  55251. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  55252. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  55253. };
  55254. /**
  55255. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55256. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55257. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55258. * `nb` (positive integer) the number of particles to be created from this model
  55259. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55260. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55261. */
  55262. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55263. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55264. var meshInd = mesh.getIndices();
  55265. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55266. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55267. var shape = this._posToShape(meshPos);
  55268. var shapeUV = this._uvsToShapeUV(meshUV);
  55269. var posfunc = options ? options.positionFunction : null;
  55270. var vtxfunc = options ? options.vertexFunction : null;
  55271. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55272. // particles
  55273. var idx = this.nbParticles;
  55274. for (var i = 0; i < nb; i++) {
  55275. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  55276. if (this._updatable) {
  55277. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  55278. }
  55279. this._index += shape.length;
  55280. idx++;
  55281. }
  55282. this.nbParticles += nb;
  55283. this._shapeCounter++;
  55284. return this._shapeCounter - 1;
  55285. };
  55286. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55287. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55288. this._resetCopy();
  55289. if (particle._model._positionFunction) {
  55290. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55291. }
  55292. if (this._copy.rotationQuaternion) {
  55293. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55294. }
  55295. else {
  55296. this._yaw = this._copy.rotation.y;
  55297. this._pitch = this._copy.rotation.x;
  55298. this._roll = this._copy.rotation.z;
  55299. this._quaternionRotationYPR();
  55300. }
  55301. this._quaternionToRotationMatrix();
  55302. this._shape = particle._model._shape;
  55303. for (var pt = 0; pt < this._shape.length; pt++) {
  55304. this._vertex.x = this._shape[pt].x;
  55305. this._vertex.y = this._shape[pt].y;
  55306. this._vertex.z = this._shape[pt].z;
  55307. if (particle._model._vertexFunction) {
  55308. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55309. }
  55310. this._vertex.x *= this._copy.scaling.x;
  55311. this._vertex.y *= this._copy.scaling.y;
  55312. this._vertex.z *= this._copy.scaling.z;
  55313. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55314. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55315. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55316. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55317. }
  55318. particle.position.x = 0;
  55319. particle.position.y = 0;
  55320. particle.position.z = 0;
  55321. particle.rotation.x = 0;
  55322. particle.rotation.y = 0;
  55323. particle.rotation.z = 0;
  55324. particle.rotationQuaternion = null;
  55325. particle.scaling.x = 1;
  55326. particle.scaling.y = 1;
  55327. particle.scaling.z = 1;
  55328. };
  55329. /**
  55330. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55331. */
  55332. SolidParticleSystem.prototype.rebuildMesh = function () {
  55333. for (var p = 0; p < this.particles.length; p++) {
  55334. this._rebuildParticle(this.particles[p]);
  55335. }
  55336. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55337. };
  55338. /**
  55339. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55340. * This method calls `updateParticle()` for each particle of the SPS.
  55341. * For an animated SPS, it is usually called within the render loop.
  55342. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55343. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55344. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55345. */
  55346. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55347. if (start === void 0) { start = 0; }
  55348. if (end === void 0) { end = this.nbParticles - 1; }
  55349. if (update === void 0) { update = true; }
  55350. if (!this._updatable) {
  55351. return;
  55352. }
  55353. // custom beforeUpdate
  55354. this.beforeUpdateParticles(start, end, update);
  55355. this._cam_axisX.x = 1;
  55356. this._cam_axisX.y = 0;
  55357. this._cam_axisX.z = 0;
  55358. this._cam_axisY.x = 0;
  55359. this._cam_axisY.y = 1;
  55360. this._cam_axisY.z = 0;
  55361. this._cam_axisZ.x = 0;
  55362. this._cam_axisZ.y = 0;
  55363. this._cam_axisZ.z = 1;
  55364. // if the particles will always face the camera
  55365. if (this.billboard) {
  55366. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  55367. this._yaw = this.mesh.rotation.y;
  55368. this._pitch = this.mesh.rotation.x;
  55369. this._roll = this.mesh.rotation.z;
  55370. this._quaternionRotationYPR();
  55371. this._quaternionToRotationMatrix();
  55372. this._rotMatrix.invertToRef(this._invertMatrix);
  55373. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  55374. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  55375. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  55376. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  55377. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  55378. this._cam_axisY.normalize();
  55379. this._cam_axisX.normalize();
  55380. this._cam_axisZ.normalize();
  55381. }
  55382. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55383. var idx = 0;
  55384. var index = 0;
  55385. var colidx = 0;
  55386. var colorIndex = 0;
  55387. var uvidx = 0;
  55388. var uvIndex = 0;
  55389. var pt = 0;
  55390. if (this._computeBoundingBox) {
  55391. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55392. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55393. }
  55394. // particle loop
  55395. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  55396. for (var p = start; p <= end; p++) {
  55397. this._particle = this.particles[p];
  55398. this._shape = this._particle._model._shape;
  55399. this._shapeUV = this._particle._model._shapeUV;
  55400. // call to custom user function to update the particle properties
  55401. this.updateParticle(this._particle);
  55402. if (this._particle.isVisible) {
  55403. // particle rotation matrix
  55404. if (this.billboard) {
  55405. this._particle.rotation.x = 0.0;
  55406. this._particle.rotation.y = 0.0;
  55407. }
  55408. if (this._computeParticleRotation) {
  55409. if (this._particle.rotationQuaternion) {
  55410. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55411. }
  55412. else {
  55413. this._yaw = this._particle.rotation.y;
  55414. this._pitch = this._particle.rotation.x;
  55415. this._roll = this._particle.rotation.z;
  55416. this._quaternionRotationYPR();
  55417. }
  55418. this._quaternionToRotationMatrix();
  55419. }
  55420. // particle vertex loop
  55421. for (pt = 0; pt < this._shape.length; pt++) {
  55422. idx = index + pt * 3;
  55423. colidx = colorIndex + pt * 4;
  55424. uvidx = uvIndex + pt * 2;
  55425. this._vertex.x = this._shape[pt].x;
  55426. this._vertex.y = this._shape[pt].y;
  55427. this._vertex.z = this._shape[pt].z;
  55428. if (this._computeParticleVertex) {
  55429. this.updateParticleVertex(this._particle, this._vertex, pt);
  55430. }
  55431. // positions
  55432. this._vertex.x *= this._particle.scaling.x;
  55433. this._vertex.y *= this._particle.scaling.y;
  55434. this._vertex.z *= this._particle.scaling.z;
  55435. 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];
  55436. 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;
  55437. 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;
  55438. 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;
  55439. 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;
  55440. 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;
  55441. 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;
  55442. if (this._computeBoundingBox) {
  55443. if (this._positions32[idx] < this._minimum.x) {
  55444. this._minimum.x = this._positions32[idx];
  55445. }
  55446. if (this._positions32[idx] > this._maximum.x) {
  55447. this._maximum.x = this._positions32[idx];
  55448. }
  55449. if (this._positions32[idx + 1] < this._minimum.y) {
  55450. this._minimum.y = this._positions32[idx + 1];
  55451. }
  55452. if (this._positions32[idx + 1] > this._maximum.y) {
  55453. this._maximum.y = this._positions32[idx + 1];
  55454. }
  55455. if (this._positions32[idx + 2] < this._minimum.z) {
  55456. this._minimum.z = this._positions32[idx + 2];
  55457. }
  55458. if (this._positions32[idx + 2] > this._maximum.z) {
  55459. this._maximum.z = this._positions32[idx + 2];
  55460. }
  55461. }
  55462. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  55463. if (!this._computeParticleVertex && !this.billboard) {
  55464. this._normal.x = this._fixedNormal32[idx];
  55465. this._normal.y = this._fixedNormal32[idx + 1];
  55466. this._normal.z = this._fixedNormal32[idx + 2];
  55467. 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];
  55468. 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;
  55469. 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;
  55470. 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;
  55471. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55472. 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;
  55473. 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;
  55474. }
  55475. if (this._computeParticleColor) {
  55476. this._colors32[colidx] = this._particle.color.r;
  55477. this._colors32[colidx + 1] = this._particle.color.g;
  55478. this._colors32[colidx + 2] = this._particle.color.b;
  55479. this._colors32[colidx + 3] = this._particle.color.a;
  55480. }
  55481. if (this._computeParticleTexture) {
  55482. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55483. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55484. }
  55485. }
  55486. }
  55487. else {
  55488. for (pt = 0; pt < this._shape.length; pt++) {
  55489. idx = index + pt * 3;
  55490. colidx = colorIndex + pt * 4;
  55491. uvidx = uvIndex + pt * 2;
  55492. this._positions32[idx] = this._camera.position.x;
  55493. this._positions32[idx + 1] = this._camera.position.y;
  55494. this._positions32[idx + 2] = this._camera.position.z;
  55495. this._normals32[idx] = 0.0;
  55496. this._normals32[idx + 1] = 0.0;
  55497. this._normals32[idx + 2] = 0.0;
  55498. if (this._computeParticleColor) {
  55499. this._colors32[colidx] = this._particle.color.r;
  55500. this._colors32[colidx + 1] = this._particle.color.g;
  55501. this._colors32[colidx + 2] = this._particle.color.b;
  55502. this._colors32[colidx + 3] = this._particle.color.a;
  55503. }
  55504. if (this._computeParticleTexture) {
  55505. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55506. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55507. }
  55508. }
  55509. }
  55510. // increment indexes for the next particle
  55511. index = idx + 3;
  55512. colorIndex = colidx + 4;
  55513. uvIndex = uvidx + 2;
  55514. }
  55515. // if the VBO must be updated
  55516. if (update) {
  55517. if (this._computeParticleColor) {
  55518. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55519. }
  55520. if (this._computeParticleTexture) {
  55521. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55522. }
  55523. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55524. if (!this.mesh.areNormalsFrozen) {
  55525. if (this._computeParticleVertex || this.billboard) {
  55526. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55527. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  55528. for (var i = 0; i < this._normals32.length; i++) {
  55529. this._fixedNormal32[i] = this._normals32[i];
  55530. }
  55531. }
  55532. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55533. }
  55534. }
  55535. if (this._computeBoundingBox) {
  55536. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55537. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55538. }
  55539. this.afterUpdateParticles(start, end, update);
  55540. };
  55541. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55542. this._halfroll = this._roll * 0.5;
  55543. this._halfpitch = this._pitch * 0.5;
  55544. this._halfyaw = this._yaw * 0.5;
  55545. this._sinRoll = Math.sin(this._halfroll);
  55546. this._cosRoll = Math.cos(this._halfroll);
  55547. this._sinPitch = Math.sin(this._halfpitch);
  55548. this._cosPitch = Math.cos(this._halfpitch);
  55549. this._sinYaw = Math.sin(this._halfyaw);
  55550. this._cosYaw = Math.cos(this._halfyaw);
  55551. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  55552. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  55553. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  55554. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  55555. };
  55556. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55557. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55558. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55559. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55560. this._rotMatrix.m[3] = 0;
  55561. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55562. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55563. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55564. this._rotMatrix.m[7] = 0;
  55565. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55566. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55567. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55568. this._rotMatrix.m[11] = 0;
  55569. this._rotMatrix.m[12] = 0;
  55570. this._rotMatrix.m[13] = 0;
  55571. this._rotMatrix.m[14] = 0;
  55572. this._rotMatrix.m[15] = 1.0;
  55573. };
  55574. /**
  55575. * Disposes the SPS
  55576. */
  55577. SolidParticleSystem.prototype.dispose = function () {
  55578. this.mesh.dispose();
  55579. this.vars = null;
  55580. // drop references to internal big arrays for the GC
  55581. this._positions = null;
  55582. this._indices = null;
  55583. this._normals = null;
  55584. this._uvs = null;
  55585. this._colors = null;
  55586. this._positions32 = null;
  55587. this._normals32 = null;
  55588. this._fixedNormal32 = null;
  55589. this._uvs32 = null;
  55590. this._colors32 = null;
  55591. this.pickedParticles = null;
  55592. };
  55593. /**
  55594. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55595. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55596. */
  55597. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55598. if (!this._isVisibilityBoxLocked) {
  55599. this.mesh.refreshBoundingInfo();
  55600. }
  55601. };
  55602. /**
  55603. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55604. * @param size the size (float) of the visibility box
  55605. * note : this doesn't lock the SPS mesh bounding box.
  55606. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55607. */
  55608. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55609. var vis = size / 2;
  55610. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55611. };
  55612. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55613. // getter and setter
  55614. get: function () {
  55615. return this._alwaysVisible;
  55616. },
  55617. /**
  55618. * Sets the SPS as always visible or not
  55619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55620. */
  55621. set: function (val) {
  55622. this._alwaysVisible = val;
  55623. this.mesh.alwaysSelectAsActiveMesh = val;
  55624. },
  55625. enumerable: true,
  55626. configurable: true
  55627. });
  55628. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55629. get: function () {
  55630. return this._isVisibilityBoxLocked;
  55631. },
  55632. /**
  55633. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55634. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55635. */
  55636. set: function (val) {
  55637. this._isVisibilityBoxLocked = val;
  55638. this.mesh.getBoundingInfo().isLocked = val;
  55639. },
  55640. enumerable: true,
  55641. configurable: true
  55642. });
  55643. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55644. // getters
  55645. get: function () {
  55646. return this._computeParticleRotation;
  55647. },
  55648. // Optimizer setters
  55649. /**
  55650. * Tells to `setParticles()` to compute the particle rotations or not.
  55651. * Default value : true. The SPS is faster when it's set to false.
  55652. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55653. */
  55654. set: function (val) {
  55655. this._computeParticleRotation = val;
  55656. },
  55657. enumerable: true,
  55658. configurable: true
  55659. });
  55660. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55661. get: function () {
  55662. return this._computeParticleColor;
  55663. },
  55664. /**
  55665. * Tells to `setParticles()` to compute the particle colors or not.
  55666. * Default value : true. The SPS is faster when it's set to false.
  55667. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55668. */
  55669. set: function (val) {
  55670. this._computeParticleColor = val;
  55671. },
  55672. enumerable: true,
  55673. configurable: true
  55674. });
  55675. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55676. get: function () {
  55677. return this._computeParticleTexture;
  55678. },
  55679. /**
  55680. * Tells to `setParticles()` to compute the particle textures or not.
  55681. * Default value : true. The SPS is faster when it's set to false.
  55682. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55683. */
  55684. set: function (val) {
  55685. this._computeParticleTexture = val;
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55691. get: function () {
  55692. return this._computeParticleVertex;
  55693. },
  55694. /**
  55695. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55696. * Default value : false. The SPS is faster when it's set to false.
  55697. * Note : the particle custom vertex positions aren't stored values.
  55698. */
  55699. set: function (val) {
  55700. this._computeParticleVertex = val;
  55701. },
  55702. enumerable: true,
  55703. configurable: true
  55704. });
  55705. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55706. get: function () {
  55707. return this._computeBoundingBox;
  55708. },
  55709. /**
  55710. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55711. */
  55712. set: function (val) {
  55713. this._computeBoundingBox = val;
  55714. },
  55715. enumerable: true,
  55716. configurable: true
  55717. });
  55718. // =======================================================================
  55719. // Particle behavior logic
  55720. // these following methods may be overwritten by the user to fit his needs
  55721. /**
  55722. * This function does nothing. It may be overwritten to set all the particle first values.
  55723. * The SPS doesn't call this function, you may have to call it by your own.
  55724. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55725. */
  55726. SolidParticleSystem.prototype.initParticles = function () {
  55727. };
  55728. /**
  55729. * This function does nothing. It may be overwritten to recycle a particle.
  55730. * The SPS doesn't call this function, you may have to call it by your own.
  55731. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55732. */
  55733. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55734. return particle;
  55735. };
  55736. /**
  55737. * Updates a particle : this function should be overwritten by the user.
  55738. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55740. * ex : just set a particle position or velocity and recycle conditions
  55741. */
  55742. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55743. return particle;
  55744. };
  55745. /**
  55746. * Updates a vertex of a particle : it can be overwritten by the user.
  55747. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55748. * @param particle the current particle
  55749. * @param vertex the current index of the current particle
  55750. * @param pt the index of the current vertex in the particle shape
  55751. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55752. * ex : just set a vertex particle position
  55753. */
  55754. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55755. return vertex;
  55756. };
  55757. /**
  55758. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55759. * This does nothing and may be overwritten by the user.
  55760. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55761. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55762. * @param update the boolean update value actually passed to setParticles()
  55763. */
  55764. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55765. };
  55766. /**
  55767. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55768. * This will be passed three parameters.
  55769. * This does nothing and may be overwritten by the user.
  55770. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55771. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55772. * @param update the boolean update value actually passed to setParticles()
  55773. */
  55774. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55775. };
  55776. return SolidParticleSystem;
  55777. })();
  55778. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55779. })(BABYLON || (BABYLON = {}));
  55780. var BABYLON;
  55781. (function (BABYLON) {
  55782. var Internals;
  55783. (function (Internals) {
  55784. var FileFaceOrientation = (function () {
  55785. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  55786. this.name = name;
  55787. this.worldAxisForNormal = worldAxisForNormal;
  55788. this.worldAxisForFileX = worldAxisForFileX;
  55789. this.worldAxisForFileY = worldAxisForFileY;
  55790. }
  55791. return FileFaceOrientation;
  55792. })();
  55793. ;
  55794. /**
  55795. * Helper class dealing with the extraction of spherical polynomial dataArray
  55796. * from a cube map.
  55797. */
  55798. var CubeMapToSphericalPolynomialTools = (function () {
  55799. function CubeMapToSphericalPolynomialTools() {
  55800. }
  55801. /**
  55802. * Converts a cubemap to the according Spherical Polynomial data.
  55803. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55804. *
  55805. * @param cubeInfo The Cube map to extract the information from.
  55806. * @return The Spherical Polynomial data.
  55807. */
  55808. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  55809. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  55810. var totalSolidAngle = 0.0;
  55811. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  55812. var du = 2.0 / cubeInfo.size;
  55813. var dv = du;
  55814. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  55815. var minUV = du * 0.5 - 1.0;
  55816. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55817. var fileFace = this.FileFaces[faceIndex];
  55818. var dataArray = cubeInfo[fileFace.name];
  55819. var v = minUV;
  55820. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  55821. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  55822. // Because SP is still linear, so summation is fine in that basis.
  55823. for (var y = 0; y < cubeInfo.size; y++) {
  55824. var u = minUV;
  55825. for (var x = 0; x < cubeInfo.size; x++) {
  55826. // World direction (not normalised)
  55827. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  55828. worldDirection.normalize();
  55829. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55830. if (1) {
  55831. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  55832. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  55833. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  55834. var color = new BABYLON.Color3(r, g, b);
  55835. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55836. }
  55837. else {
  55838. if (faceIndex == 0) {
  55839. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55840. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55841. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55842. }
  55843. else if (faceIndex == 1) {
  55844. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55845. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55846. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55847. }
  55848. else if (faceIndex == 2) {
  55849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55850. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55851. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55852. }
  55853. else if (faceIndex == 3) {
  55854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55855. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55856. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55857. }
  55858. else if (faceIndex == 4) {
  55859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55861. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55862. }
  55863. else if (faceIndex == 5) {
  55864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55866. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55867. }
  55868. 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]);
  55869. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55870. }
  55871. totalSolidAngle += deltaSolidAngle;
  55872. u += du;
  55873. }
  55874. v += dv;
  55875. }
  55876. }
  55877. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  55878. var correction = correctSolidAngle / totalSolidAngle;
  55879. sphericalHarmonics.scale(correction);
  55880. // Additionally scale by pi -- audit needed
  55881. sphericalHarmonics.scale(1.0 / Math.PI);
  55882. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55883. };
  55884. CubeMapToSphericalPolynomialTools.FileFaces = [
  55885. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55886. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55887. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55888. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55889. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55890. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55891. ];
  55892. return CubeMapToSphericalPolynomialTools;
  55893. })();
  55894. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55895. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55896. })(BABYLON || (BABYLON = {}));
  55897. var BABYLON;
  55898. (function (BABYLON) {
  55899. var Internals;
  55900. (function (Internals) {
  55901. /**
  55902. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55903. */
  55904. var PanoramaToCubeMapTools = (function () {
  55905. function PanoramaToCubeMapTools() {
  55906. }
  55907. /**
  55908. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55909. *
  55910. * @param float32Array The source data.
  55911. * @param inputWidth The width of the input panorama.
  55912. * @param inputhHeight The height of the input panorama.
  55913. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55914. * @return The cubemap data
  55915. */
  55916. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55917. if (!float32Array) {
  55918. throw "ConvertPanoramaToCubemap: input cannot be null";
  55919. }
  55920. if (float32Array.length != inputWidth * inputHeight * 3) {
  55921. throw "ConvertPanoramaToCubemap: input size is wrong";
  55922. }
  55923. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55924. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55925. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55926. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55927. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55928. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55929. return {
  55930. front: textureFront,
  55931. back: textureBack,
  55932. left: textureLeft,
  55933. right: textureRight,
  55934. up: textureUp,
  55935. down: textureDown,
  55936. size: size
  55937. };
  55938. };
  55939. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55940. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55941. var textureArray = new Float32Array(buffer);
  55942. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55943. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55944. var dy = 1 / texSize;
  55945. var fy = 0;
  55946. for (var y = 0; y < texSize; y++) {
  55947. var xv1 = faceData[0];
  55948. var xv2 = faceData[2];
  55949. for (var x = 0; x < texSize; x++) {
  55950. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55951. v.normalize();
  55952. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55953. // 3 channels per pixels
  55954. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55955. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55956. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55957. xv1 = xv1.add(rotDX1);
  55958. xv2 = xv2.add(rotDX2);
  55959. }
  55960. fy += dy;
  55961. }
  55962. return textureArray;
  55963. };
  55964. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55965. var theta = Math.atan2(vDir.z, vDir.x);
  55966. var phi = Math.acos(vDir.y);
  55967. while (theta < -Math.PI)
  55968. theta += 2 * Math.PI;
  55969. while (theta > Math.PI)
  55970. theta -= 2 * Math.PI;
  55971. var dx = theta / Math.PI;
  55972. var dy = phi / Math.PI;
  55973. // recenter.
  55974. dx = dx * 0.5 + 0.5;
  55975. var px = Math.round(dx * inputWidth);
  55976. if (px < 0)
  55977. px = 0;
  55978. else if (px >= inputWidth)
  55979. px = inputWidth - 1;
  55980. var py = Math.round(dy * inputHeight);
  55981. if (py < 0)
  55982. py = 0;
  55983. else if (py >= inputHeight)
  55984. py = inputHeight - 1;
  55985. var inputY = (inputHeight - py - 1);
  55986. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55987. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55988. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55989. return {
  55990. r: r,
  55991. g: g,
  55992. b: b
  55993. };
  55994. };
  55995. PanoramaToCubeMapTools.FACE_FRONT = [
  55996. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55997. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55998. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55999. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56000. ];
  56001. PanoramaToCubeMapTools.FACE_BACK = [
  56002. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56003. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56004. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56005. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56006. ];
  56007. PanoramaToCubeMapTools.FACE_RIGHT = [
  56008. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56009. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56010. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56011. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56012. ];
  56013. PanoramaToCubeMapTools.FACE_LEFT = [
  56014. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56015. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56016. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56017. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56018. ];
  56019. PanoramaToCubeMapTools.FACE_DOWN = [
  56020. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56021. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56022. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56023. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56024. ];
  56025. PanoramaToCubeMapTools.FACE_UP = [
  56026. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56027. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56028. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56029. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56030. ];
  56031. return PanoramaToCubeMapTools;
  56032. })();
  56033. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56034. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56035. })(BABYLON || (BABYLON = {}));
  56036. var BABYLON;
  56037. (function (BABYLON) {
  56038. var Internals;
  56039. (function (Internals) {
  56040. ;
  56041. /**
  56042. * This groups tools to convert HDR texture to native colors array.
  56043. */
  56044. var HDRTools = (function () {
  56045. function HDRTools() {
  56046. }
  56047. HDRTools.Ldexp = function (mantissa, exponent) {
  56048. if (exponent > 1023) {
  56049. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56050. }
  56051. if (exponent < -1074) {
  56052. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56053. }
  56054. return mantissa * Math.pow(2, exponent);
  56055. };
  56056. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56057. if (exponent > 0) {
  56058. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56059. float32array[index + 0] = red * exponent;
  56060. float32array[index + 1] = green * exponent;
  56061. float32array[index + 2] = blue * exponent;
  56062. }
  56063. else {
  56064. float32array[index + 0] = 0;
  56065. float32array[index + 1] = 0;
  56066. float32array[index + 2] = 0;
  56067. }
  56068. };
  56069. HDRTools.readStringLine = function (uint8array, startIndex) {
  56070. var line = "";
  56071. var character = "";
  56072. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56073. character = String.fromCharCode(uint8array[i]);
  56074. if (character == "\n") {
  56075. break;
  56076. }
  56077. line += character;
  56078. }
  56079. return line;
  56080. };
  56081. /**
  56082. * Reads header information from an RGBE texture stored in a native array.
  56083. * More information on this format are available here:
  56084. * https://en.wikipedia.org/wiki/RGBE_image_format
  56085. *
  56086. * @param uint8array The binary file stored in native array.
  56087. * @return The header information.
  56088. */
  56089. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56090. var height = 0;
  56091. var width = 0;
  56092. var line = this.readStringLine(uint8array, 0);
  56093. if (line[0] != '#' || line[1] != '?') {
  56094. throw "Bad HDR Format.";
  56095. }
  56096. var endOfHeader = false;
  56097. var findFormat = false;
  56098. var lineIndex = 0;
  56099. do {
  56100. lineIndex += (line.length + 1);
  56101. line = this.readStringLine(uint8array, lineIndex);
  56102. if (line == "FORMAT=32-bit_rle_rgbe") {
  56103. findFormat = true;
  56104. }
  56105. else if (line.length == 0) {
  56106. endOfHeader = true;
  56107. }
  56108. } while (!endOfHeader);
  56109. if (!findFormat) {
  56110. throw "HDR Bad header format, unsupported FORMAT";
  56111. }
  56112. lineIndex += (line.length + 1);
  56113. line = this.readStringLine(uint8array, lineIndex);
  56114. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56115. var match = sizeRegexp.exec(line);
  56116. // TODO. Support +Y and -X if needed.
  56117. if (match.length < 3) {
  56118. throw "HDR Bad header format, no size";
  56119. }
  56120. width = parseInt(match[2]);
  56121. height = parseInt(match[1]);
  56122. if (width < 8 || width > 0x7fff) {
  56123. throw "HDR Bad header format, unsupported size";
  56124. }
  56125. lineIndex += (line.length + 1);
  56126. return {
  56127. height: height,
  56128. width: width,
  56129. dataPosition: lineIndex
  56130. };
  56131. };
  56132. /**
  56133. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56134. * This RGBE texture needs to store the information as a panorama.
  56135. *
  56136. * More information on this format are available here:
  56137. * https://en.wikipedia.org/wiki/RGBE_image_format
  56138. *
  56139. * @param buffer The binary file stored in an array buffer.
  56140. * @param size The expected size of the extracted cubemap.
  56141. * @return The Cube Map information.
  56142. */
  56143. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56144. var uint8array = new Uint8Array(buffer);
  56145. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56146. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56147. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56148. return cubeMapData;
  56149. };
  56150. /**
  56151. * Returns the pixels data extracted from an RGBE texture.
  56152. * This pixels will be stored left to right up to down in the R G B order in one array.
  56153. *
  56154. * More information on this format are available here:
  56155. * https://en.wikipedia.org/wiki/RGBE_image_format
  56156. *
  56157. * @param uint8array The binary file stored in an array buffer.
  56158. * @param hdrInfo The header information of the file.
  56159. * @return The pixels data in RGB right to left up to down order.
  56160. */
  56161. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56162. // Keep for multi format supports.
  56163. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56164. };
  56165. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56166. var num_scanlines = hdrInfo.height;
  56167. var scanline_width = hdrInfo.width;
  56168. var a, b, c, d, count;
  56169. var dataIndex = hdrInfo.dataPosition;
  56170. var index = 0, endIndex = 0, i = 0;
  56171. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56172. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56173. // 3 channels of 4 bytes per pixel in float.
  56174. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56175. var resultArray = new Float32Array(resultBuffer);
  56176. // read in each successive scanline
  56177. while (num_scanlines > 0) {
  56178. a = uint8array[dataIndex++];
  56179. b = uint8array[dataIndex++];
  56180. c = uint8array[dataIndex++];
  56181. d = uint8array[dataIndex++];
  56182. if (a != 2 || b != 2 || (c & 0x80)) {
  56183. // this file is not run length encoded
  56184. throw "HDR Bad header format, not RLE";
  56185. }
  56186. if (((c << 8) | d) != scanline_width) {
  56187. throw "HDR Bad header format, wrong scan line width";
  56188. }
  56189. index = 0;
  56190. // read each of the four channels for the scanline into the buffer
  56191. for (i = 0; i < 4; i++) {
  56192. endIndex = (i + 1) * scanline_width;
  56193. while (index < endIndex) {
  56194. a = uint8array[dataIndex++];
  56195. b = uint8array[dataIndex++];
  56196. if (a > 128) {
  56197. // a run of the same value
  56198. count = a - 128;
  56199. if ((count == 0) || (count > endIndex - index)) {
  56200. throw "HDR Bad Format, bad scanline data (run)";
  56201. }
  56202. while (count-- > 0) {
  56203. scanLineArray[index++] = b;
  56204. }
  56205. }
  56206. else {
  56207. // a non-run
  56208. count = a;
  56209. if ((count == 0) || (count > endIndex - index)) {
  56210. throw "HDR Bad Format, bad scanline data (non-run)";
  56211. }
  56212. scanLineArray[index++] = b;
  56213. if (--count > 0) {
  56214. for (var j = 0; j < count; j++) {
  56215. scanLineArray[index++] = uint8array[dataIndex++];
  56216. }
  56217. }
  56218. }
  56219. }
  56220. }
  56221. // now convert data from buffer into floats
  56222. for (i = 0; i < scanline_width; i++) {
  56223. a = scanLineArray[i];
  56224. b = scanLineArray[i + scanline_width];
  56225. c = scanLineArray[i + 2 * scanline_width];
  56226. d = scanLineArray[i + 3 * scanline_width];
  56227. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56228. }
  56229. num_scanlines--;
  56230. }
  56231. return resultArray;
  56232. };
  56233. return HDRTools;
  56234. })();
  56235. Internals.HDRTools = HDRTools;
  56236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56237. })(BABYLON || (BABYLON = {}));
  56238. //_______________________________________________________________
  56239. // Extracted from CubeMapGen:
  56240. // https://code.google.com/archive/p/cubemapgen/
  56241. //
  56242. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56243. //_______________________________________________________________
  56244. var BABYLON;
  56245. (function (BABYLON) {
  56246. var Internals;
  56247. (function (Internals) {
  56248. /**
  56249. * The bounding box information used during the conversion process.
  56250. */
  56251. var CMGBoundinBox = (function () {
  56252. function CMGBoundinBox() {
  56253. this.min = new BABYLON.Vector3(0, 0, 0);
  56254. this.max = new BABYLON.Vector3(0, 0, 0);
  56255. this.clear();
  56256. }
  56257. CMGBoundinBox.prototype.clear = function () {
  56258. this.min.x = CMGBoundinBox.MAX;
  56259. this.min.y = CMGBoundinBox.MAX;
  56260. this.min.z = CMGBoundinBox.MAX;
  56261. this.max.x = CMGBoundinBox.MIN;
  56262. this.max.y = CMGBoundinBox.MIN;
  56263. this.max.z = CMGBoundinBox.MIN;
  56264. };
  56265. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56266. this.min.x = Math.min(this.min.x, x);
  56267. this.min.y = Math.min(this.min.y, y);
  56268. this.min.z = Math.min(this.min.z, z);
  56269. this.max.x = Math.max(this.max.x, x);
  56270. this.max.y = Math.max(this.max.y, y);
  56271. this.max.z = Math.max(this.max.z, z);
  56272. };
  56273. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56274. this.min.x = Math.max(this.min.x, x);
  56275. this.min.y = Math.max(this.min.y, y);
  56276. this.min.z = Math.max(this.min.z, z);
  56277. };
  56278. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56279. this.max.x = Math.min(this.max.x, x);
  56280. this.max.y = Math.min(this.max.y, y);
  56281. this.max.z = Math.min(this.max.z, z);
  56282. };
  56283. CMGBoundinBox.prototype.empty = function () {
  56284. if ((this.min.x > this.max.y) ||
  56285. (this.min.y > this.max.y) ||
  56286. (this.min.z > this.max.y)) {
  56287. return true;
  56288. }
  56289. else {
  56290. return false;
  56291. }
  56292. };
  56293. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56294. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56295. return CMGBoundinBox;
  56296. })();
  56297. /**
  56298. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56299. * required by the glossinees of a material.
  56300. *
  56301. * This only supports the cosine drop power as well as Warp fixup generation method.
  56302. *
  56303. * This is using the process from CubeMapGen described here:
  56304. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56305. */
  56306. var PMREMGenerator = (function () {
  56307. /**
  56308. * Constructor of the generator.
  56309. *
  56310. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56311. * @param inputSize The size of the cubemap faces
  56312. * @param outputSize The size of the output cubemap faces
  56313. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56314. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56315. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56316. * @param specularPower The max specular level of the desired cubemap
  56317. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56318. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56319. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56320. */
  56321. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56322. this.input = input;
  56323. this.inputSize = inputSize;
  56324. this.outputSize = outputSize;
  56325. this.maxNumMipLevels = maxNumMipLevels;
  56326. this.numChannels = numChannels;
  56327. this.isFloat = isFloat;
  56328. this.specularPower = specularPower;
  56329. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56330. this.excludeBase = excludeBase;
  56331. this.fixup = fixup;
  56332. this._outputSurface = [];
  56333. this._numMipLevels = 0;
  56334. }
  56335. /**
  56336. * Launches the filter process and return the result.
  56337. *
  56338. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56339. */
  56340. PMREMGenerator.prototype.filterCubeMap = function () {
  56341. // Init cubemap processor
  56342. this.init();
  56343. // Filters the cubemap
  56344. this.filterCubeMapMipChain();
  56345. // Returns the filtered mips.
  56346. return this._outputSurface;
  56347. };
  56348. PMREMGenerator.prototype.init = function () {
  56349. var i;
  56350. var j;
  56351. var mipLevelSize;
  56352. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56353. if (this.maxNumMipLevels == 0) {
  56354. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56355. }
  56356. //first miplevel size
  56357. mipLevelSize = this.outputSize;
  56358. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56359. for (j = 0; j < this.maxNumMipLevels; j++) {
  56360. this._outputSurface.length++;
  56361. this._outputSurface[j] = [];
  56362. //Iterate over faces for output images
  56363. for (i = 0; i < 6; i++) {
  56364. this._outputSurface[j].length++;
  56365. // Initializes a new array for the output.
  56366. if (this.isFloat) {
  56367. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56368. }
  56369. else {
  56370. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56371. }
  56372. }
  56373. //next mip level is half size
  56374. mipLevelSize >>= 1;
  56375. this._numMipLevels++;
  56376. //terminate if mip chain becomes too small
  56377. if (mipLevelSize == 0) {
  56378. this.maxNumMipLevels = j;
  56379. return;
  56380. }
  56381. }
  56382. };
  56383. //--------------------------------------------------------------------------------------
  56384. //Cube map filtering and mip chain generation.
  56385. // the cube map filtereing is specified using a number of parameters:
  56386. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56387. // indicates the region of the hemisphere to filter over for each tap.
  56388. //
  56389. // Note that the top mip level is also a filtered version of the original input images
  56390. // as well in order to create mip chains for diffuse environment illumination.
  56391. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56392. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56393. //
  56394. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56395. // is a_InitialMipAngle
  56396. //
  56397. // The angle for the subsequent levels of the mip chain are specified by their parents
  56398. // filtering angle and a per-level scale and bias
  56399. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56400. //
  56401. //--------------------------------------------------------------------------------------
  56402. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56403. // First, take count of the lighting model to modify SpecularPower
  56404. // 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;
  56405. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56406. //Cone angle start (for generating subsequent mip levels)
  56407. var currentSpecularPower = this.specularPower;
  56408. //Build filter lookup tables based on the source miplevel size
  56409. this.precomputeFilterLookupTables(this.inputSize);
  56410. // Note that we need to filter the first level before generating mipmap
  56411. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56412. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56413. // TODO : Write a function to copy and scale the base mipmap in output
  56414. // I am just lazy here and just put a high specular power value, and do some if.
  56415. if (this.excludeBase && (levelIndex == 0)) {
  56416. // 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).
  56417. currentSpecularPower = 100000.0;
  56418. }
  56419. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56420. var srcCubeImage = this.input;
  56421. var dstCubeImage = this._outputSurface[levelIndex];
  56422. var dstSize = this.outputSize >> levelIndex;
  56423. // Compute required angle.
  56424. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56425. // filter cube surfaces
  56426. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56427. // fix seams
  56428. if (this.fixup) {
  56429. this.fixupCubeEdges(dstCubeImage, dstSize);
  56430. }
  56431. // Decrease the specular power to generate the mipmap chain
  56432. // TODO : Use another method for Exclude (see first comment at start of the function
  56433. if (this.excludeBase && (levelIndex == 0)) {
  56434. currentSpecularPower = this.specularPower;
  56435. }
  56436. currentSpecularPower *= this.cosinePowerDropPerMip;
  56437. }
  56438. };
  56439. //--------------------------------------------------------------------------------------
  56440. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56441. // It allow to optimize the texel to access base on the specular power.
  56442. //--------------------------------------------------------------------------------------
  56443. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56444. // We want to find the alpha such that:
  56445. // cos(alpha)^cosinePower = epsilon
  56446. // That's: acos(epsilon^(1/cosinePower))
  56447. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  56448. var angle = 180.0;
  56449. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  56450. angle *= 180.0 / Math.PI; // Convert to degree
  56451. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  56452. return angle;
  56453. };
  56454. //--------------------------------------------------------------------------------------
  56455. //Builds the following lookup tables prior to filtering:
  56456. // -normalizer cube map
  56457. // -tap weight lookup table
  56458. //
  56459. //--------------------------------------------------------------------------------------
  56460. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  56461. var srcTexelAngle;
  56462. var iCubeFace;
  56463. //clear pre-existing normalizer cube map
  56464. this._normCubeMap = [];
  56465. //Normalized vectors per cubeface and per-texel solid angle
  56466. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  56467. };
  56468. //--------------------------------------------------------------------------------------
  56469. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  56470. //
  56471. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  56472. //
  56473. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  56474. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  56475. // below
  56476. //--------------------------------------------------------------------------------------
  56477. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  56478. var iCubeFace;
  56479. var u;
  56480. var v;
  56481. //iterate over cube faces
  56482. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56483. //First three channels for norm cube, and last channel for solid angle
  56484. this._normCubeMap.push(new Float32Array(size * size * 4));
  56485. //fast texture walk, build normalizer cube map
  56486. var facesData = this.input[iCubeFace];
  56487. for (v = 0; v < size; v++) {
  56488. for (u = 0; u < size; u++) {
  56489. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  56490. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  56491. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  56492. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  56493. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  56494. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  56495. }
  56496. }
  56497. }
  56498. };
  56499. //--------------------------------------------------------------------------------------
  56500. // Convert cubemap face texel coordinates and face idx to 3D vector
  56501. // note the U and V coords are integer coords and range from 0 to size-1
  56502. // this routine can be used to generate a normalizer cube map
  56503. //--------------------------------------------------------------------------------------
  56504. // SL BEGIN
  56505. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  56506. var nvcU;
  56507. var nvcV;
  56508. var tempVec;
  56509. // Change from original AMD code
  56510. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56511. // + 0.5f is for texel center addressing
  56512. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  56513. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  56514. // warp fixup
  56515. if (fixup && size > 1) {
  56516. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  56517. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  56518. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  56519. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  56520. }
  56521. // Get current vector
  56522. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  56523. // U contribution
  56524. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56525. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  56526. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  56527. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  56528. // V contribution and Sum
  56529. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56530. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  56531. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  56532. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  56533. //add face axis
  56534. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  56535. PMREMGenerator._vectorTemp.x += faceAxis[0];
  56536. PMREMGenerator._vectorTemp.y += faceAxis[1];
  56537. PMREMGenerator._vectorTemp.z += faceAxis[2];
  56538. //normalize vector
  56539. PMREMGenerator._vectorTemp.normalize();
  56540. return PMREMGenerator._vectorTemp;
  56541. };
  56542. //--------------------------------------------------------------------------------------
  56543. // Convert 3D vector to cubemap face texel coordinates and face idx
  56544. // note the U and V coords are integer coords and range from 0 to size-1
  56545. // this routine can be used to generate a normalizer cube map
  56546. //
  56547. // returns face IDX and texel coords
  56548. //--------------------------------------------------------------------------------------
  56549. // SL BEGIN
  56550. /*
  56551. Mapping Texture Coordinates to Cube Map Faces
  56552. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  56553. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  56554. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  56555. map arrangement in Pixar's RenderMan package.
  56556. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  56557. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  56558. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  56559. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  56560. the major axis direction). The target column in the table below explains how the major axis direction
  56561. maps to the 2D image of a particular cube map target.
  56562. major axis
  56563. direction target sc tc ma
  56564. ---------- --------------------------------- --- --- ---
  56565. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  56566. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  56567. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  56568. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  56569. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  56570. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  56571. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  56572. an updated (s,t) is calculated as follows
  56573. s = ( sc/|ma| + 1 ) / 2
  56574. t = ( tc/|ma| + 1 ) / 2
  56575. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  56576. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  56577. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  56578. */
  56579. // Note this method return U and V in range from 0 to size-1
  56580. // SL END
  56581. // Store the information in vector3 for convenience (faceindex, u, v)
  56582. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  56583. var maxCoord;
  56584. var faceIdx;
  56585. //absolute value 3
  56586. var absX = Math.abs(x);
  56587. var absY = Math.abs(y);
  56588. var absZ = Math.abs(z);
  56589. if (absX >= absY && absX >= absZ) {
  56590. maxCoord = absX;
  56591. if (x >= 0) {
  56592. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  56593. }
  56594. else {
  56595. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56596. }
  56597. }
  56598. else if (absY >= absX && absY >= absZ) {
  56599. maxCoord = absY;
  56600. if (y >= 0) {
  56601. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56602. }
  56603. else {
  56604. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56605. }
  56606. }
  56607. else {
  56608. maxCoord = absZ;
  56609. if (z >= 0) {
  56610. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56611. }
  56612. else {
  56613. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56614. }
  56615. }
  56616. //divide through by max coord so face vector lies on cube face
  56617. var scale = 1 / maxCoord;
  56618. x *= scale;
  56619. y *= scale;
  56620. z *= scale;
  56621. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56622. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  56623. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56624. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  56625. // Modify original AMD code to return value from 0 to Size - 1
  56626. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  56627. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  56628. PMREMGenerator._vectorTemp.x = faceIdx;
  56629. PMREMGenerator._vectorTemp.y = u;
  56630. PMREMGenerator._vectorTemp.z = v;
  56631. return PMREMGenerator._vectorTemp;
  56632. };
  56633. //--------------------------------------------------------------------------------------
  56634. //Original code from Ignacio CastaÒo
  56635. // This formula is from Manne ÷hrstrˆm's thesis.
  56636. // Take two coordiantes in the range [-1, 1] that define a portion of a
  56637. // cube face and return the area of the projection of that portion on the
  56638. // surface of the sphere.
  56639. //--------------------------------------------------------------------------------------
  56640. PMREMGenerator.prototype.areaElement = function (x, y) {
  56641. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  56642. };
  56643. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  56644. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56645. // (+ 0.5f is for texel center addressing)
  56646. u = (2.0 * (u + 0.5) / size) - 1.0;
  56647. v = (2.0 * (v + 0.5) / size) - 1.0;
  56648. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  56649. var invResolution = 1.0 / size;
  56650. // U and V are the -1..1 texture coordinate on the current face.
  56651. // Get projected area for this texel
  56652. var x0 = u - invResolution;
  56653. var y0 = v - invResolution;
  56654. var x1 = u + invResolution;
  56655. var y1 = v + invResolution;
  56656. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  56657. return solidAngle;
  56658. };
  56659. //--------------------------------------------------------------------------------------
  56660. //The key to the speed of these filtering routines is to quickly define a per-face
  56661. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  56662. // Later these pixels are selectively processed based on their dot products to see if
  56663. // they reside within the filtering cone.
  56664. //
  56665. //This is done by computing the smallest per-texel angle to get a conservative estimate
  56666. // of the number of texels needed to be covered in width and height order to filter the
  56667. // region. the bounding box for the center taps face is defined first, and if the
  56668. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  56669. // defined next
  56670. //--------------------------------------------------------------------------------------
  56671. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  56672. // note that pixels within these regions may be rejected
  56673. // based on the anlge
  56674. var iCubeFace;
  56675. var u;
  56676. var v;
  56677. // bounding box per face to specify region to process
  56678. var filterExtents = [];
  56679. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56680. filterExtents.push(new CMGBoundinBox());
  56681. }
  56682. // min angle a src texel can cover (in degrees)
  56683. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  56684. // angle about center tap to define filter cone
  56685. // filter angle is 1/2 the cone angle
  56686. var filterAngle = filterConeAngle / 2.0;
  56687. //ensure filter angle is larger than a texel
  56688. if (filterAngle < srcTexelAngle) {
  56689. filterAngle = srcTexelAngle;
  56690. }
  56691. //ensure filter cone is always smaller than the hemisphere
  56692. if (filterAngle > 90.0) {
  56693. filterAngle = 90.0;
  56694. }
  56695. // the maximum number of texels in 1D the filter cone angle will cover
  56696. // used to determine bounding box size for filter extents
  56697. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  56698. // ensure conservative region always covers at least one texel
  56699. if (filterSize < 1) {
  56700. filterSize = 1;
  56701. }
  56702. // dotProdThresh threshold based on cone angle to determine whether or not taps
  56703. // reside within the cone angle
  56704. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  56705. // process required faces
  56706. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56707. //iterate over dst cube map face texel
  56708. for (v = 0; v < dstSize; v++) {
  56709. for (u = 0; u < dstSize; u++) {
  56710. //get center tap direction
  56711. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  56712. //clear old per-face filter extents
  56713. this.clearFilterExtents(filterExtents);
  56714. //define per-face filter extents
  56715. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  56716. //perform filtering of src faces using filter extents
  56717. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  56718. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  56719. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  56720. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  56721. }
  56722. }
  56723. }
  56724. };
  56725. //--------------------------------------------------------------------------------------
  56726. //Clear filter extents for the 6 cube map faces
  56727. //--------------------------------------------------------------------------------------
  56728. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  56729. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  56730. filterExtents[iCubeFaces].clear();
  56731. }
  56732. };
  56733. //--------------------------------------------------------------------------------------
  56734. //Define per-face bounding box filter extents
  56735. //
  56736. // These define conservative texel regions in each of the faces the filter can possibly
  56737. // process. When the pixels in the regions are actually processed, the dot product
  56738. // between the tap vector and the center tap vector is used to determine the weight of
  56739. // the tap and whether or not the tap is within the cone.
  56740. //
  56741. //--------------------------------------------------------------------------------------
  56742. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  56743. //neighboring face and bleed over amount, and width of BBOX for
  56744. // left, right, top, and bottom edges of this face
  56745. var bleedOverAmount = [0, 0, 0, 0];
  56746. var bleedOverBBoxMin = [0, 0, 0, 0];
  56747. var bleedOverBBoxMax = [0, 0, 0, 0];
  56748. var neighborFace;
  56749. var neighborEdge;
  56750. var oppositeFaceIdx;
  56751. //get face idx, and u, v info from center tap dir
  56752. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  56753. var faceIdx = result.x;
  56754. var u = result.y;
  56755. var v = result.z;
  56756. //define bbox size within face
  56757. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  56758. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  56759. filterExtents[faceIdx].clampMin(0, 0, 0);
  56760. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  56761. //u and v extent in face corresponding to center tap
  56762. var minU = filterExtents[faceIdx].min.x;
  56763. var minV = filterExtents[faceIdx].min.y;
  56764. var maxU = filterExtents[faceIdx].max.x;
  56765. var maxV = filterExtents[faceIdx].max.y;
  56766. //bleed over amounts for face across u=0 edge (left)
  56767. bleedOverAmount[0] = (bboxSize - u);
  56768. bleedOverBBoxMin[0] = minV;
  56769. bleedOverBBoxMax[0] = maxV;
  56770. //bleed over amounts for face across u=1 edge (right)
  56771. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  56772. bleedOverBBoxMin[1] = minV;
  56773. bleedOverBBoxMax[1] = maxV;
  56774. //bleed over to face across v=0 edge (up)
  56775. bleedOverAmount[2] = (bboxSize - v);
  56776. bleedOverBBoxMin[2] = minU;
  56777. bleedOverBBoxMax[2] = maxU;
  56778. //bleed over to face across v=1 edge (down)
  56779. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  56780. bleedOverBBoxMin[3] = minU;
  56781. bleedOverBBoxMax[3] = maxU;
  56782. //compute bleed over regions in neighboring faces
  56783. for (var i = 0; i < 4; i++) {
  56784. if (bleedOverAmount[i] > 0) {
  56785. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  56786. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  56787. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  56788. // be flipped: the cases are
  56789. // if a left edge mates with a left or bottom edge on the neighbor
  56790. // if a top edge mates with a top or right edge on the neighbor
  56791. // if a right edge mates with a right or top edge on the neighbor
  56792. // if a bottom edge mates with a bottom or left edge on the neighbor
  56793. //Seeing as the edges are enumerated as follows
  56794. // left =0
  56795. // right =1
  56796. // top =2
  56797. // bottom =3
  56798. //
  56799. // so if the edge enums are the same, or the sum of the enums == 3,
  56800. // the bbox needs to be flipped
  56801. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  56802. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  56803. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  56804. }
  56805. //The way the bounding box is extended onto the neighboring face
  56806. // depends on which edge of neighboring face abuts with this one
  56807. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  56808. case PMREMGenerator.CP_EDGE_LEFT:
  56809. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  56810. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56811. break;
  56812. case PMREMGenerator.CP_EDGE_RIGHT:
  56813. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  56814. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56815. break;
  56816. case PMREMGenerator.CP_EDGE_TOP:
  56817. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  56818. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  56819. break;
  56820. case PMREMGenerator.CP_EDGE_BOTTOM:
  56821. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  56822. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  56823. break;
  56824. }
  56825. //clamp filter extents in non-center tap faces to remain within surface
  56826. filterExtents[neighborFace].clampMin(0, 0, 0);
  56827. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  56828. }
  56829. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  56830. // from the center tap face, then process the opposite face entirely for now.
  56831. //Note that the cases in which this happens, what usually happens is that
  56832. // more than one edge bleeds onto the opposite face, and the bounding box
  56833. // encompasses the entire cube map face.
  56834. if (bleedOverAmount[i] > srcSize) {
  56835. //determine opposite face
  56836. switch (faceIdx) {
  56837. case PMREMGenerator.CP_FACE_X_POS:
  56838. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56839. break;
  56840. case PMREMGenerator.CP_FACE_X_NEG:
  56841. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  56842. break;
  56843. case PMREMGenerator.CP_FACE_Y_POS:
  56844. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56845. break;
  56846. case PMREMGenerator.CP_FACE_Y_NEG:
  56847. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56848. break;
  56849. case PMREMGenerator.CP_FACE_Z_POS:
  56850. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56851. break;
  56852. case PMREMGenerator.CP_FACE_Z_NEG:
  56853. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56854. break;
  56855. default:
  56856. break;
  56857. }
  56858. //just encompass entire face for now
  56859. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  56860. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  56861. }
  56862. }
  56863. };
  56864. //--------------------------------------------------------------------------------------
  56865. //ProcessFilterExtents
  56866. // Process bounding box in each cube face
  56867. //
  56868. //--------------------------------------------------------------------------------------
  56869. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  56870. //accumulators are 64-bit floats in order to have the precision needed
  56871. // over a summation of a large number of pixels
  56872. var dstAccum = [0, 0, 0, 0];
  56873. var weightAccum = 0;
  56874. var k = 0;
  56875. var nSrcChannels = this.numChannels;
  56876. // norm cube map and srcCubeMap have same face width
  56877. var faceWidth = srcSize;
  56878. //amount to add to pointer to move to next scanline in images
  56879. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  56880. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  56881. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  56882. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  56883. // iterate over cubefaces
  56884. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56885. //if bbox is non empty
  56886. if (!filterExtents[iFaceIdx].empty()) {
  56887. var uStart = filterExtents[iFaceIdx].min.x;
  56888. var vStart = filterExtents[iFaceIdx].min.y;
  56889. var uEnd = filterExtents[iFaceIdx].max.x;
  56890. var vEnd = filterExtents[iFaceIdx].max.y;
  56891. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56892. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56893. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56894. for (var v = vStart; v <= vEnd; v++) {
  56895. var normCubeRowWalk = 0;
  56896. var srcCubeRowWalk = 0;
  56897. for (var u = uStart; u <= uEnd; u++) {
  56898. //pointer to direction in cube map associated with texel
  56899. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56900. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56901. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56902. //check dot product to see if texel is within cone
  56903. var tapDotProd = texelVectX * centerTapDir.x +
  56904. texelVectY * centerTapDir.y +
  56905. texelVectZ * centerTapDir.z;
  56906. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56907. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56908. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56909. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56910. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56911. // so just adding one to specularpower do the trick.
  56912. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56913. //iterate over channels
  56914. for (k = 0; k < nSrcChannels; k++) {
  56915. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56916. srcCubeRowWalk++;
  56917. }
  56918. weightAccum += weight; //accumulate weight
  56919. }
  56920. else {
  56921. //step across source pixel
  56922. srcCubeRowWalk += nSrcChannels;
  56923. }
  56924. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56925. }
  56926. startIndexNormCubeMap += normCubePitch;
  56927. startIndexSrcCubeMap += srcCubePitch;
  56928. }
  56929. }
  56930. }
  56931. //divide through by weights if weight is non zero
  56932. if (weightAccum != 0.0) {
  56933. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56934. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56935. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56936. if (this.numChannels > 3) {
  56937. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56938. }
  56939. }
  56940. else {
  56941. // otherwise sample nearest
  56942. // get face idx and u, v texel coordinate in face
  56943. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56944. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56945. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56946. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56947. if (this.numChannels > 3) {
  56948. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56949. }
  56950. }
  56951. return PMREMGenerator._vectorTemp;
  56952. };
  56953. //--------------------------------------------------------------------------------------
  56954. // Fixup cube edges
  56955. //
  56956. // average texels on cube map faces across the edges
  56957. // WARP/BENT Method Only.
  56958. //--------------------------------------------------------------------------------------
  56959. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56960. var k;
  56961. var j;
  56962. var i;
  56963. var iFace;
  56964. var iCorner = 0;
  56965. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56966. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56967. // note that if functionality to filter across the three texels for each corner, then
  56968. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56969. var cornerPtr = [
  56970. [[], [], []],
  56971. [[], [], []],
  56972. [[], [], []],
  56973. [[], [], []],
  56974. [[], [], []],
  56975. [[], [], []],
  56976. [[], [], []],
  56977. [[], [], []]
  56978. ];
  56979. //if there is no fixup, or fixup width = 0, do nothing
  56980. if (cubeMapSize < 1) {
  56981. return;
  56982. }
  56983. //special case 1x1 cubemap, average face colors
  56984. if (cubeMapSize == 1) {
  56985. //iterate over channels
  56986. for (k = 0; k < this.numChannels; k++) {
  56987. var accum = 0.0;
  56988. //iterate over faces to accumulate face colors
  56989. for (iFace = 0; iFace < 6; iFace++) {
  56990. accum += cubeMap[iFace][k];
  56991. }
  56992. //compute average over 6 face colors
  56993. accum /= 6.0;
  56994. //iterate over faces to distribute face colors
  56995. for (iFace = 0; iFace < 6; iFace++) {
  56996. cubeMap[iFace][k] = accum;
  56997. }
  56998. }
  56999. return;
  57000. }
  57001. //iterate over faces to collect list of corner texel pointers
  57002. for (iFace = 0; iFace < 6; iFace++) {
  57003. //the 4 corner pointers for this face
  57004. faceCornerStartIndicies[0] = [iFace, 0];
  57005. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57006. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57007. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57008. //iterate over face corners to collect cube corner pointers
  57009. for (iCorner = 0; iCorner < 4; iCorner++) {
  57010. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57011. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57012. cornerNumPtrs[corner]++;
  57013. }
  57014. }
  57015. //iterate over corners to average across corner tap values
  57016. for (iCorner = 0; iCorner < 8; iCorner++) {
  57017. for (k = 0; k < this.numChannels; k++) {
  57018. var cornerTapAccum = 0.0;
  57019. //iterate over corner texels and average results
  57020. for (i = 0; i < 3; i++) {
  57021. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57022. }
  57023. //divide by 3 to compute average of corner tap values
  57024. cornerTapAccum *= (1.0 / 3.0);
  57025. //iterate over corner texels and average results
  57026. for (i = 0; i < 3; i++) {
  57027. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57028. }
  57029. }
  57030. }
  57031. //iterate over the twelve edges of the cube to average across edges
  57032. for (i = 0; i < 12; i++) {
  57033. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57034. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57035. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57036. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57037. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57038. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57039. var edgeWalk = 0;
  57040. var neighborEdgeWalk = 0;
  57041. //Determine walking pointers based on edge type
  57042. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57043. switch (edge) {
  57044. case PMREMGenerator.CP_EDGE_LEFT:
  57045. // no change to faceEdgeStartPtr
  57046. edgeWalk = this.numChannels * cubeMapSize;
  57047. break;
  57048. case PMREMGenerator.CP_EDGE_RIGHT:
  57049. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57050. edgeWalk = this.numChannels * cubeMapSize;
  57051. break;
  57052. case PMREMGenerator.CP_EDGE_TOP:
  57053. // no change to faceEdgeStartPtr
  57054. edgeWalk = this.numChannels;
  57055. break;
  57056. case PMREMGenerator.CP_EDGE_BOTTOM:
  57057. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57058. edgeWalk = this.numChannels;
  57059. break;
  57060. }
  57061. //For certain types of edge abutments, the neighbor edge walk needs to
  57062. // be flipped: the cases are
  57063. // if a left edge mates with a left or bottom edge on the neighbor
  57064. // if a top edge mates with a top or right edge on the neighbor
  57065. // if a right edge mates with a right or top edge on the neighbor
  57066. // if a bottom edge mates with a bottom or left edge on the neighbor
  57067. //Seeing as the edges are enumerated as follows
  57068. // left =0
  57069. // right =1
  57070. // top =2
  57071. // bottom =3
  57072. //
  57073. //If the edge enums are the same, or the sum of the enums == 3,
  57074. // the neighbor edge walk needs to be flipped
  57075. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57076. switch (neighborEdge) {
  57077. case PMREMGenerator.CP_EDGE_LEFT:
  57078. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57079. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57080. break;
  57081. case PMREMGenerator.CP_EDGE_RIGHT:
  57082. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57083. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57084. break;
  57085. case PMREMGenerator.CP_EDGE_TOP:
  57086. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57087. neighborEdgeWalk = -this.numChannels;
  57088. break;
  57089. case PMREMGenerator.CP_EDGE_BOTTOM:
  57090. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57091. neighborEdgeWalk = -this.numChannels;
  57092. break;
  57093. }
  57094. }
  57095. else {
  57096. //swapped direction neighbor edge walk
  57097. switch (neighborEdge) {
  57098. case PMREMGenerator.CP_EDGE_LEFT:
  57099. //no change to neighborEdgeStartPtr for this case since it points
  57100. // to the upper left corner already
  57101. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57102. break;
  57103. case PMREMGenerator.CP_EDGE_RIGHT:
  57104. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57105. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57106. break;
  57107. case PMREMGenerator.CP_EDGE_TOP:
  57108. //no change to neighborEdgeStartPtr for this case since it points
  57109. // to the upper left corner already
  57110. neighborEdgeWalk = this.numChannels;
  57111. break;
  57112. case PMREMGenerator.CP_EDGE_BOTTOM:
  57113. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57114. neighborEdgeWalk = this.numChannels;
  57115. break;
  57116. }
  57117. }
  57118. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57119. //nearby neighborhood
  57120. //step ahead one texel on edge
  57121. edgeStartIndex += edgeWalk;
  57122. neighborEdgeStartIndex += neighborEdgeWalk;
  57123. // note that this loop does not process the corner texels, since they have already been
  57124. // averaged across faces across earlier
  57125. for (j = 1; j < (cubeMapSize - 1); j++) {
  57126. //for each set of taps along edge, average them
  57127. // and rewrite the results into the edges
  57128. for (k = 0; k < this.numChannels; k++) {
  57129. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57130. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57131. //compute average of tap intensity values
  57132. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57133. //propagate average of taps to edge taps
  57134. cubeMap[face][edgeStartIndex + k] = avgTap;
  57135. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57136. }
  57137. edgeStartIndex += edgeWalk;
  57138. neighborEdgeStartIndex += neighborEdgeWalk;
  57139. }
  57140. }
  57141. };
  57142. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57143. PMREMGenerator.CP_UDIR = 0;
  57144. PMREMGenerator.CP_VDIR = 1;
  57145. PMREMGenerator.CP_FACEAXIS = 2;
  57146. //used to index cube faces
  57147. PMREMGenerator.CP_FACE_X_POS = 0;
  57148. PMREMGenerator.CP_FACE_X_NEG = 1;
  57149. PMREMGenerator.CP_FACE_Y_POS = 2;
  57150. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57151. PMREMGenerator.CP_FACE_Z_POS = 4;
  57152. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57153. //used to index image edges
  57154. // NOTE.. the actual number corresponding to the edge is important
  57155. // do not change these, or the code will break
  57156. //
  57157. // CP_EDGE_LEFT is u = 0
  57158. // CP_EDGE_RIGHT is u = width-1
  57159. // CP_EDGE_TOP is v = 0
  57160. // CP_EDGE_BOTTOM is v = height-1
  57161. PMREMGenerator.CP_EDGE_LEFT = 0;
  57162. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57163. PMREMGenerator.CP_EDGE_TOP = 2;
  57164. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57165. //corners of CUBE map (P or N specifys if it corresponds to the
  57166. // positive or negative direction each of X, Y, and Z
  57167. PMREMGenerator.CP_CORNER_NNN = 0;
  57168. PMREMGenerator.CP_CORNER_NNP = 1;
  57169. PMREMGenerator.CP_CORNER_NPN = 2;
  57170. PMREMGenerator.CP_CORNER_NPP = 3;
  57171. PMREMGenerator.CP_CORNER_PNN = 4;
  57172. PMREMGenerator.CP_CORNER_PNP = 5;
  57173. PMREMGenerator.CP_CORNER_PPN = 6;
  57174. PMREMGenerator.CP_CORNER_PPP = 7;
  57175. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57176. //3x2 matrices that map cube map indexing vectors in 3d
  57177. // (after face selection and divide through by the
  57178. // _ABSOLUTE VALUE_ of the max coord)
  57179. // into NVC space
  57180. //Note this currently assumes the D3D cube face ordering and orientation
  57181. PMREMGenerator._sgFace2DMapping = [
  57182. //XPOS face
  57183. [[0, 0, -1],
  57184. [0, -1, 0],
  57185. [1, 0, 0]],
  57186. //XNEG face
  57187. [[0, 0, 1],
  57188. [0, -1, 0],
  57189. [-1, 0, 0]],
  57190. //YPOS face
  57191. [[1, 0, 0],
  57192. [0, 0, 1],
  57193. [0, 1, 0]],
  57194. //YNEG face
  57195. [[1, 0, 0],
  57196. [0, 0, -1],
  57197. [0, -1, 0]],
  57198. //ZPOS face
  57199. [[1, 0, 0],
  57200. [0, -1, 0],
  57201. [0, 0, 1]],
  57202. //ZNEG face
  57203. [[-1, 0, 0],
  57204. [0, -1, 0],
  57205. [0, 0, -1]],
  57206. ];
  57207. //------------------------------------------------------------------------------
  57208. // D3D cube map face specification
  57209. // mapping from 3D x,y,z cube map lookup coordinates
  57210. // to 2D within face u,v coordinates
  57211. //
  57212. // --------------------> U direction
  57213. // | (within-face texture space)
  57214. // | _____
  57215. // | | |
  57216. // | | +Y |
  57217. // | _____|_____|_____ _____
  57218. // | | | | | |
  57219. // | | -X | +Z | +X | -Z |
  57220. // | |_____|_____|_____|_____|
  57221. // | | |
  57222. // | | -Y |
  57223. // | |_____|
  57224. // |
  57225. // v V direction
  57226. // (within-face texture space)
  57227. //------------------------------------------------------------------------------
  57228. //Information about neighbors and how texture coorrdinates change across faces
  57229. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57230. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57231. //Note this currently assumes the D3D cube face ordering and orientation
  57232. PMREMGenerator._sgCubeNgh = [
  57233. //XPOS face
  57234. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57235. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57236. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57237. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57238. //XNEG face
  57239. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57240. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57241. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57242. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57243. //YPOS face
  57244. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57245. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57246. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57247. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57248. //YNEG face
  57249. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57250. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57251. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57252. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57253. //ZPOS face
  57254. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57255. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57256. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57257. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57258. //ZNEG face
  57259. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57260. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57261. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57262. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57263. ];
  57264. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57265. // this table is used to average over the edges.
  57266. PMREMGenerator._sgCubeEdgeList = [
  57267. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57268. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57269. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57270. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57271. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57272. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57273. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57274. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57275. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57276. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57277. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57278. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57279. ];
  57280. //Information about which of the 8 cube corners are correspond to the
  57281. // the 4 corners in each cube face
  57282. // the order is upper left, upper right, lower left, lower right
  57283. PMREMGenerator._sgCubeCornerList = [
  57284. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57285. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57286. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57287. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57288. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57289. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57290. ];
  57291. return PMREMGenerator;
  57292. })();
  57293. Internals.PMREMGenerator = PMREMGenerator;
  57294. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57295. })(BABYLON || (BABYLON = {}));
  57296. var BABYLON;
  57297. (function (BABYLON) {
  57298. /**
  57299. * This represents a texture coming from an HDR input.
  57300. *
  57301. * The only supported format is currently panorama picture stored in RGBE format.
  57302. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57303. */
  57304. var HDRCubeTexture = (function (_super) {
  57305. __extends(HDRCubeTexture, _super);
  57306. /**
  57307. * Instantiates an HDRTexture from the following parameters.
  57308. *
  57309. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57310. * @param scene The scene the texture will be used in
  57311. * @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.
  57312. * @param noMipmap Forces to not generate the mipmap if true
  57313. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57314. * @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)
  57315. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57316. */
  57317. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  57318. if (noMipmap === void 0) { noMipmap = false; }
  57319. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57320. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57321. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57322. _super.call(this, scene);
  57323. this._useInGammaSpace = false;
  57324. this._generateHarmonics = true;
  57325. this._isBABYLONPreprocessed = false;
  57326. /**
  57327. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57328. */
  57329. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57330. /**
  57331. * The spherical polynomial data extracted from the texture.
  57332. */
  57333. this.sphericalPolynomial = null;
  57334. /**
  57335. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57336. * This is usefull at run time to apply the good shader.
  57337. */
  57338. this.isPMREM = false;
  57339. if (!url) {
  57340. return;
  57341. }
  57342. this.name = url;
  57343. this.url = url;
  57344. this.hasAlpha = false;
  57345. this.isCube = true;
  57346. this._textureMatrix = BABYLON.Matrix.Identity();
  57347. if (size) {
  57348. this._isBABYLONPreprocessed = false;
  57349. this._noMipmap = noMipmap;
  57350. this._size = size;
  57351. this._useInGammaSpace = useInGammaSpace;
  57352. this._usePMREMGenerator = usePMREMGenerator &&
  57353. scene.getEngine().getCaps().textureLOD &&
  57354. this.getScene().getEngine().getCaps().textureFloat &&
  57355. !this._useInGammaSpace;
  57356. }
  57357. else {
  57358. this._isBABYLONPreprocessed = true;
  57359. this._noMipmap = false;
  57360. this._useInGammaSpace = false;
  57361. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57362. this.getScene().getEngine().getCaps().textureFloat &&
  57363. !this._useInGammaSpace;
  57364. }
  57365. this.isPMREM = this._usePMREMGenerator;
  57366. this._texture = this._getFromCache(url, this._noMipmap);
  57367. if (!this._texture) {
  57368. if (!scene.useDelayedTextureLoading) {
  57369. this.loadTexture();
  57370. }
  57371. else {
  57372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57373. }
  57374. }
  57375. }
  57376. /**
  57377. * Occurs when the file is a preprocessed .babylon.hdr file.
  57378. */
  57379. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57380. var _this = this;
  57381. var mipLevels = 0;
  57382. var floatArrayView = null;
  57383. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57384. var mips = [];
  57385. var startIndex = 30;
  57386. for (var level = 0; level < mipLevels; level++) {
  57387. mips.push([]);
  57388. // Fill each pixel of the mip level.
  57389. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57390. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57391. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57392. mips[level].push(faceData);
  57393. startIndex += faceSize;
  57394. }
  57395. }
  57396. return mips;
  57397. } : null;
  57398. var callback = function (buffer) {
  57399. // Create Native Array Views
  57400. var intArrayView = new Int32Array(buffer);
  57401. floatArrayView = new Float32Array(buffer);
  57402. // Fill header.
  57403. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57404. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57405. // Update Texture Information.
  57406. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57407. // Fill polynomial information.
  57408. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57409. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57410. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57411. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57412. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57413. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57414. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57415. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57416. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57417. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57418. // Fill pixel data.
  57419. mipLevels = intArrayView[29]; // Number of mip levels.
  57420. var startIndex = 30;
  57421. var data = [];
  57422. var faceSize = Math.pow(_this._size, 2) * 3;
  57423. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57424. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57425. startIndex += faceSize;
  57426. }
  57427. var results = [];
  57428. var byteArray = null;
  57429. // Push each faces.
  57430. for (var k = 0; k < 6; k++) {
  57431. var dataFace = null;
  57432. // If special cases.
  57433. if (!mipmapGenerator) {
  57434. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57435. dataFace = data[j];
  57436. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57437. // 3 channels of 1 bytes per pixel in bytes.
  57438. var byteBuffer = new ArrayBuffer(faceSize);
  57439. byteArray = new Uint8Array(byteBuffer);
  57440. }
  57441. for (var i = 0; i < _this._size * _this._size; i++) {
  57442. // Put in gamma space if requested.
  57443. if (_this._useInGammaSpace) {
  57444. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57445. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57446. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57447. }
  57448. // Convert to int texture for fallback.
  57449. if (byteArray) {
  57450. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57451. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57452. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57453. // May use luminance instead if the result is not accurate.
  57454. var max = Math.max(Math.max(r, g), b);
  57455. if (max > 255) {
  57456. var scale = 255 / max;
  57457. r *= scale;
  57458. g *= scale;
  57459. b *= scale;
  57460. }
  57461. byteArray[(i * 3) + 0] = r;
  57462. byteArray[(i * 3) + 1] = g;
  57463. byteArray[(i * 3) + 2] = b;
  57464. }
  57465. }
  57466. }
  57467. else {
  57468. dataFace = data[k];
  57469. }
  57470. // Fill the array accordingly.
  57471. if (byteArray) {
  57472. results.push(byteArray);
  57473. }
  57474. else {
  57475. results.push(dataFace);
  57476. }
  57477. }
  57478. return results;
  57479. };
  57480. 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);
  57481. };
  57482. /**
  57483. * Occurs when the file is raw .hdr file.
  57484. */
  57485. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57486. var _this = this;
  57487. var callback = function (buffer) {
  57488. // Extract the raw linear data.
  57489. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57490. // Generate harmonics if needed.
  57491. if (_this._generateHarmonics) {
  57492. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57493. }
  57494. var results = [];
  57495. var byteArray = null;
  57496. // Push each faces.
  57497. for (var j = 0; j < 6; j++) {
  57498. // Create uintarray fallback.
  57499. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57500. // 3 channels of 1 bytes per pixel in bytes.
  57501. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57502. byteArray = new Uint8Array(byteBuffer);
  57503. }
  57504. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57505. // If special cases.
  57506. if (_this._useInGammaSpace || byteArray) {
  57507. for (var i = 0; i < _this._size * _this._size; i++) {
  57508. // Put in gamma space if requested.
  57509. if (_this._useInGammaSpace) {
  57510. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57511. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57512. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57513. }
  57514. // Convert to int texture for fallback.
  57515. if (byteArray) {
  57516. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57517. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57518. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57519. // May use luminance instead if the result is not accurate.
  57520. var max = Math.max(Math.max(r, g), b);
  57521. if (max > 255) {
  57522. var scale = 255 / max;
  57523. r *= scale;
  57524. g *= scale;
  57525. b *= scale;
  57526. }
  57527. byteArray[(i * 3) + 0] = r;
  57528. byteArray[(i * 3) + 1] = g;
  57529. byteArray[(i * 3) + 2] = b;
  57530. }
  57531. }
  57532. }
  57533. if (byteArray) {
  57534. results.push(byteArray);
  57535. }
  57536. else {
  57537. results.push(dataFace);
  57538. }
  57539. }
  57540. return results;
  57541. };
  57542. var mipmapGenerator = null;
  57543. if (!this._noMipmap &&
  57544. this._usePMREMGenerator) {
  57545. mipmapGenerator = function (data) {
  57546. // Custom setup of the generator matching with the PBR shader values.
  57547. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  57548. return generator.filterCubeMap();
  57549. };
  57550. }
  57551. 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);
  57552. };
  57553. /**
  57554. * Starts the loading process of the texture.
  57555. */
  57556. HDRCubeTexture.prototype.loadTexture = function () {
  57557. if (this._isBABYLONPreprocessed) {
  57558. this.loadBabylonTexture();
  57559. }
  57560. else {
  57561. this.loadHDRTexture();
  57562. }
  57563. };
  57564. HDRCubeTexture.prototype.clone = function () {
  57565. var size = this._isBABYLONPreprocessed ? null : this._size;
  57566. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57567. // Base texture
  57568. newTexture.level = this.level;
  57569. newTexture.wrapU = this.wrapU;
  57570. newTexture.wrapV = this.wrapV;
  57571. newTexture.coordinatesIndex = this.coordinatesIndex;
  57572. newTexture.coordinatesMode = this.coordinatesMode;
  57573. return newTexture;
  57574. };
  57575. // Methods
  57576. HDRCubeTexture.prototype.delayLoad = function () {
  57577. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57578. return;
  57579. }
  57580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57581. this._texture = this._getFromCache(this.url, this._noMipmap);
  57582. if (!this._texture) {
  57583. this.loadTexture();
  57584. }
  57585. };
  57586. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57587. return this._textureMatrix;
  57588. };
  57589. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57590. var texture = null;
  57591. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57592. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57593. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  57594. texture.name = parsedTexture.name;
  57595. texture.hasAlpha = parsedTexture.hasAlpha;
  57596. texture.level = parsedTexture.level;
  57597. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57598. }
  57599. return texture;
  57600. };
  57601. HDRCubeTexture.prototype.serialize = function () {
  57602. if (!this.name) {
  57603. return null;
  57604. }
  57605. var serializationObject = {};
  57606. serializationObject.name = this.name;
  57607. serializationObject.hasAlpha = this.hasAlpha;
  57608. serializationObject.isCube = true;
  57609. serializationObject.level = this.level;
  57610. serializationObject.size = this._size;
  57611. serializationObject.coordinatesMode = this.coordinatesMode;
  57612. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57613. serializationObject.generateHarmonics = this._generateHarmonics;
  57614. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57615. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57616. return serializationObject;
  57617. };
  57618. /**
  57619. * Saves as a file the data contained in the texture in a binary format.
  57620. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57621. * as the spherical used in the lighting.
  57622. * @param url The HDR file url.
  57623. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57624. * @param onError Method called if any error happens during download.
  57625. * @return The packed binary data.
  57626. */
  57627. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57628. if (onError === void 0) { onError = null; }
  57629. var callback = function (buffer) {
  57630. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57631. // Returns a URL you can use as a href.
  57632. var objUrl = window.URL.createObjectURL(data);
  57633. // Simulates a link to it and click to dowload.
  57634. var a = document.createElement("a");
  57635. document.body.appendChild(a);
  57636. a.style.display = "none";
  57637. a.href = objUrl;
  57638. a.download = "envmap.babylon.hdr";
  57639. a.click();
  57640. };
  57641. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57642. };
  57643. /**
  57644. * Serializes the data contained in the texture in a binary format.
  57645. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57646. * as the spherical used in the lighting.
  57647. * @param url The HDR file url.
  57648. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57649. * @param onError Method called if any error happens during download.
  57650. * @return The packed binary data.
  57651. */
  57652. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57653. if (onError === void 0) { onError = null; }
  57654. // Needs the url tho create the texture.
  57655. if (!url) {
  57656. return null;
  57657. }
  57658. // Check Power of two size.
  57659. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57660. return null;
  57661. }
  57662. var getDataCallback = function (dataBuffer) {
  57663. // Extract the raw linear data.
  57664. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  57665. // Generate harmonics if needed.
  57666. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  57667. // Generate seamless faces
  57668. var mipGeneratorArray = [];
  57669. // Data are known to be in +X +Y +Z -X -Y -Z
  57670. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  57671. mipGeneratorArray.push(cubeData.right); // +X
  57672. mipGeneratorArray.push(cubeData.left); // -X
  57673. mipGeneratorArray.push(cubeData.up); // +Y
  57674. mipGeneratorArray.push(cubeData.down); // -Y
  57675. mipGeneratorArray.push(cubeData.front); // +Z
  57676. mipGeneratorArray.push(cubeData.back); // -Z
  57677. // Custom setup of the generator matching with the PBR shader values.
  57678. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  57679. var mippedData = generator.filterCubeMap();
  57680. // Compute required byte length.
  57681. var byteLength = 1 * 4; // Raw Data Version int32.
  57682. byteLength += 4; // CubeMap max mip face size int32.
  57683. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  57684. // Add data size.
  57685. byteLength += 4; // Number of mip levels int32.
  57686. for (var level = 0; level < mippedData.length; level++) {
  57687. var mipSize = size >> level;
  57688. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  57689. }
  57690. // Prepare binary structure.
  57691. var buffer = new ArrayBuffer(byteLength);
  57692. var intArrayView = new Int32Array(buffer);
  57693. var floatArrayView = new Float32Array(buffer);
  57694. // Fill header.
  57695. intArrayView[0] = 1; // Version 1.
  57696. intArrayView[1] = size; // CubeMap max mip face size.
  57697. // Fill polynomial information.
  57698. sphericalPolynomial.x.toArray(floatArrayView, 2);
  57699. sphericalPolynomial.y.toArray(floatArrayView, 5);
  57700. sphericalPolynomial.z.toArray(floatArrayView, 8);
  57701. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  57702. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  57703. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  57704. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  57705. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  57706. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  57707. // Fill pixel data.
  57708. intArrayView[29] = mippedData.length; // Number of mip levels.
  57709. var startIndex = 30;
  57710. for (var level = 0; level < mippedData.length; level++) {
  57711. // Fill each pixel of the mip level.
  57712. var faceSize = Math.pow(size >> level, 2) * 3;
  57713. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57714. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  57715. startIndex += faceSize;
  57716. }
  57717. }
  57718. // Callback.
  57719. callback(buffer);
  57720. };
  57721. // Download and process.
  57722. BABYLON.Tools.LoadFile(url, function (data) {
  57723. getDataCallback(data);
  57724. }, null, null, true, onError);
  57725. };
  57726. HDRCubeTexture._facesMapping = [
  57727. "right",
  57728. "up",
  57729. "front",
  57730. "left",
  57731. "down",
  57732. "back"
  57733. ];
  57734. return HDRCubeTexture;
  57735. })(BABYLON.BaseTexture);
  57736. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57737. })(BABYLON || (BABYLON = {}));
  57738. var BABYLON;
  57739. (function (BABYLON) {
  57740. var Debug;
  57741. (function (Debug) {
  57742. /**
  57743. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  57744. */
  57745. var SkeletonViewer = (function () {
  57746. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  57747. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  57748. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  57749. this.skeleton = skeleton;
  57750. this.mesh = mesh;
  57751. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  57752. this.renderingGroupId = renderingGroupId;
  57753. this.color = BABYLON.Color3.White();
  57754. this._debugLines = [];
  57755. this._isEnabled = false;
  57756. this._scene = scene;
  57757. this.update();
  57758. this._renderFunction = this.update.bind(this);
  57759. }
  57760. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  57761. get: function () {
  57762. return this._isEnabled;
  57763. },
  57764. set: function (value) {
  57765. if (this._isEnabled === value) {
  57766. return;
  57767. }
  57768. this._isEnabled = value;
  57769. if (value) {
  57770. this._scene.registerBeforeRender(this._renderFunction);
  57771. }
  57772. else {
  57773. this._scene.unregisterBeforeRender(this._renderFunction);
  57774. }
  57775. },
  57776. enumerable: true,
  57777. configurable: true
  57778. });
  57779. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  57780. if (x === void 0) { x = 0; }
  57781. if (y === void 0) { y = 0; }
  57782. if (z === void 0) { z = 0; }
  57783. var tmat = BABYLON.Tmp.Matrix[0];
  57784. var parentBone = bone.getParent();
  57785. tmat.copyFrom(bone.getLocalMatrix());
  57786. if (x !== 0 || y !== 0 || z !== 0) {
  57787. var tmat2 = BABYLON.Tmp.Matrix[1];
  57788. BABYLON.Matrix.IdentityToRef(tmat2);
  57789. tmat2.m[12] = x;
  57790. tmat2.m[13] = y;
  57791. tmat2.m[14] = z;
  57792. tmat2.multiplyToRef(tmat, tmat);
  57793. }
  57794. if (parentBone) {
  57795. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  57796. }
  57797. tmat.multiplyToRef(meshMat, tmat);
  57798. position.x = tmat.m[12];
  57799. position.y = tmat.m[13];
  57800. position.z = tmat.m[14];
  57801. };
  57802. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  57803. var len = bones.length;
  57804. for (var i = 0; i < len; i++) {
  57805. var bone = bones[i];
  57806. var points = this._debugLines[i];
  57807. if (!points) {
  57808. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57809. this._debugLines[i] = points;
  57810. }
  57811. this._getBonePosition(points[0], bone, meshMat);
  57812. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  57813. }
  57814. };
  57815. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  57816. var len = bones.length;
  57817. var boneNum = 0;
  57818. for (var i = len - 1; i >= 0; i--) {
  57819. var childBone = bones[i];
  57820. var parentBone = childBone.getParent();
  57821. if (!parentBone) {
  57822. continue;
  57823. }
  57824. var points = this._debugLines[boneNum];
  57825. if (!points) {
  57826. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57827. this._debugLines[boneNum] = points;
  57828. }
  57829. this._getBonePosition(points[0], childBone, meshMat);
  57830. this._getBonePosition(points[1], parentBone, meshMat);
  57831. boneNum++;
  57832. }
  57833. };
  57834. SkeletonViewer.prototype.update = function () {
  57835. if (this.autoUpdateBonesMatrices) {
  57836. this._updateBoneMatrix(this.skeleton.bones[0]);
  57837. }
  57838. if (this.skeleton.bones[0].length === undefined) {
  57839. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57840. }
  57841. else {
  57842. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57843. }
  57844. if (!this._debugMesh) {
  57845. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  57846. this._debugMesh.renderingGroupId = this.renderingGroupId;
  57847. }
  57848. else {
  57849. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  57850. }
  57851. this._debugMesh.color = this.color;
  57852. };
  57853. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  57854. if (bone.getParent()) {
  57855. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  57856. }
  57857. var children = bone.children;
  57858. var len = children.length;
  57859. for (var i = 0; i < len; i++) {
  57860. this._updateBoneMatrix(children[i]);
  57861. }
  57862. };
  57863. SkeletonViewer.prototype.dispose = function () {
  57864. if (this._debugMesh) {
  57865. this.isEnabled = false;
  57866. this._debugMesh.dispose();
  57867. this._debugMesh = null;
  57868. }
  57869. };
  57870. return SkeletonViewer;
  57871. })();
  57872. Debug.SkeletonViewer = SkeletonViewer;
  57873. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57874. })(BABYLON || (BABYLON = {}));
  57875. var BABYLON;
  57876. (function (BABYLON) {
  57877. /**
  57878. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57879. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57880. * 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;
  57881. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57882. */
  57883. var ColorCurves = (function () {
  57884. function ColorCurves() {
  57885. this._dirty = true;
  57886. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57887. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57888. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57889. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57890. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57891. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57892. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57893. this._globalHue = 30;
  57894. this._globalDensity = 0;
  57895. this._globalSaturation = 0;
  57896. this._globalExposure = 0;
  57897. this._highlightsHue = 30;
  57898. this._highlightsDensity = 0;
  57899. this._highlightsSaturation = 0;
  57900. this._highlightsExposure = 0;
  57901. this._midtonesHue = 30;
  57902. this._midtonesDensity = 0;
  57903. this._midtonesSaturation = 0;
  57904. this._midtonesExposure = 0;
  57905. this._shadowsHue = 30;
  57906. this._shadowsDensity = 0;
  57907. this._shadowsSaturation = 0;
  57908. this._shadowsExposure = 0;
  57909. }
  57910. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57911. /**
  57912. * Gets the global Hue value.
  57913. * 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).
  57914. */
  57915. get: function () {
  57916. return this._globalHue;
  57917. },
  57918. /**
  57919. * Sets the global Hue value.
  57920. * 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).
  57921. */
  57922. set: function (value) {
  57923. this._globalHue = value;
  57924. this._dirty = true;
  57925. },
  57926. enumerable: true,
  57927. configurable: true
  57928. });
  57929. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57930. /**
  57931. * Gets the global Density value.
  57932. * 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.
  57933. * Values less than zero provide a filter of opposite hue.
  57934. */
  57935. get: function () {
  57936. return this._globalDensity;
  57937. },
  57938. /**
  57939. * Sets the global Density value.
  57940. * 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.
  57941. * Values less than zero provide a filter of opposite hue.
  57942. */
  57943. set: function (value) {
  57944. this._globalDensity = value;
  57945. this._dirty = true;
  57946. },
  57947. enumerable: true,
  57948. configurable: true
  57949. });
  57950. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57951. /**
  57952. * Gets the global Saturation value.
  57953. * 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.
  57954. */
  57955. get: function () {
  57956. return this._globalSaturation;
  57957. },
  57958. /**
  57959. * Sets the global Saturation value.
  57960. * 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.
  57961. */
  57962. set: function (value) {
  57963. this._globalSaturation = value;
  57964. this._dirty = true;
  57965. },
  57966. enumerable: true,
  57967. configurable: true
  57968. });
  57969. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57970. /**
  57971. * Gets the highlights Hue value.
  57972. * 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).
  57973. */
  57974. get: function () {
  57975. return this._highlightsHue;
  57976. },
  57977. /**
  57978. * Sets the highlights Hue value.
  57979. * 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).
  57980. */
  57981. set: function (value) {
  57982. this._highlightsHue = value;
  57983. this._dirty = true;
  57984. },
  57985. enumerable: true,
  57986. configurable: true
  57987. });
  57988. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57989. /**
  57990. * Gets the highlights Density value.
  57991. * 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.
  57992. * Values less than zero provide a filter of opposite hue.
  57993. */
  57994. get: function () {
  57995. return this._highlightsDensity;
  57996. },
  57997. /**
  57998. * Sets the highlights Density value.
  57999. * 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.
  58000. * Values less than zero provide a filter of opposite hue.
  58001. */
  58002. set: function (value) {
  58003. this._highlightsDensity = value;
  58004. this._dirty = true;
  58005. },
  58006. enumerable: true,
  58007. configurable: true
  58008. });
  58009. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58010. /**
  58011. * Gets the highlights Saturation value.
  58012. * 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.
  58013. */
  58014. get: function () {
  58015. return this._highlightsSaturation;
  58016. },
  58017. /**
  58018. * Sets the highlights Saturation value.
  58019. * 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.
  58020. */
  58021. set: function (value) {
  58022. this._highlightsSaturation = value;
  58023. this._dirty = true;
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58029. /**
  58030. * Gets the highlights Exposure value.
  58031. * 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.
  58032. */
  58033. get: function () {
  58034. return this._highlightsExposure;
  58035. },
  58036. /**
  58037. * Sets the highlights Exposure value.
  58038. * 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.
  58039. */
  58040. set: function (value) {
  58041. this._highlightsExposure = value;
  58042. this._dirty = true;
  58043. },
  58044. enumerable: true,
  58045. configurable: true
  58046. });
  58047. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58048. /**
  58049. * Gets the midtones Hue value.
  58050. * 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).
  58051. */
  58052. get: function () {
  58053. return this._midtonesHue;
  58054. },
  58055. /**
  58056. * Sets the midtones Hue value.
  58057. * 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).
  58058. */
  58059. set: function (value) {
  58060. this._midtonesHue = value;
  58061. this._dirty = true;
  58062. },
  58063. enumerable: true,
  58064. configurable: true
  58065. });
  58066. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58067. /**
  58068. * Gets the midtones Density value.
  58069. * 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.
  58070. * Values less than zero provide a filter of opposite hue.
  58071. */
  58072. get: function () {
  58073. return this._midtonesDensity;
  58074. },
  58075. /**
  58076. * Sets the midtones Density value.
  58077. * 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.
  58078. * Values less than zero provide a filter of opposite hue.
  58079. */
  58080. set: function (value) {
  58081. this._midtonesDensity = value;
  58082. this._dirty = true;
  58083. },
  58084. enumerable: true,
  58085. configurable: true
  58086. });
  58087. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58088. /**
  58089. * Gets the midtones Saturation value.
  58090. * 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.
  58091. */
  58092. get: function () {
  58093. return this._midtonesSaturation;
  58094. },
  58095. /**
  58096. * Sets the midtones Saturation value.
  58097. * 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.
  58098. */
  58099. set: function (value) {
  58100. this._midtonesSaturation = value;
  58101. this._dirty = true;
  58102. },
  58103. enumerable: true,
  58104. configurable: true
  58105. });
  58106. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58107. /**
  58108. * Gets the midtones Exposure value.
  58109. * 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.
  58110. */
  58111. get: function () {
  58112. return this._midtonesExposure;
  58113. },
  58114. /**
  58115. * Sets the midtones Exposure value.
  58116. * 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.
  58117. */
  58118. set: function (value) {
  58119. this._midtonesExposure = value;
  58120. this._dirty = true;
  58121. },
  58122. enumerable: true,
  58123. configurable: true
  58124. });
  58125. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58126. /**
  58127. * Gets the shadows Hue value.
  58128. * 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).
  58129. */
  58130. get: function () {
  58131. return this._shadowsHue;
  58132. },
  58133. /**
  58134. * Sets the shadows Hue value.
  58135. * 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).
  58136. */
  58137. set: function (value) {
  58138. this._shadowsHue = value;
  58139. this._dirty = true;
  58140. },
  58141. enumerable: true,
  58142. configurable: true
  58143. });
  58144. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58145. /**
  58146. * Gets the shadows Density value.
  58147. * 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.
  58148. * Values less than zero provide a filter of opposite hue.
  58149. */
  58150. get: function () {
  58151. return this._shadowsDensity;
  58152. },
  58153. /**
  58154. * Sets the shadows Density value.
  58155. * 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.
  58156. * Values less than zero provide a filter of opposite hue.
  58157. */
  58158. set: function (value) {
  58159. this._shadowsDensity = value;
  58160. this._dirty = true;
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58166. /**
  58167. * Gets the shadows Saturation value.
  58168. * 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.
  58169. */
  58170. get: function () {
  58171. return this._shadowsSaturation;
  58172. },
  58173. /**
  58174. * Sets the shadows Saturation value.
  58175. * 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.
  58176. */
  58177. set: function (value) {
  58178. this._shadowsSaturation = value;
  58179. this._dirty = true;
  58180. },
  58181. enumerable: true,
  58182. configurable: true
  58183. });
  58184. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58185. /**
  58186. * Gets the shadows Exposure value.
  58187. * 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.
  58188. */
  58189. get: function () {
  58190. return this._shadowsExposure;
  58191. },
  58192. /**
  58193. * Sets the shadows Exposure value.
  58194. * 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.
  58195. */
  58196. set: function (value) {
  58197. this._shadowsExposure = value;
  58198. this._dirty = true;
  58199. },
  58200. enumerable: true,
  58201. configurable: true
  58202. });
  58203. /**
  58204. * Binds the color curves to the shader.
  58205. * @param colorCurves The color curve to bind
  58206. * @param effect The effect to bind to
  58207. */
  58208. ColorCurves.Bind = function (colorCurves, effect) {
  58209. if (colorCurves._dirty) {
  58210. colorCurves._dirty = false;
  58211. // Fill in global info.
  58212. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58213. // Compute highlights info.
  58214. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58215. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58216. // Compute midtones info.
  58217. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58218. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58219. // Compute shadows info.
  58220. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58221. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58222. // Compute deltas (neutral is midtones).
  58223. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58224. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58225. }
  58226. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58227. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58228. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58229. };
  58230. /**
  58231. * Prepare the list of uniforms associated with the ColorCurves effects.
  58232. * @param uniformsList The list of uniforms used in the effect
  58233. */
  58234. ColorCurves.PrepareUniforms = function (uniformsList) {
  58235. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58236. };
  58237. /**
  58238. * Returns color grading data based on a hue, density, saturation and exposure value.
  58239. * @param filterHue The hue of the color filter.
  58240. * @param filterDensity The density of the color filter.
  58241. * @param saturation The saturation.
  58242. * @param exposure The exposure.
  58243. * @param result The result data container.
  58244. */
  58245. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58246. if (hue == null) {
  58247. return;
  58248. }
  58249. hue = ColorCurves.clamp(hue, 0, 360);
  58250. density = ColorCurves.clamp(density, -100, 100);
  58251. saturation = ColorCurves.clamp(saturation, -100, 100);
  58252. exposure = ColorCurves.clamp(exposure, -100, 100);
  58253. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58254. // so that the maximum filter density is only 50% control. This provides fine control
  58255. // for small values and reasonable range.
  58256. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58257. density *= 0.5;
  58258. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58259. if (density < 0) {
  58260. density *= -1;
  58261. hue = (hue + 180) % 360;
  58262. }
  58263. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58264. result.scaleToRef(2, result);
  58265. result.a = 1 + 0.01 * saturation;
  58266. };
  58267. /**
  58268. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58269. * @param value The input slider value in range [-100,100].
  58270. * @returns Adjusted value.
  58271. */
  58272. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58273. value /= 100;
  58274. var x = Math.abs(value);
  58275. x = Math.pow(x, 2);
  58276. if (value < 0) {
  58277. x *= -1;
  58278. }
  58279. x *= 100;
  58280. return x;
  58281. };
  58282. /**
  58283. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58284. * @param hue The hue (H) input.
  58285. * @param saturation The saturation (S) input.
  58286. * @param brightness The brightness (B) input.
  58287. * @result An RGBA color represented as Vector4.
  58288. */
  58289. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58290. var h = ColorCurves.clamp(hue, 0, 360);
  58291. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58292. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58293. if (s === 0) {
  58294. result.r = v;
  58295. result.g = v;
  58296. result.b = v;
  58297. }
  58298. else {
  58299. // sector 0 to 5
  58300. h /= 60;
  58301. var i = Math.floor(h);
  58302. // fractional part of h
  58303. var f = h - i;
  58304. var p = v * (1 - s);
  58305. var q = v * (1 - s * f);
  58306. var t = v * (1 - s * (1 - f));
  58307. switch (i) {
  58308. case 0:
  58309. result.r = v;
  58310. result.g = t;
  58311. result.b = p;
  58312. break;
  58313. case 1:
  58314. result.r = q;
  58315. result.g = v;
  58316. result.b = p;
  58317. break;
  58318. case 2:
  58319. result.r = p;
  58320. result.g = v;
  58321. result.b = t;
  58322. break;
  58323. case 3:
  58324. result.r = p;
  58325. result.g = q;
  58326. result.b = v;
  58327. break;
  58328. case 4:
  58329. result.r = t;
  58330. result.g = p;
  58331. result.b = v;
  58332. break;
  58333. default:
  58334. result.r = v;
  58335. result.g = p;
  58336. result.b = q;
  58337. break;
  58338. }
  58339. }
  58340. result.a = 1;
  58341. };
  58342. /**
  58343. * Returns a value clamped between min and max
  58344. * @param value The value to clamp
  58345. * @param min The minimum of value
  58346. * @param max The maximum of value
  58347. * @returns The clamped value.
  58348. */
  58349. ColorCurves.clamp = function (value, min, max) {
  58350. return Math.min(Math.max(value, min), max);
  58351. };
  58352. /**
  58353. * Clones the current color curve instance.
  58354. * @return The cloned curves
  58355. */
  58356. ColorCurves.prototype.clone = function () {
  58357. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58358. };
  58359. /**
  58360. * Serializes the current color curve instance to a json representation.
  58361. * @return a JSON representation
  58362. */
  58363. ColorCurves.prototype.serialize = function () {
  58364. return BABYLON.SerializationHelper.Serialize(this);
  58365. };
  58366. /**
  58367. * Parses the color curve from a json representation.
  58368. * @param source the JSON source to parse
  58369. * @return The parsed curves
  58370. */
  58371. ColorCurves.Parse = function (source) {
  58372. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58373. };
  58374. __decorate([
  58375. BABYLON.serialize()
  58376. ], ColorCurves.prototype, "_globalHue", void 0);
  58377. __decorate([
  58378. BABYLON.serialize()
  58379. ], ColorCurves.prototype, "_globalDensity", void 0);
  58380. __decorate([
  58381. BABYLON.serialize()
  58382. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58383. __decorate([
  58384. BABYLON.serialize()
  58385. ], ColorCurves.prototype, "_globalExposure", void 0);
  58386. __decorate([
  58387. BABYLON.serialize()
  58388. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58389. __decorate([
  58390. BABYLON.serialize()
  58391. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58392. __decorate([
  58393. BABYLON.serialize()
  58394. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58395. __decorate([
  58396. BABYLON.serialize()
  58397. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58398. __decorate([
  58399. BABYLON.serialize()
  58400. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58401. __decorate([
  58402. BABYLON.serialize()
  58403. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58404. __decorate([
  58405. BABYLON.serialize()
  58406. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58407. __decorate([
  58408. BABYLON.serialize()
  58409. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58410. return ColorCurves;
  58411. })();
  58412. BABYLON.ColorCurves = ColorCurves;
  58413. })(BABYLON || (BABYLON = {}));
  58414. var BABYLON;
  58415. (function (BABYLON) {
  58416. /**
  58417. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58418. * It can help converting any input color in a desired output one. This can then be used to create effects
  58419. * from sepia, black and white to sixties or futuristic rendering...
  58420. *
  58421. * The only supported format is currently 3dl.
  58422. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58423. */
  58424. var ColorGradingTexture = (function (_super) {
  58425. __extends(ColorGradingTexture, _super);
  58426. /**
  58427. * Instantiates a ColorGradingTexture from the following parameters.
  58428. *
  58429. * @param url The location of the color gradind data (currently only supporting 3dl)
  58430. * @param scene The scene the texture will be used in
  58431. */
  58432. function ColorGradingTexture(url, scene) {
  58433. _super.call(this, scene);
  58434. if (!url) {
  58435. return;
  58436. }
  58437. this._textureMatrix = BABYLON.Matrix.Identity();
  58438. this.name = url;
  58439. this.url = url;
  58440. this.hasAlpha = false;
  58441. this.isCube = false;
  58442. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58443. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58444. this.anisotropicFilteringLevel = 1;
  58445. this._texture = this._getFromCache(url, true);
  58446. if (!this._texture) {
  58447. if (!scene.useDelayedTextureLoading) {
  58448. this.loadTexture();
  58449. }
  58450. else {
  58451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58452. }
  58453. }
  58454. }
  58455. /**
  58456. * Returns the texture matrix used in most of the material.
  58457. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58458. */
  58459. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58460. return this._textureMatrix;
  58461. };
  58462. /**
  58463. * Occurs when the file being loaded is a .3dl LUT file.
  58464. */
  58465. ColorGradingTexture.prototype.load3dlTexture = function () {
  58466. var _this = this;
  58467. var mipLevels = 0;
  58468. var floatArrayView = null;
  58469. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58470. this._texture = texture;
  58471. var callback = function (text) {
  58472. var data;
  58473. var tempData;
  58474. var line;
  58475. var lines = text.split('\n');
  58476. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58477. var maxColor = 0;
  58478. for (var i = 0; i < lines.length; i++) {
  58479. line = lines[i];
  58480. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58481. continue;
  58482. if (line.indexOf('#') === 0)
  58483. continue;
  58484. var words = line.split(" ");
  58485. if (size === 0) {
  58486. // Number of space + one
  58487. size = words.length;
  58488. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58489. tempData = new Float32Array(size * size * size * 4);
  58490. continue;
  58491. }
  58492. if (size != 0) {
  58493. var r = Math.max(parseInt(words[0]), 0);
  58494. var g = Math.max(parseInt(words[1]), 0);
  58495. var b = Math.max(parseInt(words[2]), 0);
  58496. maxColor = Math.max(r, maxColor);
  58497. maxColor = Math.max(g, maxColor);
  58498. maxColor = Math.max(b, maxColor);
  58499. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58500. tempData[pixelStorageIndex + 0] = r;
  58501. tempData[pixelStorageIndex + 1] = g;
  58502. tempData[pixelStorageIndex + 2] = b;
  58503. tempData[pixelStorageIndex + 3] = 0;
  58504. pixelIndexSlice++;
  58505. if (pixelIndexSlice % size == 0) {
  58506. pixelIndexH++;
  58507. pixelIndexSlice = 0;
  58508. if (pixelIndexH % size == 0) {
  58509. pixelIndexW++;
  58510. pixelIndexH = 0;
  58511. }
  58512. }
  58513. }
  58514. }
  58515. for (var i = 0; i < tempData.length; i++) {
  58516. var value = tempData[i];
  58517. data[i] = (value / maxColor * 255);
  58518. }
  58519. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58520. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58521. };
  58522. BABYLON.Tools.LoadFile(this.url, callback);
  58523. return this._texture;
  58524. };
  58525. /**
  58526. * Starts the loading process of the texture.
  58527. */
  58528. ColorGradingTexture.prototype.loadTexture = function () {
  58529. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58530. this.load3dlTexture();
  58531. }
  58532. };
  58533. /**
  58534. * Clones the color gradind texture.
  58535. */
  58536. ColorGradingTexture.prototype.clone = function () {
  58537. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58538. // Base texture
  58539. newTexture.level = this.level;
  58540. return newTexture;
  58541. };
  58542. /**
  58543. * Called during delayed load for textures.
  58544. */
  58545. ColorGradingTexture.prototype.delayLoad = function () {
  58546. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58547. return;
  58548. }
  58549. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58550. this._texture = this._getFromCache(this.url, true);
  58551. if (!this._texture) {
  58552. this.loadTexture();
  58553. }
  58554. };
  58555. /**
  58556. * Parses a color grading texture serialized by Babylon.
  58557. * @param parsedTexture The texture information being parsedTexture
  58558. * @param scene The scene to load the texture in
  58559. * @param rootUrl The root url of the data assets to load
  58560. * @return A color gradind texture
  58561. */
  58562. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58563. var texture = null;
  58564. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58565. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58566. texture.name = parsedTexture.name;
  58567. texture.level = parsedTexture.level;
  58568. }
  58569. return texture;
  58570. };
  58571. /**
  58572. * Serializes the LUT texture to json format.
  58573. */
  58574. ColorGradingTexture.prototype.serialize = function () {
  58575. if (!this.name) {
  58576. return null;
  58577. }
  58578. var serializationObject = {};
  58579. serializationObject.name = this.name;
  58580. serializationObject.level = this.level;
  58581. return serializationObject;
  58582. };
  58583. /**
  58584. * Empty line regex stored for GC.
  58585. */
  58586. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58587. return ColorGradingTexture;
  58588. })(BABYLON.BaseTexture);
  58589. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58590. })(BABYLON || (BABYLON = {}));
  58591. var BABYLON;
  58592. (function (BABYLON) {
  58593. var PBRMaterialDefines = (function (_super) {
  58594. __extends(PBRMaterialDefines, _super);
  58595. function PBRMaterialDefines() {
  58596. _super.call(this);
  58597. this.ALBEDO = false;
  58598. this.AMBIENT = false;
  58599. this.OPACITY = false;
  58600. this.OPACITYRGB = false;
  58601. this.REFLECTION = false;
  58602. this.EMISSIVE = false;
  58603. this.REFLECTIVITY = false;
  58604. this.BUMP = false;
  58605. this.PARALLAX = false;
  58606. this.PARALLAXOCCLUSION = false;
  58607. this.SPECULAROVERALPHA = false;
  58608. this.CLIPPLANE = false;
  58609. this.ALPHATEST = false;
  58610. this.ALPHAFROMALBEDO = false;
  58611. this.POINTSIZE = false;
  58612. this.FOG = false;
  58613. this.SPECULARTERM = false;
  58614. this.OPACITYFRESNEL = false;
  58615. this.EMISSIVEFRESNEL = false;
  58616. this.FRESNEL = false;
  58617. this.NORMAL = false;
  58618. this.UV1 = false;
  58619. this.UV2 = false;
  58620. this.VERTEXCOLOR = false;
  58621. this.VERTEXALPHA = false;
  58622. this.NUM_BONE_INFLUENCERS = 0;
  58623. this.BonesPerMesh = 0;
  58624. this.INSTANCES = false;
  58625. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58626. this.MICROSURFACEAUTOMATIC = false;
  58627. this.EMISSIVEASILLUMINATION = false;
  58628. this.LINKEMISSIVEWITHALBEDO = false;
  58629. this.LIGHTMAP = false;
  58630. this.USELIGHTMAPASSHADOWMAP = false;
  58631. this.REFLECTIONMAP_3D = false;
  58632. this.REFLECTIONMAP_SPHERICAL = false;
  58633. this.REFLECTIONMAP_PLANAR = false;
  58634. this.REFLECTIONMAP_CUBIC = false;
  58635. this.REFLECTIONMAP_PROJECTION = false;
  58636. this.REFLECTIONMAP_SKYBOX = false;
  58637. this.REFLECTIONMAP_EXPLICIT = false;
  58638. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58639. this.INVERTCUBICMAP = false;
  58640. this.LOGARITHMICDEPTH = false;
  58641. this.CAMERATONEMAP = false;
  58642. this.CAMERACONTRAST = false;
  58643. this.CAMERACOLORGRADING = false;
  58644. this.CAMERACOLORCURVES = false;
  58645. this.OVERLOADEDVALUES = false;
  58646. this.OVERLOADEDSHADOWVALUES = false;
  58647. this.USESPHERICALFROMREFLECTIONMAP = false;
  58648. this.REFRACTION = false;
  58649. this.REFRACTIONMAP_3D = false;
  58650. this.LINKREFRACTIONTOTRANSPARENCY = false;
  58651. this.REFRACTIONMAPINLINEARSPACE = false;
  58652. this.LODBASEDMICROSFURACE = false;
  58653. this.USEPHYSICALLIGHTFALLOFF = false;
  58654. this.RADIANCEOVERALPHA = false;
  58655. this.USEPMREMREFLECTION = false;
  58656. this.USEPMREMREFRACTION = false;
  58657. this.OPENGLNORMALMAP = false;
  58658. this.INVERTNORMALMAPX = false;
  58659. this.INVERTNORMALMAPY = false;
  58660. this.SHADOWFULLFLOAT = false;
  58661. this.rebuild();
  58662. }
  58663. return PBRMaterialDefines;
  58664. })(BABYLON.MaterialDefines);
  58665. /**
  58666. * The Physically based material of BJS.
  58667. *
  58668. * This offers the main features of a standard PBR material.
  58669. * For more information, please refer to the documentation :
  58670. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58671. */
  58672. var PBRMaterial = (function (_super) {
  58673. __extends(PBRMaterial, _super);
  58674. /**
  58675. * Instantiates a new PBRMaterial instance.
  58676. *
  58677. * @param name The material name
  58678. * @param scene The scene the material will be use in.
  58679. */
  58680. function PBRMaterial(name, scene) {
  58681. var _this = this;
  58682. _super.call(this, name, scene);
  58683. /**
  58684. * Intensity of the direct lights e.g. the four lights available in your scene.
  58685. * This impacts both the direct diffuse and specular highlights.
  58686. */
  58687. this.directIntensity = 1.0;
  58688. /**
  58689. * Intensity of the emissive part of the material.
  58690. * This helps controlling the emissive effect without modifying the emissive color.
  58691. */
  58692. this.emissiveIntensity = 1.0;
  58693. /**
  58694. * Intensity of the environment e.g. how much the environment will light the object
  58695. * either through harmonics for rough material or through the refelction for shiny ones.
  58696. */
  58697. this.environmentIntensity = 1.0;
  58698. /**
  58699. * This is a special control allowing the reduction of the specular highlights coming from the
  58700. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58701. */
  58702. this.specularIntensity = 1.0;
  58703. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  58704. /**
  58705. * Debug Control allowing disabling the bump map on this material.
  58706. */
  58707. this.disableBumpMap = false;
  58708. /**
  58709. * Debug Control helping enforcing or dropping the darkness of shadows.
  58710. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58711. */
  58712. this.overloadedShadowIntensity = 1.0;
  58713. /**
  58714. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58715. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58716. */
  58717. this.overloadedShadeIntensity = 1.0;
  58718. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  58719. /**
  58720. * The camera exposure used on this material.
  58721. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58722. * This corresponds to a photographic exposure.
  58723. */
  58724. this.cameraExposure = 1.0;
  58725. /**
  58726. * The camera contrast used on this material.
  58727. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58728. */
  58729. this.cameraContrast = 1.0;
  58730. /**
  58731. * Color Grading 2D Lookup Texture.
  58732. * This allows special effects like sepia, black and white to sixties rendering style.
  58733. */
  58734. this.cameraColorGradingTexture = null;
  58735. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58736. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58737. /**
  58738. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58739. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58740. * 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;
  58741. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58742. */
  58743. this.cameraColorCurves = null;
  58744. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58745. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58746. /**
  58747. * Debug Control allowing to overload the ambient color.
  58748. * This as to be use with the overloadedAmbientIntensity parameter.
  58749. */
  58750. this.overloadedAmbient = BABYLON.Color3.White();
  58751. /**
  58752. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58753. */
  58754. this.overloadedAmbientIntensity = 0.0;
  58755. /**
  58756. * Debug Control allowing to overload the albedo color.
  58757. * This as to be use with the overloadedAlbedoIntensity parameter.
  58758. */
  58759. this.overloadedAlbedo = BABYLON.Color3.White();
  58760. /**
  58761. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58762. */
  58763. this.overloadedAlbedoIntensity = 0.0;
  58764. /**
  58765. * Debug Control allowing to overload the reflectivity color.
  58766. * This as to be use with the overloadedReflectivityIntensity parameter.
  58767. */
  58768. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58769. /**
  58770. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58771. */
  58772. this.overloadedReflectivityIntensity = 0.0;
  58773. /**
  58774. * Debug Control allowing to overload the emissive color.
  58775. * This as to be use with the overloadedEmissiveIntensity parameter.
  58776. */
  58777. this.overloadedEmissive = BABYLON.Color3.White();
  58778. /**
  58779. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58780. */
  58781. this.overloadedEmissiveIntensity = 0.0;
  58782. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  58783. /**
  58784. * Debug Control allowing to overload the reflection color.
  58785. * This as to be use with the overloadedReflectionIntensity parameter.
  58786. */
  58787. this.overloadedReflection = BABYLON.Color3.White();
  58788. /**
  58789. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58790. */
  58791. this.overloadedReflectionIntensity = 0.0;
  58792. /**
  58793. * Debug Control allowing to overload the microsurface.
  58794. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58795. */
  58796. this.overloadedMicroSurface = 0.0;
  58797. /**
  58798. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58799. */
  58800. this.overloadedMicroSurfaceIntensity = 0.0;
  58801. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  58802. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58803. /**
  58804. * AKA Diffuse Color in other nomenclature.
  58805. */
  58806. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58807. /**
  58808. * AKA Specular Color in other nomenclature.
  58809. */
  58810. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58811. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58812. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58813. /**
  58814. * AKA Glossiness in other nomenclature.
  58815. */
  58816. this.microSurface = 0.9;
  58817. /**
  58818. * source material index of refraction (IOR)' / 'destination material IOR.
  58819. */
  58820. this.indexOfRefraction = 0.66;
  58821. /**
  58822. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58823. */
  58824. this.invertRefractionY = false;
  58825. /**
  58826. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58827. * Materials half opaque for instance using refraction could benefit from this control.
  58828. */
  58829. this.linkRefractionWithTransparency = false;
  58830. /**
  58831. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58832. */
  58833. this.linkEmissiveWithAlbedo = false;
  58834. this.useLightmapAsShadowmap = false;
  58835. /**
  58836. * In this mode, the emissive informtaion will always be added to the lighting once.
  58837. * A light for instance can be thought as emissive.
  58838. */
  58839. this.useEmissiveAsIllumination = false;
  58840. /**
  58841. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58842. */
  58843. this.useAlphaFromAlbedoTexture = false;
  58844. /**
  58845. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58846. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58847. */
  58848. this.useSpecularOverAlpha = true;
  58849. /**
  58850. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58851. */
  58852. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58853. /**
  58854. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58855. * The material will try to infer what glossiness each pixel should be.
  58856. */
  58857. this.useAutoMicroSurfaceFromReflectivityMap = false;
  58858. /**
  58859. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58860. * the creation of the material.
  58861. */
  58862. this.useScalarInLinearSpace = false;
  58863. /**
  58864. * BJS is using an harcoded light falloff based on a manually sets up range.
  58865. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58866. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58867. */
  58868. this.usePhysicalLightFalloff = true;
  58869. /**
  58870. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58871. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58872. */
  58873. this.useRadianceOverAlpha = true;
  58874. /**
  58875. * Allows using the bump map in parallax mode.
  58876. */
  58877. this.useParallax = false;
  58878. /**
  58879. * Allows using the bump map in parallax occlusion mode.
  58880. */
  58881. this.useParallaxOcclusion = false;
  58882. /**
  58883. * Controls the scale bias of the parallax mode.
  58884. */
  58885. this.parallaxScaleBias = 0.05;
  58886. /**
  58887. * If sets to true, disables all the lights affecting the material.
  58888. */
  58889. this.disableLighting = false;
  58890. /**
  58891. * Number of Simultaneous lights allowed on the material.
  58892. */
  58893. this.maxSimultaneousLights = 4;
  58894. /**
  58895. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58896. */
  58897. this.invertNormalMapX = false;
  58898. /**
  58899. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58900. */
  58901. this.invertNormalMapY = false;
  58902. this._renderTargets = new BABYLON.SmartArray(16);
  58903. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58904. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58905. this._tempColor = new BABYLON.Color3();
  58906. this._defines = new PBRMaterialDefines();
  58907. this._cachedDefines = new PBRMaterialDefines();
  58908. this._myScene = null;
  58909. this._myShadowGenerator = null;
  58910. this._cachedDefines.BonesPerMesh = -1;
  58911. this.getRenderTargetTextures = function () {
  58912. _this._renderTargets.reset();
  58913. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58914. _this._renderTargets.push(_this.reflectionTexture);
  58915. }
  58916. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58917. _this._renderTargets.push(_this.refractionTexture);
  58918. }
  58919. return _this._renderTargets;
  58920. };
  58921. }
  58922. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58923. get: function () {
  58924. return this._useLogarithmicDepth;
  58925. },
  58926. set: function (value) {
  58927. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58928. },
  58929. enumerable: true,
  58930. configurable: true
  58931. });
  58932. PBRMaterial.prototype.needAlphaBlending = function () {
  58933. if (this.linkRefractionWithTransparency) {
  58934. return false;
  58935. }
  58936. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58937. };
  58938. PBRMaterial.prototype.needAlphaTesting = function () {
  58939. if (this.linkRefractionWithTransparency) {
  58940. return false;
  58941. }
  58942. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58943. };
  58944. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58945. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58946. };
  58947. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58948. return this.albedoTexture;
  58949. };
  58950. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58951. if (!mesh) {
  58952. return true;
  58953. }
  58954. if (this._defines.INSTANCES !== useInstances) {
  58955. return false;
  58956. }
  58957. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58958. return true;
  58959. }
  58960. return false;
  58961. };
  58962. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58963. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58964. };
  58965. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58966. if (!useScalarInLinear) {
  58967. color.toLinearSpaceToRef(ref);
  58968. }
  58969. else {
  58970. ref.r = color.r;
  58971. ref.g = color.g;
  58972. ref.b = color.b;
  58973. }
  58974. };
  58975. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58976. var lightIndex = 0;
  58977. var depthValuesAlreadySet = false;
  58978. for (var index = 0; index < scene.lights.length; index++) {
  58979. var light = scene.lights[index];
  58980. if (!light.isEnabled()) {
  58981. continue;
  58982. }
  58983. if (!light.canAffectMesh(mesh)) {
  58984. continue;
  58985. }
  58986. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58987. // GAMMA CORRECTION.
  58988. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58989. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58990. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58991. if (defines["SPECULARTERM"]) {
  58992. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58993. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58994. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58995. }
  58996. // Shadows
  58997. if (scene.shadowsEnabled) {
  58998. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58999. }
  59000. lightIndex++;
  59001. if (lightIndex === maxSimultaneousLights)
  59002. break;
  59003. }
  59004. };
  59005. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59006. if (this.checkReadyOnlyOnce) {
  59007. if (this._wasPreviouslyReady) {
  59008. return true;
  59009. }
  59010. }
  59011. var scene = this.getScene();
  59012. if (!this.checkReadyOnEveryCall) {
  59013. if (this._renderId === scene.getRenderId()) {
  59014. if (this._checkCache(scene, mesh, useInstances)) {
  59015. return true;
  59016. }
  59017. }
  59018. }
  59019. var engine = scene.getEngine();
  59020. var needNormals = false;
  59021. var needUVs = false;
  59022. this._defines.reset();
  59023. if (scene.texturesEnabled) {
  59024. // Textures
  59025. if (scene.texturesEnabled) {
  59026. if (scene.getEngine().getCaps().textureLOD) {
  59027. this._defines.LODBASEDMICROSFURACE = true;
  59028. }
  59029. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59030. if (!this.albedoTexture.isReady()) {
  59031. return false;
  59032. }
  59033. else {
  59034. needUVs = true;
  59035. this._defines.ALBEDO = true;
  59036. }
  59037. }
  59038. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59039. if (!this.ambientTexture.isReady()) {
  59040. return false;
  59041. }
  59042. else {
  59043. needUVs = true;
  59044. this._defines.AMBIENT = true;
  59045. }
  59046. }
  59047. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59048. if (!this.opacityTexture.isReady()) {
  59049. return false;
  59050. }
  59051. else {
  59052. needUVs = true;
  59053. this._defines.OPACITY = true;
  59054. if (this.opacityTexture.getAlphaFromRGB) {
  59055. this._defines.OPACITYRGB = true;
  59056. }
  59057. }
  59058. }
  59059. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59060. if (!this.reflectionTexture.isReady()) {
  59061. return false;
  59062. }
  59063. else {
  59064. needNormals = true;
  59065. this._defines.REFLECTION = true;
  59066. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59067. this._defines.INVERTCUBICMAP = true;
  59068. }
  59069. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59070. switch (this.reflectionTexture.coordinatesMode) {
  59071. case BABYLON.Texture.CUBIC_MODE:
  59072. case BABYLON.Texture.INVCUBIC_MODE:
  59073. this._defines.REFLECTIONMAP_CUBIC = true;
  59074. break;
  59075. case BABYLON.Texture.EXPLICIT_MODE:
  59076. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59077. break;
  59078. case BABYLON.Texture.PLANAR_MODE:
  59079. this._defines.REFLECTIONMAP_PLANAR = true;
  59080. break;
  59081. case BABYLON.Texture.PROJECTION_MODE:
  59082. this._defines.REFLECTIONMAP_PROJECTION = true;
  59083. break;
  59084. case BABYLON.Texture.SKYBOX_MODE:
  59085. this._defines.REFLECTIONMAP_SKYBOX = true;
  59086. break;
  59087. case BABYLON.Texture.SPHERICAL_MODE:
  59088. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59089. break;
  59090. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59091. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59092. break;
  59093. }
  59094. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59095. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59096. needNormals = true;
  59097. if (this.reflectionTexture.isPMREM) {
  59098. this._defines.USEPMREMREFLECTION = true;
  59099. }
  59100. }
  59101. }
  59102. }
  59103. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59104. if (!this.lightmapTexture.isReady()) {
  59105. return false;
  59106. }
  59107. else {
  59108. needUVs = true;
  59109. this._defines.LIGHTMAP = true;
  59110. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59111. }
  59112. }
  59113. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59114. if (!this.emissiveTexture.isReady()) {
  59115. return false;
  59116. }
  59117. else {
  59118. needUVs = true;
  59119. this._defines.EMISSIVE = true;
  59120. }
  59121. }
  59122. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59123. if (!this.reflectivityTexture.isReady()) {
  59124. return false;
  59125. }
  59126. else {
  59127. needUVs = true;
  59128. this._defines.REFLECTIVITY = true;
  59129. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59130. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59131. }
  59132. }
  59133. }
  59134. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59135. if (!this.bumpTexture.isReady()) {
  59136. return false;
  59137. }
  59138. else {
  59139. needUVs = true;
  59140. this._defines.BUMP = true;
  59141. if (this.useParallax) {
  59142. this._defines.PARALLAX = true;
  59143. if (this.useParallaxOcclusion) {
  59144. this._defines.PARALLAXOCCLUSION = true;
  59145. }
  59146. }
  59147. if (this.invertNormalMapX) {
  59148. this._defines.INVERTNORMALMAPX = true;
  59149. }
  59150. if (this.invertNormalMapY) {
  59151. this._defines.INVERTNORMALMAPY = true;
  59152. }
  59153. }
  59154. }
  59155. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59156. if (!this.refractionTexture.isReady()) {
  59157. return false;
  59158. }
  59159. else {
  59160. needUVs = true;
  59161. this._defines.REFRACTION = true;
  59162. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59163. if (this.linkRefractionWithTransparency) {
  59164. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59165. }
  59166. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59167. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59168. if (this.refractionTexture.isPMREM) {
  59169. this._defines.USEPMREMREFRACTION = true;
  59170. }
  59171. }
  59172. }
  59173. }
  59174. if (this.cameraColorGradingTexture) {
  59175. if (!this.cameraColorGradingTexture.isReady()) {
  59176. return false;
  59177. }
  59178. else {
  59179. this._defines.CAMERACOLORGRADING = true;
  59180. }
  59181. }
  59182. }
  59183. // Effect
  59184. if (scene.clipPlane) {
  59185. this._defines.CLIPPLANE = true;
  59186. }
  59187. if (engine.getAlphaTesting()) {
  59188. this._defines.ALPHATEST = true;
  59189. }
  59190. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59191. this._defines.ALPHAFROMALBEDO = true;
  59192. }
  59193. if (this.useEmissiveAsIllumination) {
  59194. this._defines.EMISSIVEASILLUMINATION = true;
  59195. }
  59196. if (this.linkEmissiveWithAlbedo) {
  59197. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59198. }
  59199. if (this.useLogarithmicDepth) {
  59200. this._defines.LOGARITHMICDEPTH = true;
  59201. }
  59202. if (this.cameraContrast != 1) {
  59203. this._defines.CAMERACONTRAST = true;
  59204. }
  59205. if (this.cameraExposure != 1) {
  59206. this._defines.CAMERATONEMAP = true;
  59207. }
  59208. if (this.cameraColorCurves) {
  59209. this._defines.CAMERACOLORCURVES = true;
  59210. }
  59211. if (this.overloadedShadeIntensity != 1 ||
  59212. this.overloadedShadowIntensity != 1) {
  59213. this._defines.OVERLOADEDSHADOWVALUES = true;
  59214. }
  59215. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59216. this.overloadedEmissiveIntensity > 0 ||
  59217. this.overloadedReflectivityIntensity > 0 ||
  59218. this.overloadedAlbedoIntensity > 0 ||
  59219. this.overloadedAmbientIntensity > 0 ||
  59220. this.overloadedReflectionIntensity > 0) {
  59221. this._defines.OVERLOADEDVALUES = true;
  59222. }
  59223. // Point size
  59224. if (this.pointsCloud || scene.forcePointsCloud) {
  59225. this._defines.POINTSIZE = true;
  59226. }
  59227. // Fog
  59228. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59229. this._defines.FOG = true;
  59230. }
  59231. if (scene.lightsEnabled && !this.disableLighting) {
  59232. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59233. }
  59234. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59235. // Fresnel
  59236. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59237. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59238. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59239. this._defines.OPACITYFRESNEL = true;
  59240. }
  59241. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59242. this._defines.EMISSIVEFRESNEL = true;
  59243. }
  59244. needNormals = true;
  59245. this._defines.FRESNEL = true;
  59246. }
  59247. }
  59248. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  59249. this._defines.SPECULAROVERALPHA = true;
  59250. }
  59251. if (this.usePhysicalLightFalloff) {
  59252. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  59253. }
  59254. if (this.useRadianceOverAlpha) {
  59255. this._defines.RADIANCEOVERALPHA = true;
  59256. }
  59257. // Attribs
  59258. if (mesh) {
  59259. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59260. this._defines.NORMAL = true;
  59261. }
  59262. if (needUVs) {
  59263. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59264. this._defines.UV1 = true;
  59265. }
  59266. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59267. this._defines.UV2 = true;
  59268. }
  59269. }
  59270. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59271. this._defines.VERTEXCOLOR = true;
  59272. if (mesh.hasVertexAlpha) {
  59273. this._defines.VERTEXALPHA = true;
  59274. }
  59275. }
  59276. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59277. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  59278. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  59279. }
  59280. // Instances
  59281. if (useInstances) {
  59282. this._defines.INSTANCES = true;
  59283. }
  59284. }
  59285. // Get correct effect
  59286. if (!this._defines.isEqual(this._cachedDefines)) {
  59287. this._defines.cloneTo(this._cachedDefines);
  59288. scene.resetCachedMaterial();
  59289. // Fallbacks
  59290. var fallbacks = new BABYLON.EffectFallbacks();
  59291. if (this._defines.REFLECTION) {
  59292. fallbacks.addFallback(0, "REFLECTION");
  59293. }
  59294. if (this._defines.REFRACTION) {
  59295. fallbacks.addFallback(0, "REFRACTION");
  59296. }
  59297. if (this._defines.REFLECTIVITY) {
  59298. fallbacks.addFallback(0, "REFLECTIVITY");
  59299. }
  59300. if (this._defines.BUMP) {
  59301. fallbacks.addFallback(0, "BUMP");
  59302. }
  59303. if (this._defines.PARALLAX) {
  59304. fallbacks.addFallback(1, "PARALLAX");
  59305. }
  59306. if (this._defines.PARALLAXOCCLUSION) {
  59307. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  59308. }
  59309. if (this._defines.SPECULAROVERALPHA) {
  59310. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  59311. }
  59312. if (this._defines.FOG) {
  59313. fallbacks.addFallback(1, "FOG");
  59314. }
  59315. if (this._defines.POINTSIZE) {
  59316. fallbacks.addFallback(0, "POINTSIZE");
  59317. }
  59318. if (this._defines.LOGARITHMICDEPTH) {
  59319. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  59320. }
  59321. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  59322. if (this._defines.SPECULARTERM) {
  59323. fallbacks.addFallback(0, "SPECULARTERM");
  59324. }
  59325. if (this._defines.OPACITYFRESNEL) {
  59326. fallbacks.addFallback(1, "OPACITYFRESNEL");
  59327. }
  59328. if (this._defines.EMISSIVEFRESNEL) {
  59329. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  59330. }
  59331. if (this._defines.FRESNEL) {
  59332. fallbacks.addFallback(3, "FRESNEL");
  59333. }
  59334. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  59335. fallbacks.addCPUSkinningFallback(0, mesh);
  59336. }
  59337. //Attributes
  59338. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59339. if (this._defines.NORMAL) {
  59340. attribs.push(BABYLON.VertexBuffer.NormalKind);
  59341. }
  59342. if (this._defines.UV1) {
  59343. attribs.push(BABYLON.VertexBuffer.UVKind);
  59344. }
  59345. if (this._defines.UV2) {
  59346. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59347. }
  59348. if (this._defines.VERTEXCOLOR) {
  59349. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59350. }
  59351. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  59352. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  59353. // Legacy browser patch
  59354. var shaderName = "pbr";
  59355. if (!scene.getEngine().getCaps().standardDerivatives) {
  59356. shaderName = "legacypbr";
  59357. }
  59358. var join = this._defines.toString();
  59359. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  59360. "vFogInfos", "vFogColor", "pointSize",
  59361. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  59362. "mBones",
  59363. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  59364. "depthValues",
  59365. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  59366. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  59367. "logarithmicDepthConstant",
  59368. "vSphericalX", "vSphericalY", "vSphericalZ",
  59369. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  59370. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  59371. "vMicrosurfaceTextureLods",
  59372. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  59373. ];
  59374. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  59375. "cameraColorGrading2DSampler"];
  59376. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  59377. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  59378. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  59379. }
  59380. if (!this._effect.isReady()) {
  59381. return false;
  59382. }
  59383. this._renderId = scene.getRenderId();
  59384. this._wasPreviouslyReady = true;
  59385. if (mesh) {
  59386. if (!mesh._materialDefines) {
  59387. mesh._materialDefines = new PBRMaterialDefines();
  59388. }
  59389. this._defines.cloneTo(mesh._materialDefines);
  59390. }
  59391. return true;
  59392. };
  59393. PBRMaterial.prototype.unbind = function () {
  59394. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  59395. this._effect.setTexture("reflection2DSampler", null);
  59396. }
  59397. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  59398. this._effect.setTexture("refraction2DSampler", null);
  59399. }
  59400. _super.prototype.unbind.call(this);
  59401. };
  59402. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59403. this._effect.setMatrix("world", world);
  59404. };
  59405. PBRMaterial.prototype.bind = function (world, mesh) {
  59406. this._myScene = this.getScene();
  59407. // Matrices
  59408. this.bindOnlyWorldMatrix(world);
  59409. // Bones
  59410. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59411. if (this._myScene.getCachedMaterial() !== this) {
  59412. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  59413. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59414. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59415. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  59416. }
  59417. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59418. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  59419. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  59420. }
  59421. }
  59422. // Textures
  59423. if (this._myScene.texturesEnabled) {
  59424. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59425. this._effect.setTexture("albedoSampler", this.albedoTexture);
  59426. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  59427. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  59428. }
  59429. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59430. this._effect.setTexture("ambientSampler", this.ambientTexture);
  59431. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  59432. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  59433. }
  59434. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59435. this._effect.setTexture("opacitySampler", this.opacityTexture);
  59436. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  59437. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  59438. }
  59439. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59440. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  59441. if (this.reflectionTexture.isCube) {
  59442. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  59443. }
  59444. else {
  59445. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  59446. }
  59447. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  59448. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  59449. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  59450. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  59451. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  59452. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  59453. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  59454. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  59455. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  59456. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  59457. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  59458. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  59459. }
  59460. }
  59461. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59462. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  59463. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  59464. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  59465. }
  59466. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59467. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  59468. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  59469. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  59470. }
  59471. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59472. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  59473. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  59474. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  59475. }
  59476. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59477. this._effect.setTexture("bumpSampler", this.bumpTexture);
  59478. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  59479. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  59480. }
  59481. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59482. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  59483. var depth = 1.0;
  59484. if (this.refractionTexture.isCube) {
  59485. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  59486. }
  59487. else {
  59488. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  59489. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  59490. if (this.refractionTexture.depth) {
  59491. depth = this.refractionTexture.depth;
  59492. }
  59493. }
  59494. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59495. }
  59496. if ((this.reflectionTexture || this.refractionTexture)) {
  59497. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59498. }
  59499. if (this.cameraColorGradingTexture) {
  59500. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  59501. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  59502. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  59503. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  59504. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  59505. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  59506. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  59507. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  59508. 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
  59509. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  59510. 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
  59511. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  59512. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  59513. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  59514. }
  59515. }
  59516. // Clip plane
  59517. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59518. // Point size
  59519. if (this.pointsCloud) {
  59520. this._effect.setFloat("pointSize", this.pointSize);
  59521. }
  59522. // Colors
  59523. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  59524. // GAMMA CORRECTION.
  59525. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  59526. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  59527. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  59528. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  59529. // GAMMA CORRECTION.
  59530. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  59531. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  59532. // GAMMA CORRECTION.
  59533. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  59534. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  59535. }
  59536. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59537. // GAMMA CORRECTION.
  59538. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59539. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59540. // Lights
  59541. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59542. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59543. }
  59544. // View
  59545. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59546. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59547. }
  59548. // Fog
  59549. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59550. this._lightingInfos.x = this.directIntensity;
  59551. this._lightingInfos.y = this.emissiveIntensity;
  59552. this._lightingInfos.z = this.environmentIntensity;
  59553. this._lightingInfos.w = this.specularIntensity;
  59554. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59555. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59556. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59557. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59558. this._cameraInfos.x = this.cameraExposure;
  59559. this._cameraInfos.y = this.cameraContrast;
  59560. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59561. if (this.cameraColorCurves) {
  59562. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59563. }
  59564. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59565. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59566. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59567. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59568. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59569. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  59570. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  59571. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59572. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59573. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59574. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59575. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59576. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59577. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59578. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59579. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59580. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59581. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59582. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59583. // Log. depth
  59584. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59585. }
  59586. _super.prototype.bind.call(this, world, mesh);
  59587. this._myScene = null;
  59588. };
  59589. PBRMaterial.prototype.getAnimatables = function () {
  59590. var results = [];
  59591. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59592. results.push(this.albedoTexture);
  59593. }
  59594. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59595. results.push(this.ambientTexture);
  59596. }
  59597. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59598. results.push(this.opacityTexture);
  59599. }
  59600. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59601. results.push(this.reflectionTexture);
  59602. }
  59603. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59604. results.push(this.emissiveTexture);
  59605. }
  59606. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59607. results.push(this.reflectivityTexture);
  59608. }
  59609. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59610. results.push(this.bumpTexture);
  59611. }
  59612. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59613. results.push(this.lightmapTexture);
  59614. }
  59615. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59616. results.push(this.refractionTexture);
  59617. }
  59618. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59619. results.push(this.cameraColorGradingTexture);
  59620. }
  59621. return results;
  59622. };
  59623. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59624. if (forceDisposeTextures) {
  59625. if (this.albedoTexture) {
  59626. this.albedoTexture.dispose();
  59627. }
  59628. if (this.ambientTexture) {
  59629. this.ambientTexture.dispose();
  59630. }
  59631. if (this.opacityTexture) {
  59632. this.opacityTexture.dispose();
  59633. }
  59634. if (this.reflectionTexture) {
  59635. this.reflectionTexture.dispose();
  59636. }
  59637. if (this.emissiveTexture) {
  59638. this.emissiveTexture.dispose();
  59639. }
  59640. if (this.reflectivityTexture) {
  59641. this.reflectivityTexture.dispose();
  59642. }
  59643. if (this.bumpTexture) {
  59644. this.bumpTexture.dispose();
  59645. }
  59646. if (this.lightmapTexture) {
  59647. this.lightmapTexture.dispose();
  59648. }
  59649. if (this.refractionTexture) {
  59650. this.refractionTexture.dispose();
  59651. }
  59652. if (this.cameraColorGradingTexture) {
  59653. this.cameraColorGradingTexture.dispose();
  59654. }
  59655. }
  59656. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59657. };
  59658. PBRMaterial.prototype.clone = function (name) {
  59659. var _this = this;
  59660. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59661. };
  59662. PBRMaterial.prototype.serialize = function () {
  59663. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59664. serializationObject.customType = "BABYLON.PBRMaterial";
  59665. return serializationObject;
  59666. };
  59667. // Statics
  59668. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59669. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59670. };
  59671. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59672. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59673. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59674. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59675. __decorate([
  59676. BABYLON.serialize()
  59677. ], PBRMaterial.prototype, "directIntensity", void 0);
  59678. __decorate([
  59679. BABYLON.serialize()
  59680. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59681. __decorate([
  59682. BABYLON.serialize()
  59683. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59684. __decorate([
  59685. BABYLON.serialize()
  59686. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59687. __decorate([
  59688. BABYLON.serialize()
  59689. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59690. __decorate([
  59691. BABYLON.serialize()
  59692. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59693. __decorate([
  59694. BABYLON.serialize()
  59695. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59696. __decorate([
  59697. BABYLON.serialize()
  59698. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59699. __decorate([
  59700. BABYLON.serialize()
  59701. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59702. __decorate([
  59703. BABYLON.serializeAsTexture()
  59704. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59705. __decorate([
  59706. BABYLON.serializeAsColorCurves()
  59707. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59708. __decorate([
  59709. BABYLON.serializeAsColor3()
  59710. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59711. __decorate([
  59712. BABYLON.serialize()
  59713. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59714. __decorate([
  59715. BABYLON.serializeAsColor3()
  59716. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59717. __decorate([
  59718. BABYLON.serialize()
  59719. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59720. __decorate([
  59721. BABYLON.serializeAsColor3()
  59722. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59723. __decorate([
  59724. BABYLON.serialize()
  59725. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59726. __decorate([
  59727. BABYLON.serializeAsColor3()
  59728. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59729. __decorate([
  59730. BABYLON.serialize()
  59731. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59732. __decorate([
  59733. BABYLON.serializeAsColor3()
  59734. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59735. __decorate([
  59736. BABYLON.serialize()
  59737. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59738. __decorate([
  59739. BABYLON.serialize()
  59740. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59741. __decorate([
  59742. BABYLON.serialize()
  59743. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59744. __decorate([
  59745. BABYLON.serializeAsTexture()
  59746. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59747. __decorate([
  59748. BABYLON.serializeAsTexture()
  59749. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59750. __decorate([
  59751. BABYLON.serializeAsTexture()
  59752. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59753. __decorate([
  59754. BABYLON.serializeAsTexture()
  59755. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59756. __decorate([
  59757. BABYLON.serializeAsTexture()
  59758. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59759. __decorate([
  59760. BABYLON.serializeAsTexture()
  59761. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59762. __decorate([
  59763. BABYLON.serializeAsTexture()
  59764. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59765. __decorate([
  59766. BABYLON.serializeAsTexture()
  59767. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59768. __decorate([
  59769. BABYLON.serializeAsTexture()
  59770. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59771. __decorate([
  59772. BABYLON.serializeAsColor3("ambient")
  59773. ], PBRMaterial.prototype, "ambientColor", void 0);
  59774. __decorate([
  59775. BABYLON.serializeAsColor3("albedo")
  59776. ], PBRMaterial.prototype, "albedoColor", void 0);
  59777. __decorate([
  59778. BABYLON.serializeAsColor3("reflectivity")
  59779. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59780. __decorate([
  59781. BABYLON.serializeAsColor3("reflection")
  59782. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59783. __decorate([
  59784. BABYLON.serializeAsColor3("emissive")
  59785. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59786. __decorate([
  59787. BABYLON.serialize()
  59788. ], PBRMaterial.prototype, "microSurface", void 0);
  59789. __decorate([
  59790. BABYLON.serialize()
  59791. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59792. __decorate([
  59793. BABYLON.serialize()
  59794. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59795. __decorate([
  59796. BABYLON.serializeAsFresnelParameters()
  59797. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59798. __decorate([
  59799. BABYLON.serializeAsFresnelParameters()
  59800. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59801. __decorate([
  59802. BABYLON.serialize()
  59803. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59804. __decorate([
  59805. BABYLON.serialize()
  59806. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59807. __decorate([
  59808. BABYLON.serialize()
  59809. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59810. __decorate([
  59811. BABYLON.serialize()
  59812. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59813. __decorate([
  59814. BABYLON.serialize()
  59815. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59816. __decorate([
  59817. BABYLON.serialize()
  59818. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59819. __decorate([
  59820. BABYLON.serialize()
  59821. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59822. __decorate([
  59823. BABYLON.serialize()
  59824. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59825. __decorate([
  59826. BABYLON.serialize()
  59827. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59828. __decorate([
  59829. BABYLON.serialize()
  59830. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59831. __decorate([
  59832. BABYLON.serialize()
  59833. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59834. __decorate([
  59835. BABYLON.serialize()
  59836. ], PBRMaterial.prototype, "useParallax", void 0);
  59837. __decorate([
  59838. BABYLON.serialize()
  59839. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59840. __decorate([
  59841. BABYLON.serialize()
  59842. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59843. __decorate([
  59844. BABYLON.serialize()
  59845. ], PBRMaterial.prototype, "disableLighting", void 0);
  59846. __decorate([
  59847. BABYLON.serialize()
  59848. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59849. __decorate([
  59850. BABYLON.serialize()
  59851. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59852. __decorate([
  59853. BABYLON.serialize()
  59854. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59855. __decorate([
  59856. BABYLON.serialize()
  59857. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59858. return PBRMaterial;
  59859. })(BABYLON.Material);
  59860. BABYLON.PBRMaterial = PBRMaterial;
  59861. })(BABYLON || (BABYLON = {}));
  59862. var BABYLON;
  59863. (function (BABYLON) {
  59864. var DebugLayer = (function () {
  59865. function DebugLayer(scene) {
  59866. var _this = this;
  59867. this._transformationMatrix = BABYLON.Matrix.Identity();
  59868. this._enabled = false;
  59869. this._labelsEnabled = false;
  59870. this._displayStatistics = true;
  59871. this._displayTree = false;
  59872. this._displayLogs = false;
  59873. this._skeletonViewers = new Array();
  59874. this._identityMatrix = BABYLON.Matrix.Identity();
  59875. this.axisRatio = 0.02;
  59876. this.accentColor = "orange";
  59877. this._scene = scene;
  59878. this._syncPositions = function () {
  59879. var engine = _this._scene.getEngine();
  59880. var canvasRect = engine.getRenderingCanvasClientRect();
  59881. if (_this._showUI) {
  59882. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  59883. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  59884. _this._statsDiv.style.width = "400px";
  59885. _this._statsDiv.style.height = "auto";
  59886. _this._statsSubsetDiv.style.maxHeight = "240px";
  59887. _this._optionsDiv.style.left = "0px";
  59888. _this._optionsDiv.style.top = "10px";
  59889. _this._optionsDiv.style.width = "200px";
  59890. _this._optionsDiv.style.height = "auto";
  59891. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  59892. _this._logDiv.style.left = "0px";
  59893. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  59894. _this._logDiv.style.width = "600px";
  59895. _this._logDiv.style.height = "160px";
  59896. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  59897. _this._treeDiv.style.top = "10px";
  59898. _this._treeDiv.style.width = "300px";
  59899. _this._treeDiv.style.height = "auto";
  59900. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  59901. }
  59902. _this._globalDiv.style.left = canvasRect.left + "px";
  59903. _this._globalDiv.style.top = canvasRect.top + "px";
  59904. _this._drawingCanvas.style.left = "0px";
  59905. _this._drawingCanvas.style.top = "0px";
  59906. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  59907. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  59908. var devicePixelRatio = window.devicePixelRatio || 1;
  59909. var context = _this._drawingContext;
  59910. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  59911. context.mozBackingStorePixelRatio ||
  59912. context.msBackingStorePixelRatio ||
  59913. context.oBackingStorePixelRatio ||
  59914. context.backingStorePixelRatio || 1;
  59915. _this._ratio = devicePixelRatio / backingStoreRatio;
  59916. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  59917. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  59918. };
  59919. this._onCanvasClick = function (evt) {
  59920. _this._clickPosition = {
  59921. x: evt.clientX * _this._ratio,
  59922. y: evt.clientY * _this._ratio
  59923. };
  59924. };
  59925. this._syncUI = function () {
  59926. if (_this._showUI) {
  59927. if (_this._displayStatistics) {
  59928. _this._displayStats();
  59929. _this._statsDiv.style.display = "";
  59930. }
  59931. else {
  59932. _this._statsDiv.style.display = "none";
  59933. }
  59934. if (_this._displayLogs) {
  59935. _this._logDiv.style.display = "";
  59936. }
  59937. else {
  59938. _this._logDiv.style.display = "none";
  59939. }
  59940. if (_this._displayTree) {
  59941. _this._treeDiv.style.display = "";
  59942. if (_this._needToRefreshMeshesTree) {
  59943. _this._needToRefreshMeshesTree = false;
  59944. _this._refreshMeshesTreeContent();
  59945. }
  59946. }
  59947. else {
  59948. _this._treeDiv.style.display = "none";
  59949. }
  59950. }
  59951. };
  59952. this._syncData = function () {
  59953. if (_this._labelsEnabled || !_this._showUI) {
  59954. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  59955. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  59956. var engine = _this._scene.getEngine();
  59957. var viewport = _this._camera.viewport;
  59958. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59959. // Meshes
  59960. var meshes = _this._camera.getActiveMeshes();
  59961. var index;
  59962. var projectedPosition;
  59963. for (index = 0; index < meshes.length; index++) {
  59964. var mesh = meshes.data[index];
  59965. var position = mesh.getBoundingInfo().boundingSphere.center;
  59966. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  59967. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  59968. _this._renderAxis(projectedPosition, mesh, globalViewport);
  59969. }
  59970. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  59971. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  59972. }
  59973. }
  59974. // Cameras
  59975. var cameras = _this._scene.cameras;
  59976. for (index = 0; index < cameras.length; index++) {
  59977. var camera = cameras[index];
  59978. if (camera === _this._camera) {
  59979. continue;
  59980. }
  59981. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  59982. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  59983. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  59984. _this._camera.detachControl(engine.getRenderingCanvas());
  59985. _this._camera = camera;
  59986. _this._camera.attachControl(engine.getRenderingCanvas());
  59987. }, function () { return "purple"; });
  59988. }
  59989. }
  59990. // Lights
  59991. var lights = _this._scene.lights;
  59992. for (index = 0; index < lights.length; index++) {
  59993. var light = lights[index];
  59994. if (light.position) {
  59995. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  59996. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  59997. _this._renderLabel(light.name, projectedPosition, -20, function () {
  59998. light.setEnabled(!light.isEnabled());
  59999. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  60000. }
  60001. }
  60002. }
  60003. }
  60004. _this._clickPosition = undefined;
  60005. };
  60006. }
  60007. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  60008. while (this._treeSubsetDiv.hasChildNodes()) {
  60009. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  60010. }
  60011. // Add meshes
  60012. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  60013. sortedArray.sort(function (a, b) {
  60014. if (a.name === b.name) {
  60015. return 0;
  60016. }
  60017. return (a.name > b.name) ? 1 : -1;
  60018. });
  60019. for (var index = 0; index < sortedArray.length; index++) {
  60020. var mesh = sortedArray[index];
  60021. if (!mesh.isEnabled()) {
  60022. continue;
  60023. }
  60024. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  60025. m.isVisible = element.checked;
  60026. }, mesh);
  60027. }
  60028. };
  60029. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  60030. this._drawingContext.beginPath();
  60031. this._drawingContext.moveTo(zero.x, zero.y);
  60032. this._drawingContext.lineTo(unit.x, unit.y);
  60033. this._drawingContext.strokeStyle = color;
  60034. this._drawingContext.lineWidth = 4;
  60035. this._drawingContext.stroke();
  60036. this._drawingContext.font = "normal 14px Segoe UI";
  60037. this._drawingContext.fillStyle = color;
  60038. this._drawingContext.fillText(label, unitText.x, unitText.y);
  60039. };
  60040. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  60041. var position = mesh.getBoundingInfo().boundingSphere.center;
  60042. var worldMatrix = mesh.getWorldMatrix();
  60043. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  60044. var unit = (unprojectedVector.subtract(position)).length();
  60045. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60046. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60047. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  60048. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60049. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60050. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  60051. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  60052. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  60053. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  60054. };
  60055. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  60056. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  60057. this._drawingContext.font = "normal 12px Segoe UI";
  60058. var textMetrics = this._drawingContext.measureText(text);
  60059. var centerX = projectedPosition.x - textMetrics.width / 2;
  60060. var centerY = projectedPosition.y;
  60061. var clientRect = this._drawingCanvas.getBoundingClientRect();
  60062. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  60063. onClick();
  60064. }
  60065. this._drawingContext.beginPath();
  60066. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  60067. this._drawingContext.fillStyle = getFillStyle();
  60068. this._drawingContext.globalAlpha = 0.5;
  60069. this._drawingContext.fill();
  60070. this._drawingContext.globalAlpha = 1.0;
  60071. this._drawingContext.strokeStyle = '#FFFFFF';
  60072. this._drawingContext.lineWidth = 1;
  60073. this._drawingContext.stroke();
  60074. this._drawingContext.fillStyle = "#FFFFFF";
  60075. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  60076. this._drawingContext.beginPath();
  60077. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  60078. this._drawingContext.fill();
  60079. }
  60080. };
  60081. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  60082. if (!this._clickPosition) {
  60083. return false;
  60084. }
  60085. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  60086. return false;
  60087. }
  60088. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  60089. return false;
  60090. }
  60091. return true;
  60092. };
  60093. DebugLayer.prototype.isVisible = function () {
  60094. return this._enabled;
  60095. };
  60096. DebugLayer.prototype.hide = function () {
  60097. if (!this._enabled) {
  60098. return;
  60099. }
  60100. this._enabled = false;
  60101. var engine = this._scene.getEngine();
  60102. this._scene.unregisterBeforeRender(this._syncData);
  60103. this._scene.unregisterAfterRender(this._syncUI);
  60104. this._rootElement.removeChild(this._globalDiv);
  60105. this._scene.forceShowBoundingBoxes = false;
  60106. this._scene.forceWireframe = false;
  60107. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  60108. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  60109. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  60110. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  60111. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  60112. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  60113. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  60114. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  60115. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  60116. this._scene.shadowsEnabled = true;
  60117. this._scene.particlesEnabled = true;
  60118. this._scene.postProcessesEnabled = true;
  60119. this._scene.collisionsEnabled = true;
  60120. this._scene.lightsEnabled = true;
  60121. this._scene.texturesEnabled = true;
  60122. this._scene.lensFlaresEnabled = true;
  60123. this._scene.proceduralTexturesEnabled = true;
  60124. this._scene.renderTargetsEnabled = true;
  60125. this._scene.probesEnabled = true;
  60126. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  60127. this._clearSkeletonViewers();
  60128. };
  60129. DebugLayer.prototype._clearSkeletonViewers = function () {
  60130. for (var index = 0; index < this._skeletonViewers.length; index++) {
  60131. this._skeletonViewers[index].dispose();
  60132. }
  60133. this._skeletonViewers = [];
  60134. };
  60135. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  60136. if (showUI === void 0) { showUI = true; }
  60137. if (camera === void 0) { camera = null; }
  60138. if (rootElement === void 0) { rootElement = null; }
  60139. if (this._enabled) {
  60140. return;
  60141. }
  60142. this._enabled = true;
  60143. if (camera) {
  60144. this._camera = camera;
  60145. }
  60146. else {
  60147. this._camera = this._scene.activeCamera;
  60148. }
  60149. this._showUI = showUI;
  60150. var engine = this._scene.getEngine();
  60151. this._globalDiv = document.createElement("div");
  60152. this._rootElement = rootElement || document.body;
  60153. this._rootElement.appendChild(this._globalDiv);
  60154. this._generateDOMelements();
  60155. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  60156. this._syncPositions();
  60157. this._scene.registerBeforeRender(this._syncData);
  60158. this._scene.registerAfterRender(this._syncUI);
  60159. };
  60160. DebugLayer.prototype._clearLabels = function () {
  60161. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  60162. for (var index = 0; index < this._scene.meshes.length; index++) {
  60163. var mesh = this._scene.meshes[index];
  60164. mesh.renderOverlay = false;
  60165. }
  60166. };
  60167. DebugLayer.prototype._generateheader = function (root, text) {
  60168. var header = document.createElement("div");
  60169. header.innerHTML = text + "&nbsp;";
  60170. header.style.textAlign = "right";
  60171. header.style.width = "100%";
  60172. header.style.color = "white";
  60173. header.style.backgroundColor = "Black";
  60174. header.style.padding = "5px 5px 4px 0px";
  60175. header.style.marginLeft = "-5px";
  60176. header.style.fontWeight = "bold";
  60177. root.appendChild(header);
  60178. };
  60179. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  60180. var label = document.createElement("label");
  60181. label.style.display = "inline";
  60182. label.innerHTML = title;
  60183. label.style.color = color;
  60184. root.appendChild(label);
  60185. root.appendChild(document.createElement("br"));
  60186. };
  60187. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  60188. if (tag === void 0) { tag = null; }
  60189. var label = document.createElement("label");
  60190. label.style.display = "inline";
  60191. var boundingBoxesCheckbox = document.createElement("input");
  60192. boundingBoxesCheckbox.type = "checkbox";
  60193. boundingBoxesCheckbox.checked = initialState;
  60194. boundingBoxesCheckbox.style.display = "inline";
  60195. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  60196. boundingBoxesCheckbox.style.verticalAlign = "sub";
  60197. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  60198. task(evt.target, tag);
  60199. });
  60200. label.appendChild(boundingBoxesCheckbox);
  60201. var container = document.createElement("span");
  60202. var leftPart = document.createElement("span");
  60203. var rightPart = document.createElement("span");
  60204. rightPart.style.cssFloat = "right";
  60205. leftPart.innerHTML = leftTitle;
  60206. rightPart.innerHTML = rightTitle;
  60207. rightPart.style.fontSize = "12px";
  60208. rightPart.style.maxWidth = "200px";
  60209. container.appendChild(leftPart);
  60210. container.appendChild(rightPart);
  60211. label.appendChild(container);
  60212. root.appendChild(label);
  60213. root.appendChild(document.createElement("br"));
  60214. };
  60215. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  60216. if (tag === void 0) { tag = null; }
  60217. var label = document.createElement("label");
  60218. label.style.display = "inline";
  60219. var checkBox = document.createElement("input");
  60220. checkBox.type = "checkbox";
  60221. checkBox.checked = initialState;
  60222. checkBox.style.display = "inline";
  60223. checkBox.style.margin = "0px 5px 0px 0px";
  60224. checkBox.style.verticalAlign = "sub";
  60225. checkBox.addEventListener("change", function (evt) {
  60226. task(evt.target, tag);
  60227. });
  60228. label.appendChild(checkBox);
  60229. label.appendChild(document.createTextNode(title));
  60230. root.appendChild(label);
  60231. root.appendChild(document.createElement("br"));
  60232. };
  60233. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  60234. if (tag === void 0) { tag = null; }
  60235. var button = document.createElement("button");
  60236. button.innerHTML = title;
  60237. button.style.height = "24px";
  60238. button.style.width = "150px";
  60239. button.style.marginBottom = "5px";
  60240. button.style.color = "#444444";
  60241. button.style.border = "1px solid white";
  60242. button.className = "debugLayerButton";
  60243. button.addEventListener("click", function (evt) {
  60244. task(evt.target, tag);
  60245. });
  60246. root.appendChild(button);
  60247. root.appendChild(document.createElement("br"));
  60248. };
  60249. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  60250. if (tag === void 0) { tag = null; }
  60251. var label = document.createElement("label");
  60252. label.style.display = "inline";
  60253. var boundingBoxesRadio = document.createElement("input");
  60254. boundingBoxesRadio.type = "radio";
  60255. boundingBoxesRadio.name = name;
  60256. boundingBoxesRadio.checked = initialState;
  60257. boundingBoxesRadio.style.display = "inline";
  60258. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  60259. boundingBoxesRadio.style.verticalAlign = "sub";
  60260. boundingBoxesRadio.addEventListener("change", function (evt) {
  60261. task(evt.target, tag);
  60262. });
  60263. label.appendChild(boundingBoxesRadio);
  60264. label.appendChild(document.createTextNode(title));
  60265. root.appendChild(label);
  60266. root.appendChild(document.createElement("br"));
  60267. };
  60268. DebugLayer.prototype._generateDOMelements = function () {
  60269. var _this = this;
  60270. this._globalDiv.id = "DebugLayer";
  60271. this._globalDiv.style.position = "absolute";
  60272. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  60273. this._globalDiv.style.fontSize = "14px";
  60274. this._globalDiv.style.color = "white";
  60275. // Drawing canvas
  60276. this._drawingCanvas = document.createElement("canvas");
  60277. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  60278. this._drawingCanvas.style.position = "absolute";
  60279. this._drawingCanvas.style.pointerEvents = "none";
  60280. this._drawingCanvas.style.backgroundColor = "transparent";
  60281. this._drawingContext = this._drawingCanvas.getContext("2d");
  60282. this._globalDiv.appendChild(this._drawingCanvas);
  60283. if (this._showUI) {
  60284. var background = "rgba(128, 128, 128, 0.4)";
  60285. var border = "rgb(180, 180, 180) solid 1px";
  60286. // Stats
  60287. this._statsDiv = document.createElement("div");
  60288. this._statsDiv.id = "DebugLayerStats";
  60289. this._statsDiv.style.border = border;
  60290. this._statsDiv.style.position = "absolute";
  60291. this._statsDiv.style.background = background;
  60292. this._statsDiv.style.padding = "0px 0px 0px 5px";
  60293. this._generateheader(this._statsDiv, "STATISTICS");
  60294. this._statsSubsetDiv = document.createElement("div");
  60295. this._statsSubsetDiv.style.paddingTop = "5px";
  60296. this._statsSubsetDiv.style.paddingBottom = "5px";
  60297. this._statsSubsetDiv.style.overflowY = "auto";
  60298. this._statsDiv.appendChild(this._statsSubsetDiv);
  60299. // Tree
  60300. this._treeDiv = document.createElement("div");
  60301. this._treeDiv.id = "DebugLayerTree";
  60302. this._treeDiv.style.border = border;
  60303. this._treeDiv.style.position = "absolute";
  60304. this._treeDiv.style.background = background;
  60305. this._treeDiv.style.padding = "0px 0px 0px 5px";
  60306. this._treeDiv.style.display = "none";
  60307. this._generateheader(this._treeDiv, "MESHES TREE");
  60308. this._treeSubsetDiv = document.createElement("div");
  60309. this._treeSubsetDiv.style.paddingTop = "5px";
  60310. this._treeSubsetDiv.style.paddingRight = "5px";
  60311. this._treeSubsetDiv.style.overflowY = "auto";
  60312. this._treeSubsetDiv.style.maxHeight = "300px";
  60313. this._treeDiv.appendChild(this._treeSubsetDiv);
  60314. this._needToRefreshMeshesTree = true;
  60315. // Logs
  60316. this._logDiv = document.createElement("div");
  60317. this._logDiv.style.border = border;
  60318. this._logDiv.id = "DebugLayerLogs";
  60319. this._logDiv.style.position = "absolute";
  60320. this._logDiv.style.background = background;
  60321. this._logDiv.style.padding = "0px 0px 0px 5px";
  60322. this._logDiv.style.display = "none";
  60323. this._generateheader(this._logDiv, "LOGS");
  60324. this._logSubsetDiv = document.createElement("div");
  60325. this._logSubsetDiv.style.height = "127px";
  60326. this._logSubsetDiv.style.paddingTop = "5px";
  60327. this._logSubsetDiv.style.overflowY = "auto";
  60328. this._logSubsetDiv.style.fontSize = "12px";
  60329. this._logSubsetDiv.style.fontFamily = "consolas";
  60330. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  60331. this._logDiv.appendChild(this._logSubsetDiv);
  60332. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  60333. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  60334. };
  60335. // Options
  60336. this._optionsDiv = document.createElement("div");
  60337. this._optionsDiv.id = "DebugLayerOptions";
  60338. this._optionsDiv.style.border = border;
  60339. this._optionsDiv.style.position = "absolute";
  60340. this._optionsDiv.style.background = background;
  60341. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  60342. this._optionsDiv.style.overflowY = "auto";
  60343. this._generateheader(this._optionsDiv, "OPTIONS");
  60344. this._optionsSubsetDiv = document.createElement("div");
  60345. this._optionsSubsetDiv.style.paddingTop = "5px";
  60346. this._optionsSubsetDiv.style.paddingBottom = "5px";
  60347. this._optionsSubsetDiv.style.overflowY = "auto";
  60348. this._optionsSubsetDiv.style.maxHeight = "200px";
  60349. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  60350. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  60351. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  60352. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  60353. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  60354. _this._displayTree = element.checked;
  60355. _this._needToRefreshMeshesTree = true;
  60356. });
  60357. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60358. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  60359. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  60360. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  60361. _this._labelsEnabled = element.checked;
  60362. if (!_this._labelsEnabled) {
  60363. _this._clearLabels();
  60364. }
  60365. });
  60366. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  60367. if (element.checked) {
  60368. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  60369. }
  60370. else {
  60371. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  60372. }
  60373. });
  60374. ;
  60375. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60376. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  60377. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  60378. if (element.checked) {
  60379. _this._scene.forceWireframe = false;
  60380. _this._scene.forcePointsCloud = false;
  60381. }
  60382. });
  60383. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  60384. if (element.checked) {
  60385. _this._scene.forceWireframe = true;
  60386. _this._scene.forcePointsCloud = false;
  60387. }
  60388. });
  60389. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  60390. if (element.checked) {
  60391. _this._scene.forceWireframe = false;
  60392. _this._scene.forcePointsCloud = true;
  60393. }
  60394. });
  60395. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60396. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  60397. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  60398. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  60399. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  60400. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  60401. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  60402. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  60403. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  60404. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  60405. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  60406. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  60407. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60408. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  60409. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  60410. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  60411. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  60412. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  60413. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  60414. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  60415. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  60416. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  60417. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  60418. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  60419. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  60420. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  60421. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  60422. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  60423. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60424. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60425. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  60426. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  60427. if (element.checked) {
  60428. _this._scene.headphone = true;
  60429. }
  60430. });
  60431. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  60432. if (element.checked) {
  60433. _this._scene.headphone = false;
  60434. }
  60435. });
  60436. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  60437. _this._scene.audioEnabled = !element.checked;
  60438. });
  60439. }
  60440. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60441. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  60442. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  60443. if (!element.checked) {
  60444. _this._clearSkeletonViewers();
  60445. return;
  60446. }
  60447. for (var index = 0; index < _this._scene.meshes.length; index++) {
  60448. var mesh = _this._scene.meshes[index];
  60449. if (mesh.skeleton) {
  60450. var found = false;
  60451. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  60452. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  60453. found = true;
  60454. break;
  60455. }
  60456. }
  60457. if (found) {
  60458. continue;
  60459. }
  60460. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  60461. viewer.isEnabled = true;
  60462. _this._skeletonViewers.push(viewer);
  60463. }
  60464. }
  60465. });
  60466. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60467. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  60468. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  60469. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  60470. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  60471. if (_this._camera) {
  60472. console.log(_this._camera);
  60473. }
  60474. else {
  60475. console.warn("No camera defined, or debug layer created before camera creation!");
  60476. }
  60477. });
  60478. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60479. this._globalDiv.appendChild(this._statsDiv);
  60480. this._globalDiv.appendChild(this._logDiv);
  60481. this._globalDiv.appendChild(this._optionsDiv);
  60482. this._globalDiv.appendChild(this._treeDiv);
  60483. }
  60484. };
  60485. DebugLayer.prototype._displayStats = function () {
  60486. var scene = this._scene;
  60487. var engine = scene.getEngine();
  60488. var glInfo = engine.getGlInfo();
  60489. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  60490. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60491. + "<b>Count</b><br>"
  60492. + "Total meshes: " + scene.meshes.length + "<br>"
  60493. + "Total lights: " + scene.lights.length + "<br>"
  60494. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  60495. + "Total materials: " + scene.materials.length + "<br>"
  60496. + "Total textures: " + scene.textures.length + "<br>"
  60497. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  60498. + "Active indices: " + scene.getActiveIndices() + "<br>"
  60499. + "Active bones: " + scene.getActiveBones() + "<br>"
  60500. + "Active particles: " + scene.getActiveParticles() + "<br>"
  60501. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  60502. + "<b>Duration</b><br>"
  60503. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  60504. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  60505. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  60506. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  60507. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  60508. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  60509. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  60510. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  60511. + "</div>"
  60512. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60513. + "<b>Extensions</b><br>"
  60514. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  60515. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  60516. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  60517. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  60518. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  60519. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  60520. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  60521. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  60522. + "</div><br>"
  60523. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60524. + "<b>Caps.</b><br>"
  60525. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  60526. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  60527. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  60528. + "<b>Info</b><br>"
  60529. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  60530. + glInfo.version + "<br>"
  60531. + "</div><br>"
  60532. + glInfo.renderer + "<br>";
  60533. if (this.customStatsFunction) {
  60534. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  60535. }
  60536. };
  60537. return DebugLayer;
  60538. })();
  60539. BABYLON.DebugLayer = DebugLayer;
  60540. })(BABYLON || (BABYLON = {}));
  60541. 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>[0..maxSimultaneousLights]\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>[0..maxSimultaneousLights]\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 float opacity;\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\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*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>[0..maxSimultaneousLights]\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>[0..maxSimultaneousLights]\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 float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\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\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\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\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\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 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\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>[0..maxSimultaneousLights]\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>[0..maxSimultaneousLights]\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 float opacity;\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\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*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":"#ifndef FULLFLOAT\nvec4 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}\n#endif\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;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\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;\nvarying float vOpacity;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.05) {\ndiscard;\n}\ncolor.a*=vOpacity;\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 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\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);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\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 float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\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}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \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}"};
  60542. 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,vec3 reflectance90)\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,reflectance90);\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}\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,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=computeDistanceLightFalloff(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,reflectance90);\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,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\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,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,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,reflectance90);\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,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,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,specularEnvironmentR90,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\n#ifndef SHADOWFULLFLOAT\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#endif\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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\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}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\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#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\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","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\n#ifndef SHADOWFULLFLOAT\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#endif\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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  60543. 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(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(0>r)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&s>c?(t.root=c,t.found=!0,t):h>0&&s>h?(t.root=h,t.found=!0,t):t}}(),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 f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,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(m,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(m,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(m=g*-f+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(m,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),m=g*-f+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(m,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),m=g*-f+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(m,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,r){void 0===r&&(r=1.401298e-45);var n=t-i;return n>=-r&&r>=n},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,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.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},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.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},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.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},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.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},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.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},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.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},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}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,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=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];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=0>o?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&2*o*e>s+h},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.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},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.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},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.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},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=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],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.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(),r.CrossToRef(h,R,g),g.normalize(),r.Dot(a,g)<0&&(v=1),T=r.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,r.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(),r.CrossToRef(_,R,b),b.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(R,g)<0&&(v=1),T=r.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,r.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,R,g),g.normalize(),r.Dot(g,m)<0&&(v=1),T=r.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.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)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.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},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.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},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.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},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.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},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;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.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},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 r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}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,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,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 r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-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,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),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=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),-.499>u&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=r,t.z=n,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=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*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+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 r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},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,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.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],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=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],e=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]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},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 r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;16>r;r++)i.m[r]=this.m[r]+t.m[r];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],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=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=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+r*_+n*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,q=s*c-a*m,H=s*y-h*m,N=e*c-a*u,V=e*y-h*u,D=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*T)*F,t.m[13]=(i*v-r*g+n*T)*F,t.m[2]=(r*A-n*L+o*C)*F,t.m[6]=-(i*A-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*q+o*H)*F,t.m[7]=(i*I-n*N+o*V)*F,t.m[11]=-(i*q-r*N+o*D)*F,t.m[15]=(i*H-r*V+n*D)*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 e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},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 r=0;16>r;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=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],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];\nreturn i[r]=n*v+o*R+e*F+s*P,i[r+1]=n*d+o*_+e*A+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*T+o*b+e*C+s*I,i[r+4]=h*v+a*R+u*F+m*P,i[r+5]=h*d+a*_+u*A+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*T+a*b+u*C+m*I,i[r+8]=y*v+c*R+p*F+f*P,i[r+9]=y*d+c*_+p*A+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*T+c*b+p*C+f*I,i[r+12]=l*v+x*R+z*F+w*P,i[r+13]=l*d+x*_+z*A+w*Z,i[r+14]=l*g+x*M+z*L+w*S,i[r+15]=l*T+x*b+z*C+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(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=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(r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=t.FromValues(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,n),!0},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;16>n;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;16>o;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=r,x.m[3]=n,x.m[4]=o,x.m[5]=e,x.m[6]=s,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 s(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 r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,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,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),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 r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,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 r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,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 r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,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,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.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,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-n/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.GetFinalMatrix=function(i,r,n,o,e,s){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,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).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 r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}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 r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.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,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,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 r=e.Dot(this.normal,t);return i>=r},t.prototype.signedDistanceTo=function(t){return e.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,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;6>n;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},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 e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+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,r){var n=r.subtract(i),o=Math.atan2(n.y,n.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,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/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 r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>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],r=this._points[0];t+=r.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(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&u>=i){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){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 n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.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 r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),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]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s;if(void 0===o||null===o){var h;i.WithinEpsilon(n.y,1,t.Epsilon)?i.WithinEpsilon(n.x,1,t.Epsilon)?i.WithinEpsilon(n.z,1,t.Epsilon)||(h=new e(0,0,1)):h=new e(1,0,0):h=new e(0,-1,0),s=e.Cross(n,h)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();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,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,r,n,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 r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);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=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(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 r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.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,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}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=[r.Black(),r.Black(),r.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.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={}));";
  60544. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60545. module.exports = BABYLON;
  60546. };